Repository navigation
Commit 82a3ed2
fix(driver-sql): MySQL autonumber no longer issues duplicate numbers when the first rows of an object are written concurrently (#31709)
<!-- claude-projects-attribution: {"github_login":"os-steve"} -->
_Requested by **Steve** · [project
thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9Q2bn6zMspNSj2AacjJDxnw)_
Fixes #31608
Clause-②: no
Metadata-protocol: none
## 维护者速读
- 改了什么:MySQL
上新对象的自动编号计数器改为"先幂等建行、再加锁读",并发首批写入不再出现重复编号;驱动自有事务遇整事务回滚(死锁)时整段重试,调用方事务内则原样报错不重试。
- 为什么改:旧顺序在 InnoDB 下先对不存在的行加锁读,拿到的是共享的间隙锁,并发 INSERT 必然死锁;MySQL
回滚整个事务后驱动继续在自动提交下执行,读到同一个值写回,造成重复编号(实测每轮 8~10 个重复)。
- 风险与回滚:只动 `sql-driver-autonumber.ts` 一条取号路径;Postgres/SQLite
号码不变,但每次取号多一次不加锁的主键读。回滚即 revert 本 PR。
- 先看:`packages/drivers/driver-sql/src/sql-driver-autonumber.ts` 的
`getNextSequenceValue`(种子 INSERT 与锁读顺序、`rollsBackWholeTransaction`);然后
`sql-driver-autonumber-cold-race-mysql.test.ts`。
- 两分钟验证:起一个 `mysql:8.0` 容器后运行
`OS_TEST_MYSQL_URL=mysql://root:PW@127.0.0.1:PORT/conformance pnpm
--filter @objectstack/driver-sql exec vitest run
src/sql-driver-autonumber-cold-race-mysql.test.ts`,应见 8 个测试全过(在 main 上 6
个失败)。
- 需要你做的:无,席位落地。
## What changes
**Root cause, measured on a live `mysql:8.0` cell (8.0.46, InnoDB,
REPEATABLE READ):**
1. **The statement that deadlocks is the cold-seed INSERT.** The seed
did `SELECT … FOR UPDATE` on the missing counter row, then `INSERT`. A
locking read of a missing key takes a next-key lock on the gap; `SHOW
ENGINE INNODB STATUS` shows both transactions holding `lock_mode X` on
the supremum record of `_objectstack_sequences`'s PRIMARY index and each
waiting on `lock_mode X insert intention` for its INSERT of the same
`key_hash`. Gap locks are compatible with each other, so every cold
writer holds one and every INSERT waits on the others.
2. **InnoDB rolls back the WHOLE transaction, not to the savepoint
(confirmed).** A raw probe: after the victim's INSERT fails
`ER_LOCK_DEADLOCK`, `ROLLBACK TO SAVEPOINT` answers
`ER_SP_DOES_NOT_EXIST` (errno 1305), and a write made on the same
session afterwards is visible to another connection before any COMMIT,
so the session is in autocommit. knex's MySQL client swallows that 1305
(it logs "Transaction was implicitly committed") and hands back the
deadlock.
3. **How the duplicate arises.** `attemptWithoutPoisoning` reported the
failed INSERT, so the code took its recovery path: `SELECT … FOR UPDATE`
then `UPDATE last_value = last_value + 1`. Both now ran in autocommit,
so the lock ended with its own statement, and every victim read the
winner's `last_value` and wrote the same value back: a lost update. On
two drivers the counter ended at 2 with nine creates holding `TK-0002`.
The card's guess ("a deadlock rolls back past the savepoint during the
cold seed") is right; the duplicate comes from the recovery statements
running after it in autocommit.
**The fix, in the one cold-seed path, for every dialect:**
- A plain read decides whether the counter row exists. A missing row is
seeded by an idempotent INSERT, which a concurrent seeder never turns
into an error and which no gap lock precedes. Only then is the row
locked, by which point it exists, so the cold path is the warm path.
- Postgres and SQLite: `ON CONFLICT DO NOTHING`, with no conflict
target, so it matches whichever unique key the table has (a target would
raise `42P10` against the interim four-column key an incomplete key-hash
migration leaves, the reason `attemptWithoutPoisoning` gives).
- MySQL: a no-op `ON DUPLICATE KEY UPDATE`, not `INSERT IGNORE`.
Measured: with `INSERT IGNORE` the losers take a SHARED lock on the
duplicate and deadlock upgrading it for the `FOR UPDATE` (8 to 14 server
deadlocks a 16-writer burst, and 14 of 16 creates refused when each runs
in its own caller transaction). `ON DUPLICATE KEY UPDATE` takes the
exclusive lock at once: 0 deadlocks. It also leaves other errors loud
where `IGNORE` turns them into warnings.
- `rollsBackWholeTransaction` names the class: MySQL `ER_LOCK_DEADLOCK`
(errno 1213). Postgres `40P01` and lock timeouts abort only the
savepoint and keep their existing handling.
- When the locked read fails with it, there is no fallback read: the
fallback would be the autocommit lost update above.
- When the driver owns the transaction, the whole issue is retried from
the start, up to 5 attempts, then the server's error surfaces.
- Inside a caller's transaction it is never retried: the caller gets the
server's `ER_LOCK_DEADLOCK`, because that transaction and the caller's
earlier writes in it are already gone. Before, the issue went on and the
create succeeded outside the caller's rolled-back transaction.
- `getNextSequenceValue`'s host gains the `isMysql` getter (one line in
`sql-driver.ts`, the host literal) to choose the MySQL seed spelling. No
export moves; `index.ts` re-exports nothing from the module.
**Unique index (seat ruling 3), measured:** an autonumber field defined
through the spec already gets the tenant-composite unique index on every
dialect (#13894 / #14904); nothing is added here. See Open questions for
the reading.
## Tests
New file
`packages/drivers/driver-sql/src/sql-driver-autonumber-cold-race-mysql.test.ts`,
beside the #8269 Postgres twin (which is untouched):
- Live MySQL cell (`declareDialectCell(MYSQL_CELL, …)`; CI runs it in
`Temporal Conformance (live PG + MySQL)`, a named skip elsewhere), 3
cold rounds each of 16 writers:
- one driver; two drivers (two pools); every writer in its own caller
transaction. Each asserts no rejected create, codes exactly
`TK-0001`..`TK-0016`, counter `16`.
- a real deadlock built deterministically (the caller holds a lock the
other transaction wants while the other holds the counter row; the other
is made heavier so InnoDB picks the caller): the create rejects with
`ER_LOCK_DEADLOCK`, and no data row or number was written behind the
caller's back.
- SQLite cell, runs on every PR, server deadlock injected at the
cold-seed scan: driver-owned issue retried whole and issued once;
bounded at 5 attempts then the server error; never retried inside a
caller transaction (one attempt, the server error); an error that leaves
the transaction alive (`ER_LOCK_WAIT_TIMEOUT`) not retried.
No existing test was edited.
## Acceptance notes
- **Warm-path cost:** every issue, on every dialect, now makes one
non-locking primary-key read of the counter row before locking it.
Numbers issued are unchanged; the #8269 cold-race suite passes untouched
on live Postgres 16.
- `ER_LOCK_WAIT_TIMEOUT` rolls back only the statement under MySQL's
default `innodb_rollback_on_timeout=OFF`, so it is not classified as a
whole-transaction rollback; a server running with that setting ON would
still take the existing fallback on a lock timeout.
- knex's MySQL client logs "Transaction was implicitly committed, do not
mix transactions and DDL" when its `ROLLBACK TO SAVEPOINT` meets
`ER_SP_DOES_NOT_EXIST` after a deadlock. The wording is knex's and
misleading here; noted, not changed.
## Open questions
- **OQ1, unique index on the autonumber column: dropped, covered by
#14904.** The first reading ("absent") was taken on a raw `SqlDriver`
shape that never went through the spec, so the #13894 default (`unique`
omitted on an `autonumber` field materializes as `'organization'`,
`field.zod.ts`) was never applied. Re-measured on live `mysql:8.0` and
`postgres:16` (and SQLite), with the same object given raw and through
`ObjectSchema.parse`, then `initObjects`:
| dialect | raw shape (`code.unique` undefined) | spec-parsed
(`code.unique` = `'organization'`) |
|:---|:---|:---|
| MySQL 8.0 | `PRIMARY(id)` only | `PRIMARY(id)` + UNIQUE
`uniq_os31608_idx_organization_id_code` on the hash-shadow column
`…__hash` (SHA-256 of `organization_id, code`; the driver warns that
MySQL cannot key that column set over 768 characters directly) |
| Postgres 16 | pkey only | pkey + `CREATE UNIQUE INDEX
uniq_os31608_idx_organization_id_code … (organization_id, code)` |
| SQLite | pk only | pk + `CREATE UNIQUE INDEX
uniq_os31608_idx_organization_id_code … (organization_id, code)` |
Enforcement, spec-parsed, a second create with the same
`organization_id` and `code`: MySQL refused `ER_DUP_ENTRY` (the driver's
duplicate-value message naming the constraint), Postgres refused
`23505`, SQLite refused `SQLITE_CONSTRAINT_UNIQUE`; the same `code` in
another organization was accepted on all three. So MySQL has the index
as Postgres does, and there is no MySQL gap. The card's "no unique index
on the autonumber column" matches the raw shape only.
- **OQ2, one extra non-locking primary-key read per issue: accepted by
the seat.**
## Verification
Head `b0670417` (branch merged with `origin/main` at `cd43416f5`). The
OQ1 reading above was taken on this head; no code changed for it.
<details><summary>Red on main: probe and new tests</summary>
Probe (16 cold creates per round, live `mysql:8.0`, base `09df5711`):
```
one-driver-x16 round 0: ok=14 dups=8 errors=2 [ER_LOCK_DEADLOCK]
one-driver-x16 round 1: ok=16 dups=8 errors=0
one-driver-x16 round 2: ok=13 dups=7 errors=3 [ER_LOCK_DEADLOCK]
one-driver-x16 round 3: ok=16 dups=8 errors=0
one-driver-x16 round 4: ok=16 dups=0 errors=0
two-drivers-x8 round 0: ok=10 dups=8 errors=6 [ER_LOCK_DEADLOCK] counter=[2]
two-drivers-x8 round 1: ok=12 dups=10 errors=4 [ER_LOCK_DEADLOCK] counter=[2]
two-drivers-x8 round 2: ok=11 dups=9 errors=5 [ER_LOCK_DEADLOCK] counter=[2]
two-drivers-x8 round 3: ok=11 dups=9 errors=5 [ER_LOCK_DEADLOCK] counter=[2]
two-drivers-x8 round 4: ok=11 dups=9 errors=5 [ER_LOCK_DEADLOCK] counter=[2]
```
New test file against the base's `sql-driver-autonumber.ts` and
`sql-driver.ts` (tree-only restore, then `git checkout HEAD --`, `git
diff HEAD` empty): `Tests 6 failed | 2 passed (8)`. The four live MySQL
tests and the two retry pins fail; the two pins that main already
satisfied (no retry inside a caller transaction, no retry of a
live-transaction error) pass, as expected of negative pins.
</details>
<details><summary>After the fix: 20 rounds, controls</summary>
- MySQL probe, 20 rounds each mode: `one-driver-x16`, `two-drivers-x8`,
`caller-trx-x16` all `ok=16 dups=0 errors=0`, server `lock_deadlocks`
metric delta 0, counter 16.
- Postgres 16 probe, 5 rounds each mode: all `ok=16 dups=0 errors=0`.
- Live PG 16 + MySQL 8.0, every autonumber file (#8269 cold-race suite
untouched included): `Test Files 12 passed (12)`, `Tests 113 passed
(113)`.
- `pnpm --filter @objectstack/driver-sql test` (SQLite; no live URL),
after merging main: `Test Files 246 passed | 13 skipped (259)`, `Tests
4170 passed | 223 skipped (4393)`, lock VERDICT command-exit 0.
- `pnpm --filter @objectstack/driver-sql typecheck`: exit 0 (the new
test is in the program, `--listFiles`).
- `eslint --no-inline-config packages/drivers/driver-sql`: exit 0.
</details>
<details><summary>Ablations (each committed fix mutated through
scripts/ablation-replace.mjs, restored, blob == HEAD, git diff HEAD
empty)</summary>
The tests import `../src`, so no dist leg applies.
- A1 retry inside a caller transaction too: `never retries inside a
caller transaction` and the live deadlock pin red (`promise resolved …
instead of rejecting`).
- A2 no whole-issue retry: `retries the WHOLE issue …` red (`expected
"scanMaxNumericTail" to be called 5 times, but got 1 times`) and the
bound pin red.
- A3 every error classified as a whole-transaction rollback: `does not
retry an error that leaves the transaction alive` red (`promise resolved
… instead of rejecting`).
- A5 `INSERT IGNORE` on MySQL instead of `ON DUPLICATE KEY UPDATE`: the
caller-transaction burst red (`expected [ 'ER_LOCK_DEADLOCK', …(13) ] to
deeply equal []`).
- A7 fallback read after a whole-transaction rollback: the live deadlock
pin red (`promise resolved … instead of rejecting`).
</details>
<details><summary>Gates (dispatch-gates --commands, 69 commands, at
b067041)</summary>
- `node scripts/pm/dispatch-gates.mjs --repo objectstack-ai/objectstack
--ran FILE`: `69 derived famil(ies) accounted for — 69 run, 0
NOT-MEASURED`, exit 0.
- 66 of 69 exit 0 on the first pass. Three exited 3 on container
prerequisites, not the diff, and were rerun green on the same head:
`check-plugin-teardown-shape.mjs --self-test` (fixture commit `621a4876`
fetched), `check:dual-build-cjs-loads` and `check:lean-entry-closure`
(after a full `pnpm build` under the lock, VERDICT command-exit 0).
- Among them, the families that read this diff:
`check:driver-conformance`, `check:durability-log-level`,
`check:engine-double-contract`, `check:tenant-chokepoint`,
`check:cross-package-test-inputs`, `check:test-source-alias`,
`check:adr-0087-registration`, `check:empty-changeset`,
`check:changeset-no-major`, `check:nul-bytes`: all exit 0.
</details>
<!-- signed: domain:server#2 · os-steve ·
session_01ADHkmSaagzgP2FPBJq6Cre -->
---------
Co-authored-by: Claude <noreply@anthropic.com>1 parent 35a9c69 commit 82a3ed2
4 files changed
Lines changed: 362 additions & 43 deletions
File tree
- .changeset
- packages/drivers/driver-sql/src
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
| 95 | + | |
| 96 | + | |
| 97 | + | |
| 98 | + | |
| 99 | + | |
| 100 | + | |
| 101 | + | |
| 102 | + | |
| 103 | + | |
| 104 | + | |
| 105 | + | |
| 106 | + | |
| 107 | + | |
| 108 | + | |
| 109 | + | |
| 110 | + | |
| 111 | + | |
| 112 | + | |
| 113 | + | |
| 114 | + | |
| 115 | + | |
| 116 | + | |
| 117 | + | |
| 118 | + | |
| 119 | + | |
| 120 | + | |
| 121 | + | |
| 122 | + | |
| 123 | + | |
| 124 | + | |
| 125 | + | |
| 126 | + | |
| 127 | + | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| 138 | + | |
| 139 | + | |
| 140 | + | |
| 141 | + | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
| 145 | + | |
| 146 | + | |
| 147 | + | |
| 148 | + | |
| 149 | + | |
| 150 | + | |
| 151 | + | |
| 152 | + | |
| 153 | + | |
| 154 | + | |
| 155 | + | |
| 156 | + | |
| 157 | + | |
| 158 | + | |
| 159 | + | |
| 160 | + | |
| 161 | + | |
| 162 | + | |
| 163 | + | |
| 164 | + | |
| 165 | + | |
| 166 | + | |
| 167 | + | |
| 168 | + | |
| 169 | + | |
| 170 | + | |
| 171 | + | |
| 172 | + | |
| 173 | + | |
| 174 | + | |
| 175 | + | |
| 176 | + | |
| 177 | + | |
| 178 | + | |
| 179 | + | |
| 180 | + | |
| 181 | + | |
| 182 | + | |
| 183 | + | |
| 184 | + | |
| 185 | + | |
| 186 | + | |
| 187 | + | |
| 188 | + | |
| 189 | + | |
| 190 | + | |
| 191 | + | |
| 192 | + | |
| 193 | + | |
| 194 | + | |
| 195 | + | |
| 196 | + | |
| 197 | + | |
| 198 | + | |
| 199 | + | |
| 200 | + | |
| 201 | + | |
| 202 | + | |
| 203 | + | |
| 204 | + | |
| 205 | + | |
| 206 | + | |
| 207 | + | |
| 208 | + | |
| 209 | + | |
| 210 | + | |
| 211 | + | |
| 212 | + | |
| 213 | + | |
| 214 | + | |
| 215 | + | |
| 216 | + | |
| 217 | + | |
| 218 | + | |
| 219 | + | |
| 220 | + | |
| 221 | + | |
| 222 | + | |
| 223 | + | |
| 224 | + | |
0 commit comments