Repository navigation
fix(driver-sql): MySQL autonumber no longer issues duplicate numbers when the first rows of an object are written concurrently - #31709
Conversation
… MySQL never issues duplicates On MySQL 8 the cold seed locked a missing counter row and then inserted it. The locking read takes a shared gap lock, the concurrent inserts deadlock on it, InnoDB rolls the losers' whole transactions back, and the recovery statements then ran in autocommit as a lost update: duplicate numbers. The counter row is now seeded first by an idempotent insert (ON CONFLICT DO NOTHING; a no-op ON DUPLICATE KEY UPDATE on MySQL, which takes the exclusive lock at once and so does not deadlock the losers on a lock upgrade) and locked only once it exists. A whole-transaction rollback is retried from the start when the driver owns the transaction and refused with the server's own error inside a caller's transaction. Claude-Session: https://claude.ai/code/session_01ADHkmSaagzgP2FPBJq6Cre Co-authored-by: Claude <noreply@anthropic.com>
…ked read's own error knex's MySQL client swallows the ER_SP_DOES_NOT_EXIST its ROLLBACK TO SAVEPOINT meets after a deadlock and rejects with the deadlock itself, so no stash of the original error is needed: the locked read's failure is checked directly. The live refusal pin now ends the other transaction before awaiting the issue, so an issue that went on after the rollback would complete and be seen. Claude-Session: https://claude.ai/code/session_01ADHkmSaagzgP2FPBJq6Cre Co-authored-by: Claude <noreply@anthropic.com>
📓 Docs Drift Check13 anchor(s) derived from 1 changed package(s); no hand-written page names any of them, so this run has nothing to list — not a clean bill of health. This check sees only pages that NAME a derived anchor: one that documents this change in prose, or enumerates it in an authoring dialect, names none and stays invisible to it on every run. What this run could not see
Coarse fallback — 14 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # while this PR is open — GitHub drops the merge commit once it closes
git fetch origin 6b7c44637f0b3d63a3af0398e5a531b7780607f8 && git checkout 6b7c44637f0b3d63a3af0398e5a531b7780607f8
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin e81636ce7ed9161e759076556871ab73d3aac4cd b0670417621568f49607ce8ced7e86632ed0d97e && git checkout -B drift-repro e81636ce7ed9161e759076556871ab73d3aac4cd && git merge --no-ff b0670417621568f49607ce8ced7e86632ed0d97e
node scripts/docs-audit/affected-docs.mjs --json e81636ce7ed9161e759076556871ab73d3aac4cd |
|
domain:server#2 · os-steve · session_01ADHkmQKZzp4DLtqiCkZZRM 维护者速读
席位核对 — ACCEPT · domain:server#2 · Head-sha
|
Requested by Steve · project thread
Fixes #31608
Clause-②: no
Metadata-protocol: none
维护者速读
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.0cell (8.0.46, InnoDB, REPEATABLE READ):SELECT … FOR UPDATEon the missing counter row, thenINSERT. A locking read of a missing key takes a next-key lock on the gap;SHOW ENGINE INNODB STATUSshows both transactions holdinglock_mode Xon the supremum record of_objectstack_sequences's PRIMARY index and each waiting onlock_mode X insert intentionfor its INSERT of the samekey_hash. Gap locks are compatible with each other, so every cold writer holds one and every INSERT waits on the others.ER_LOCK_DEADLOCK,ROLLBACK TO SAVEPOINTanswersER_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.attemptWithoutPoisoningreported the failed INSERT, so the code took its recovery path:SELECT … FOR UPDATEthenUPDATE last_value = last_value + 1. Both now ran in autocommit, so the lock ended with its own statement, and every victim read the winner'slast_valueand wrote the same value back: a lost update. On two drivers the counter ended at 2 with nine creates holdingTK-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:
ON CONFLICT DO NOTHING, with no conflict target, so it matches whichever unique key the table has (a target would raise42P10against the interim four-column key an incomplete key-hash migration leaves, the reasonattemptWithoutPoisoninggives).ON DUPLICATE KEY UPDATE, notINSERT IGNORE. Measured: withINSERT IGNOREthe losers take a SHARED lock on the duplicate and deadlock upgrading it for theFOR 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 UPDATEtakes the exclusive lock at once: 0 deadlocks. It also leaves other errors loud whereIGNOREturns them into warnings.rollsBackWholeTransactionnames the class: MySQLER_LOCK_DEADLOCK(errno 1213). Postgres40P01and lock timeouts abort only the savepoint and keep their existing handling.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 theisMysqlgetter (one line insql-driver.ts, the host literal) to choose the MySQL seed spelling. No export moves;index.tsre-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):declareDialectCell(MYSQL_CELL, …); CI runs it inTemporal Conformance (live PG + MySQL), a named skip elsewhere), 3 cold rounds each of 16 writers:TK-0001..TK-0016, counter16.ER_LOCK_DEADLOCK, and no data row or number was written behind the caller's back.ER_LOCK_WAIT_TIMEOUT) not retried.No existing test was edited.
Acceptance notes
ER_LOCK_WAIT_TIMEOUTrolls back only the statement under MySQL's defaultinnodb_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.ROLLBACK TO SAVEPOINTmeetsER_SP_DOES_NOT_EXISTafter 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 feat(spec): autonumber fields default to unique: 'organization'; explicit unique: false opts out (#13894) #14904. The first reading ("absent") was taken on a raw
SqlDrivershape that never went through the spec, so the autonumber 业务标识字段默认不唯一,可铸重号 —— 裁定:默认唯一(租户复合形状),显式退出才不唯一 #13894 default (uniqueomitted on anautonumberfield materializes as'organization',field.zod.ts) was never applied. Re-measured on livemysql:8.0andpostgres:16(and SQLite), with the same object given raw and throughObjectSchema.parse, theninitObjects:code.uniqueundefined)code.unique='organization')PRIMARY(id)onlyPRIMARY(id)+ UNIQUEuniq_os31608_idx_organization_id_codeon the hash-shadow column…__hash(SHA-256 oforganization_id, code; the driver warns that MySQL cannot key that column set over 768 characters directly)CREATE UNIQUE INDEX uniq_os31608_idx_organization_id_code … (organization_id, code)CREATE UNIQUE INDEX uniq_os31608_idx_organization_id_code … (organization_id, code)Enforcement, spec-parsed, a second create with the same
organization_idandcode: MySQL refusedER_DUP_ENTRY(the driver's duplicate-value message naming the constraint), Postgres refused23505, SQLite refusedSQLITE_CONSTRAINT_UNIQUE; the samecodein 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 withorigin/mainatcd43416f5). The OQ1 reading above was taken on this head; no code changed for it.Red on main: probe and new tests
Probe (16 cold creates per round, live
mysql:8.0, base09df5711):New test file against the base's
sql-driver-autonumber.tsandsql-driver.ts(tree-only restore, thengit checkout HEAD --,git diff HEADempty):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.After the fix: 20 rounds, controls
one-driver-x16,two-drivers-x8,caller-trx-x16allok=16 dups=0 errors=0, serverlock_deadlocksmetric delta 0, counter 16.ok=16 dups=0 errors=0.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.Ablations (each committed fix mutated through scripts/ablation-replace.mjs, restored, blob == HEAD, git diff HEAD empty)
The tests import
../src, so no dist leg applies.never retries inside a caller transactionand the live deadlock pin red (promise resolved … instead of rejecting).retries the WHOLE issue …red (expected "scanMaxNumericTail" to be called 5 times, but got 1 times) and the bound pin red.does not retry an error that leaves the transaction alivered (promise resolved … instead of rejecting).INSERT IGNOREon MySQL instead ofON DUPLICATE KEY UPDATE: the caller-transaction burst red (expected [ 'ER_LOCK_DEADLOCK', …(13) ] to deeply equal []).promise resolved … instead of rejecting).Gates (dispatch-gates --commands, 69 commands, at b067041)
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.check-plugin-teardown-shape.mjs --self-test(fixture commit621a4876fetched),check:dual-build-cjs-loadsandcheck:lean-entry-closure(after a fullpnpm buildunder the lock, VERDICT command-exit 0).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.