Skip to content

Commit 82a3ed2

Browse files
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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/driver-sql': patch
3+
---
4+
5+
fix(driver-sql): concurrent first writes to a new autonumber object on MySQL no longer issue duplicate numbers
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
On MySQL 8, the first records written concurrently to an object whose autonumber counter did not exist yet could share a number (measured: 16 cold writers gave up to 10 duplicates, with some creates failing `ER_LOCK_DEADLOCK`). The cold seed locked a missing counter row before inserting it; on InnoDB that takes a gap lock every writer shares, so the inserts deadlocked, the server rolled the losers' whole transactions back, and the driver went on in autocommit, where its locked read no longer locked anything.
11+
12+
The counter row is now seeded first, by an idempotent insert (`ON CONFLICT DO NOTHING` on Postgres and SQLite, a no-op `ON DUPLICATE KEY UPDATE` on MySQL), and locked only once it exists, so a cold counter takes the same path as a warm one. Measured on MySQL 8.0 after the fix: 16 cold writers on one driver, on two drivers, and in 16 caller transactions issue 1..16 once each, with no deadlock.
13+
14+
When the server does roll the whole transaction back (`ER_LOCK_DEADLOCK`): an issue in a transaction the driver owns is retried from the start, up to five attempts; an issue inside the caller's transaction is not retried and the caller gets the server's `ER_LOCK_DEADLOCK`, since that transaction, and the caller's earlier writes in it, are already gone. Before, the issue went on and its writes autocommitted outside the caller's transaction.
15+
16+
Postgres and SQLite issue the same numbers as before; every issue now reads the counter row once without a lock before locking it.
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* #31608 — on MySQL 8, the first CONCURRENT autonumber inserts into a COLD
5+
* object issued DUPLICATE numbers. The MySQL twin of #8269
6+
* (`sql-driver-autonumber-cold-race.test.ts`), which is the Postgres one.
7+
*
8+
* ## The mechanism, measured on `mysql:8.0` (InnoDB, REPEATABLE READ)
9+
*
10+
* The cold seed was speculative: `SELECT … FOR UPDATE` on the missing counter
11+
* row, then an INSERT. A locking read of a missing key takes a next-key lock
12+
* on the gap (`lock_mode X` on the supremum record); gap locks are compatible
13+
* with each other, so every cold writer held one, and each INSERT then waited
14+
* on the others' for its insert intention: `ER_LOCK_DEADLOCK` on the INSERT.
15+
* InnoDB rolls the victim's WHOLE transaction back, not to the savepoint
16+
* (`ROLLBACK TO SAVEPOINT` then answers `ER_SP_DOES_NOT_EXIST`), and the
17+
* session drops to autocommit. The recovery statements ran on regardless, so
18+
* the `FOR UPDATE` lock ended with its own statement and every victim read
19+
* the winner's counter and wrote the same value back: a lost update. Before
20+
* the fix, 5 rounds of 16 cold writers gave 7-8 duplicates in 4 rounds on one
21+
* driver, and 8-10 duplicates in every round on two drivers, with 2-6 surfaced
22+
* `ER_LOCK_DEADLOCK` create errors.
23+
*
24+
* Postgres never had this shape (a deadlock there aborts the savepoint only,
25+
* which `attemptWithoutPoisoning` recovers), and SQLite serialises writers, so
26+
* a live MySQL server is the only place the duplicate can be seen.
27+
*/
28+
29+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
30+
import { SqlDriver } from '../src/index.js';
31+
import { declareDialectCell, dialectCell, MYSQL_CELL, type DialectCell } from './live-dialect-matrix.testkit.js';
32+
33+
const TABLE = 'os31608_cold_race';
34+
const SEQUENCES_TABLE = '_objectstack_sequences';
35+
36+
const SHAPE = {
37+
name: TABLE,
38+
fields: {
39+
organization_id: { type: 'string' },
40+
code: { type: 'autonumber', format: 'TK-{0000}' },
41+
name: { type: 'string' },
42+
},
43+
} as any;
44+
45+
/** The band a cold counter must issue: 1..n, each once. */
46+
const band = (n: number) => Array.from({ length: n }, (_, i) => `TK-${String(i + 1).padStart(4, '0')}`);
47+
48+
/** A server-shaped MySQL deadlock: the two fields `rollsBackWholeTransaction` reads. */
49+
const deadlock = () => Object.assign(new Error('Deadlock found when trying to get lock; try restarting transaction'), { code: 'ER_LOCK_DEADLOCK', errno: 1213 });
50+
51+
async function makeCold(driver: SqlDriver): Promise<void> {
52+
const knex = (driver as any).knex;
53+
await knex.schema.dropTableIfExists(TABLE);
54+
if (await knex.schema.hasTable(SEQUENCES_TABLE)) await knex(SEQUENCES_TABLE).where('object', TABLE).del();
55+
await driver.initObjects([SHAPE]);
56+
}
57+
58+
async function counterOf(driver: SqlDriver): Promise<number[]> {
59+
const rows = await (driver as any).knex(SEQUENCES_TABLE).where('object', TABLE).select('last_value');
60+
return rows.map((r: any) => Number(r.last_value));
61+
}
62+
63+
declareDialectCell(MYSQL_CELL, 'autonumber cold concurrent race (#31608)', (cell: DialectCell) => {
64+
describe(`sql-driver — autonumber cold concurrent race (${cell.label}) [#31608]`, () => {
65+
const ROUNDS = 3;
66+
const WRITERS = 16;
67+
let drivers: SqlDriver[];
68+
69+
beforeEach(() => {
70+
// Two driver instances = two connection pools, the in-container stand-in
71+
// for two server processes writing to one database.
72+
drivers = [new SqlDriver(cell.config()), new SqlDriver(cell.config())];
73+
});
74+
75+
afterEach(async () => {
76+
await (drivers[0] as any).knex.schema.dropTableIfExists(TABLE).catch(() => {});
77+
await Promise.all(drivers.map((d) => d.disconnect()));
78+
});
79+
80+
const burst = async (pick: (i: number) => SqlDriver, inCallerTransaction = false) => {
81+
for (let round = 0; round < ROUNDS; round++) {
82+
await makeCold(drivers[0]);
83+
await drivers[1].initObjects([SHAPE]);
84+
const settled = await Promise.allSettled(
85+
Array.from({ length: WRITERS }, (_, i) => {
86+
const d = pick(i);
87+
const row = { organization_id: 'os31608_org', name: `w${i}` };
88+
return inCallerTransaction
89+
? (d as any).knex.transaction((trx: any) => d.create(TABLE, row, { transaction: trx } as any))
90+
: d.create(TABLE, row);
91+
}),
92+
);
93+
// Every writer succeeds: no deadlock is surfaced to a create the
94+
// driver could have completed.
95+
expect(settled.filter((s) => s.status === 'rejected').map((s: any) => s.reason?.code ?? String(s.reason))).toEqual([]);
96+
// 1..16, each once — unfixed, the band repeats TK-0002 (and others).
97+
expect(settled.map((s: any) => s.value.code).sort(), `round ${round}`).toEqual(band(WRITERS));
98+
expect(await counterOf(drivers[0])).toEqual([WRITERS]);
99+
}
100+
};
101+
102+
it('issues 1..N once each on one driver, 16 cold writers', async () => {
103+
await burst(() => drivers[0]);
104+
});
105+
106+
it('issues 1..N once each across two drivers (two pools), 16 cold writers', async () => {
107+
await burst((i) => drivers[i % 2]);
108+
});
109+
110+
it('issues 1..N once each when every writer runs in its own caller transaction', async () => {
111+
await burst((i) => drivers[i % 2], true);
112+
});
113+
114+
it('refuses with the server deadlock, and writes nothing, when a deadlock rolls back the caller transaction', async () => {
115+
// A REAL deadlock, built deterministically: the caller holds a lock the
116+
// other transaction wants, while the other holds the counter row the
117+
// caller's issue wants. The other transaction is made the heavier one
118+
// (it has written rows) so InnoDB picks the caller as the victim.
119+
const [driver] = drivers;
120+
const knex = (driver as any).knex;
121+
await makeCold(driver);
122+
await driver.create(TABLE, { organization_id: 'os31608_org', name: 'warm' }); // TK-0001, counter row exists
123+
const LOCKS = 'os31608_lock_probe';
124+
await knex.schema.dropTableIfExists(LOCKS);
125+
await knex.schema.createTable(LOCKS, (t: any) => {
126+
t.string('k').primary();
127+
});
128+
await knex(LOCKS).insert({ k: 'held-by-caller' });
129+
try {
130+
const other = await knex.transaction();
131+
let caller: any;
132+
try {
133+
await other(LOCKS).insert(Array.from({ length: 20 }, (_, i) => ({ k: `weight-${i}` })));
134+
await other(SEQUENCES_TABLE).where('object', TABLE).forUpdate().select('last_value');
135+
caller = await knex.transaction();
136+
await caller(LOCKS).where('k', 'held-by-caller').forUpdate().first();
137+
// Blocks on the counter row the other transaction holds.
138+
const issuing = driver.create(TABLE, { organization_id: 'os31608_org', name: 'victim' }, { transaction: caller } as any);
139+
issuing.catch(() => {});
140+
await new Promise((r) => setTimeout(r, 300));
141+
// Closes the cycle; InnoDB rolls the caller back. (`.then` sends it:
142+
// a knex builder is lazy until something awaits it.)
143+
const closing = other(LOCKS).where('k', 'held-by-caller').forUpdate().first().then(() => 'granted', (e: any) => e?.code);
144+
// The other side was not the victim: it got the lock once the
145+
// caller's transaction was gone. Ending it frees the counter row, so
146+
// nothing stops an issue that went on regardless from completing.
147+
expect(await closing).toBe('granted');
148+
await other.rollback();
149+
// The server's own error reaches the caller. Unfixed, the issue went
150+
// on in autocommit instead and the create SUCCEEDED, outside the
151+
// caller's rolled-back transaction.
152+
await expect(issuing).rejects.toMatchObject({ code: 'ER_LOCK_DEADLOCK' });
153+
} finally {
154+
await other.rollback().catch(() => {});
155+
await caller?.rollback().catch(() => {});
156+
}
157+
// Nothing autocommitted behind the caller's back: no row, no number.
158+
expect((await knex(TABLE).select('code')).map((r: any) => r.code)).toEqual(['TK-0001']);
159+
expect(await counterOf(driver)).toEqual([1]);
160+
} finally {
161+
await knex.schema.dropTableIfExists(LOCKS);
162+
}
163+
});
164+
});
165+
});
166+
167+
// The retry contract, pinned on the embedded cell so it runs on every PR. A
168+
// SQLite server never raises `ER_LOCK_DEADLOCK`, so the server's answer is
169+
// injected at the cold-seed scan — the first statement of a cold issue.
170+
describe('sql-driver — autonumber issue after a whole-transaction rollback (sqlite, injected) [#31608]', () => {
171+
let driver: SqlDriver;
172+
173+
beforeEach(async () => {
174+
driver = new SqlDriver(dialectCell('sqlite').config());
175+
await driver.initObjects([SHAPE]);
176+
});
177+
178+
afterEach(async () => {
179+
vi.restoreAllMocks();
180+
await driver.disconnect();
181+
});
182+
183+
const failScan = (times: number, error: () => unknown) => {
184+
const real = (driver as any).scanMaxNumericTail.bind(driver);
185+
let calls = 0;
186+
const spy = vi.spyOn(driver as any, 'scanMaxNumericTail').mockImplementation(async (...a: unknown[]) => {
187+
calls++;
188+
if (calls <= times) throw error();
189+
return real(...a);
190+
});
191+
return spy;
192+
};
193+
194+
it('retries the WHOLE issue when the driver owns the transaction, and issues the number once', async () => {
195+
const spy = failScan(1, deadlock);
196+
const row = await driver.create(TABLE, { organization_id: 'os31608_org', name: 'a' });
197+
expect(row.code).toBe('TK-0001');
198+
expect(spy).toHaveBeenCalledTimes(2);
199+
expect(await counterOf(driver)).toEqual([1]);
200+
});
201+
202+
it('gives up with the server error after a bounded number of whole-issue attempts', async () => {
203+
const spy = failScan(Infinity, deadlock);
204+
await expect(driver.create(TABLE, { organization_id: 'os31608_org', name: 'a' })).rejects.toMatchObject({ code: 'ER_LOCK_DEADLOCK' });
205+
expect(spy).toHaveBeenCalledTimes(5);
206+
expect(await counterOf(driver)).toEqual([]);
207+
});
208+
209+
it('never retries inside a caller transaction: the caller gets the server error, once', async () => {
210+
const spy = failScan(1, deadlock);
211+
const knex = (driver as any).knex;
212+
await expect(
213+
knex.transaction((trx: any) => driver.create(TABLE, { organization_id: 'os31608_org', name: 'a' }, { transaction: trx } as any)),
214+
).rejects.toMatchObject({ code: 'ER_LOCK_DEADLOCK' });
215+
expect(spy).toHaveBeenCalledTimes(1);
216+
expect(await counterOf(driver)).toEqual([]);
217+
});
218+
219+
it('does not retry an error that leaves the transaction alive', async () => {
220+
const spy = failScan(1, () => Object.assign(new Error('Lock wait timeout exceeded'), { code: 'ER_LOCK_WAIT_TIMEOUT', errno: 1205 }));
221+
await expect(driver.create(TABLE, { organization_id: 'os31608_org', name: 'a' })).rejects.toMatchObject({ code: 'ER_LOCK_WAIT_TIMEOUT' });
222+
expect(spy).toHaveBeenCalledTimes(1);
223+
});
224+
});

0 commit comments

Comments
 (0)