diff --git a/.changeset/31608-mysql-cold-autonumber-duplicates.md b/.changeset/31608-mysql-cold-autonumber-duplicates.md new file mode 100644 index 00000000000..7cb75fc868b --- /dev/null +++ b/.changeset/31608-mysql-cold-autonumber-duplicates.md @@ -0,0 +1,16 @@ +--- +'@objectstack/driver-sql': patch +--- + +fix(driver-sql): concurrent first writes to a new autonumber object on MySQL no longer issue duplicate numbers + +Clause-②: no +Metadata-protocol: none + +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. + +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. + +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. + +Postgres and SQLite issue the same numbers as before; every issue now reads the counter row once without a lock before locking it. diff --git a/packages/drivers/driver-sql/src/sql-driver-autonumber-cold-race-mysql.test.ts b/packages/drivers/driver-sql/src/sql-driver-autonumber-cold-race-mysql.test.ts new file mode 100644 index 00000000000..c1c18e882eb --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-autonumber-cold-race-mysql.test.ts @@ -0,0 +1,224 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #31608 — on MySQL 8, the first CONCURRENT autonumber inserts into a COLD + * object issued DUPLICATE numbers. The MySQL twin of #8269 + * (`sql-driver-autonumber-cold-race.test.ts`), which is the Postgres one. + * + * ## The mechanism, measured on `mysql:8.0` (InnoDB, REPEATABLE READ) + * + * The cold seed was speculative: `SELECT … FOR UPDATE` on the missing counter + * row, then an INSERT. A locking read of a missing key takes a next-key lock + * on the gap (`lock_mode X` on the supremum record); gap locks are compatible + * with each other, so every cold writer held one, and each INSERT then waited + * on the others' for its insert intention: `ER_LOCK_DEADLOCK` on the INSERT. + * InnoDB rolls the victim's WHOLE transaction back, not to the savepoint + * (`ROLLBACK TO SAVEPOINT` then answers `ER_SP_DOES_NOT_EXIST`), and the + * session drops to autocommit. The recovery statements ran on regardless, so + * the `FOR UPDATE` lock ended with its own statement and every victim read + * the winner's counter and wrote the same value back: a lost update. Before + * the fix, 5 rounds of 16 cold writers gave 7-8 duplicates in 4 rounds on one + * driver, and 8-10 duplicates in every round on two drivers, with 2-6 surfaced + * `ER_LOCK_DEADLOCK` create errors. + * + * Postgres never had this shape (a deadlock there aborts the savepoint only, + * which `attemptWithoutPoisoning` recovers), and SQLite serialises writers, so + * a live MySQL server is the only place the duplicate can be seen. + */ + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { SqlDriver } from '../src/index.js'; +import { declareDialectCell, dialectCell, MYSQL_CELL, type DialectCell } from './live-dialect-matrix.testkit.js'; + +const TABLE = 'os31608_cold_race'; +const SEQUENCES_TABLE = '_objectstack_sequences'; + +const SHAPE = { + name: TABLE, + fields: { + organization_id: { type: 'string' }, + code: { type: 'autonumber', format: 'TK-{0000}' }, + name: { type: 'string' }, + }, +} as any; + +/** The band a cold counter must issue: 1..n, each once. */ +const band = (n: number) => Array.from({ length: n }, (_, i) => `TK-${String(i + 1).padStart(4, '0')}`); + +/** A server-shaped MySQL deadlock: the two fields `rollsBackWholeTransaction` reads. */ +const deadlock = () => Object.assign(new Error('Deadlock found when trying to get lock; try restarting transaction'), { code: 'ER_LOCK_DEADLOCK', errno: 1213 }); + +async function makeCold(driver: SqlDriver): Promise { + const knex = (driver as any).knex; + await knex.schema.dropTableIfExists(TABLE); + if (await knex.schema.hasTable(SEQUENCES_TABLE)) await knex(SEQUENCES_TABLE).where('object', TABLE).del(); + await driver.initObjects([SHAPE]); +} + +async function counterOf(driver: SqlDriver): Promise { + const rows = await (driver as any).knex(SEQUENCES_TABLE).where('object', TABLE).select('last_value'); + return rows.map((r: any) => Number(r.last_value)); +} + +declareDialectCell(MYSQL_CELL, 'autonumber cold concurrent race (#31608)', (cell: DialectCell) => { + describe(`sql-driver — autonumber cold concurrent race (${cell.label}) [#31608]`, () => { + const ROUNDS = 3; + const WRITERS = 16; + let drivers: SqlDriver[]; + + beforeEach(() => { + // Two driver instances = two connection pools, the in-container stand-in + // for two server processes writing to one database. + drivers = [new SqlDriver(cell.config()), new SqlDriver(cell.config())]; + }); + + afterEach(async () => { + await (drivers[0] as any).knex.schema.dropTableIfExists(TABLE).catch(() => {}); + await Promise.all(drivers.map((d) => d.disconnect())); + }); + + const burst = async (pick: (i: number) => SqlDriver, inCallerTransaction = false) => { + for (let round = 0; round < ROUNDS; round++) { + await makeCold(drivers[0]); + await drivers[1].initObjects([SHAPE]); + const settled = await Promise.allSettled( + Array.from({ length: WRITERS }, (_, i) => { + const d = pick(i); + const row = { organization_id: 'os31608_org', name: `w${i}` }; + return inCallerTransaction + ? (d as any).knex.transaction((trx: any) => d.create(TABLE, row, { transaction: trx } as any)) + : d.create(TABLE, row); + }), + ); + // Every writer succeeds: no deadlock is surfaced to a create the + // driver could have completed. + expect(settled.filter((s) => s.status === 'rejected').map((s: any) => s.reason?.code ?? String(s.reason))).toEqual([]); + // 1..16, each once — unfixed, the band repeats TK-0002 (and others). + expect(settled.map((s: any) => s.value.code).sort(), `round ${round}`).toEqual(band(WRITERS)); + expect(await counterOf(drivers[0])).toEqual([WRITERS]); + } + }; + + it('issues 1..N once each on one driver, 16 cold writers', async () => { + await burst(() => drivers[0]); + }); + + it('issues 1..N once each across two drivers (two pools), 16 cold writers', async () => { + await burst((i) => drivers[i % 2]); + }); + + it('issues 1..N once each when every writer runs in its own caller transaction', async () => { + await burst((i) => drivers[i % 2], true); + }); + + it('refuses with the server deadlock, and writes nothing, when a deadlock rolls back the caller transaction', async () => { + // A REAL deadlock, built deterministically: the caller holds a lock the + // other transaction wants, while the other holds the counter row the + // caller's issue wants. The other transaction is made the heavier one + // (it has written rows) so InnoDB picks the caller as the victim. + const [driver] = drivers; + const knex = (driver as any).knex; + await makeCold(driver); + await driver.create(TABLE, { organization_id: 'os31608_org', name: 'warm' }); // TK-0001, counter row exists + const LOCKS = 'os31608_lock_probe'; + await knex.schema.dropTableIfExists(LOCKS); + await knex.schema.createTable(LOCKS, (t: any) => { + t.string('k').primary(); + }); + await knex(LOCKS).insert({ k: 'held-by-caller' }); + try { + const other = await knex.transaction(); + let caller: any; + try { + await other(LOCKS).insert(Array.from({ length: 20 }, (_, i) => ({ k: `weight-${i}` }))); + await other(SEQUENCES_TABLE).where('object', TABLE).forUpdate().select('last_value'); + caller = await knex.transaction(); + await caller(LOCKS).where('k', 'held-by-caller').forUpdate().first(); + // Blocks on the counter row the other transaction holds. + const issuing = driver.create(TABLE, { organization_id: 'os31608_org', name: 'victim' }, { transaction: caller } as any); + issuing.catch(() => {}); + await new Promise((r) => setTimeout(r, 300)); + // Closes the cycle; InnoDB rolls the caller back. (`.then` sends it: + // a knex builder is lazy until something awaits it.) + const closing = other(LOCKS).where('k', 'held-by-caller').forUpdate().first().then(() => 'granted', (e: any) => e?.code); + // The other side was not the victim: it got the lock once the + // caller's transaction was gone. Ending it frees the counter row, so + // nothing stops an issue that went on regardless from completing. + expect(await closing).toBe('granted'); + await other.rollback(); + // The server's own error reaches the caller. Unfixed, the issue went + // on in autocommit instead and the create SUCCEEDED, outside the + // caller's rolled-back transaction. + await expect(issuing).rejects.toMatchObject({ code: 'ER_LOCK_DEADLOCK' }); + } finally { + await other.rollback().catch(() => {}); + await caller?.rollback().catch(() => {}); + } + // Nothing autocommitted behind the caller's back: no row, no number. + expect((await knex(TABLE).select('code')).map((r: any) => r.code)).toEqual(['TK-0001']); + expect(await counterOf(driver)).toEqual([1]); + } finally { + await knex.schema.dropTableIfExists(LOCKS); + } + }); + }); +}); + +// The retry contract, pinned on the embedded cell so it runs on every PR. A +// SQLite server never raises `ER_LOCK_DEADLOCK`, so the server's answer is +// injected at the cold-seed scan — the first statement of a cold issue. +describe('sql-driver — autonumber issue after a whole-transaction rollback (sqlite, injected) [#31608]', () => { + let driver: SqlDriver; + + beforeEach(async () => { + driver = new SqlDriver(dialectCell('sqlite').config()); + await driver.initObjects([SHAPE]); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + await driver.disconnect(); + }); + + const failScan = (times: number, error: () => unknown) => { + const real = (driver as any).scanMaxNumericTail.bind(driver); + let calls = 0; + const spy = vi.spyOn(driver as any, 'scanMaxNumericTail').mockImplementation(async (...a: unknown[]) => { + calls++; + if (calls <= times) throw error(); + return real(...a); + }); + return spy; + }; + + it('retries the WHOLE issue when the driver owns the transaction, and issues the number once', async () => { + const spy = failScan(1, deadlock); + const row = await driver.create(TABLE, { organization_id: 'os31608_org', name: 'a' }); + expect(row.code).toBe('TK-0001'); + expect(spy).toHaveBeenCalledTimes(2); + expect(await counterOf(driver)).toEqual([1]); + }); + + it('gives up with the server error after a bounded number of whole-issue attempts', async () => { + const spy = failScan(Infinity, deadlock); + await expect(driver.create(TABLE, { organization_id: 'os31608_org', name: 'a' })).rejects.toMatchObject({ code: 'ER_LOCK_DEADLOCK' }); + expect(spy).toHaveBeenCalledTimes(5); + expect(await counterOf(driver)).toEqual([]); + }); + + it('never retries inside a caller transaction: the caller gets the server error, once', async () => { + const spy = failScan(1, deadlock); + const knex = (driver as any).knex; + await expect( + knex.transaction((trx: any) => driver.create(TABLE, { organization_id: 'os31608_org', name: 'a' }, { transaction: trx } as any)), + ).rejects.toMatchObject({ code: 'ER_LOCK_DEADLOCK' }); + expect(spy).toHaveBeenCalledTimes(1); + expect(await counterOf(driver)).toEqual([]); + }); + + it('does not retry an error that leaves the transaction alive', async () => { + const spy = failScan(1, () => Object.assign(new Error('Lock wait timeout exceeded'), { code: 'ER_LOCK_WAIT_TIMEOUT', errno: 1205 })); + await expect(driver.create(TABLE, { organization_id: 'os31608_org', name: 'a' })).rejects.toMatchObject({ code: 'ER_LOCK_WAIT_TIMEOUT' }); + expect(spy).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/drivers/driver-sql/src/sql-driver-autonumber.ts b/packages/drivers/driver-sql/src/sql-driver-autonumber.ts index 026dfdda8d7..0bfe1c16874 100644 --- a/packages/drivers/driver-sql/src/sql-driver-autonumber.ts +++ b/packages/drivers/driver-sql/src/sql-driver-autonumber.ts @@ -84,6 +84,7 @@ export interface AutonumberHost { fillAutoNumberFields: SqlDriver['fillAutoNumberFields']; getNextSequenceValue: SqlDriver['getNextSequenceValue']; injectTenantOnInsert: SqlDriver['injectTenantOnInsert']; + readonly isMysql: SqlDriver['isMysql']; readonly issuedAutoNumbers: SqlDriver['issuedAutoNumbers']; readonly knex: SqlDriver['knex']; readonly physicalTableByObject: SqlDriver['physicalTableByObject']; @@ -95,7 +96,7 @@ export interface AutonumberHost { } /** The body of `SqlDriver#getNextSequenceValue`; the method's docblock there is its contract. */ -export async function getNextSequenceValue(this: Pick, object: string, tableName: string, field: string, prefix: string, tenantField: string | null, tenantId: string | null, parentTrx?: Knex.Transaction, scope = '', suffix = ''): Promise { +export async function getNextSequenceValue(this: Pick, object: string, tableName: string, field: string, prefix: string, tenantField: string | null, tenantId: string | null, parentTrx?: Knex.Transaction, scope = '', suffix = ''): Promise { // Pass the caller's transaction so a cold-cache first write inside a batch // transaction ensures the table on the right connection instead of dead- // locking on a second one (SQLite pool max=1). `initObjects` normally warms @@ -129,52 +130,128 @@ export async function getNextSequenceValue(this: Pick { - // Lock the row (no-op on SQLite, real lock on Postgres/MySQL). - // - // Speculative, so it runs under a savepoint: `.forUpdate()` on a MISSING - // row does NOT throw on Postgres (measured: returns zero rows), so the - // fallback below is unreachable for the reason the old comment gave. It - // IS reachable for lock-level failures — deadlock (40P01), lock/statement - // timeout (55P03/57014) — and without the savepoint each of those turned - // into a `25P02` from the fallback SELECT, masking the real error. - let existing: any; - const locked = await this.attemptWithoutPoisoning(trx, (scoped) => - scoped(SEQUENCES_TABLE).where(key).forUpdate().first(), - ); - if (locked.ok) { - existing = locked.value; - } else { - // Fall back to a plain SELECT then rely on transaction isolation. - existing = await trx(SEQUENCES_TABLE).where(key).first(); - } + // ## The cold seed is idempotent and comes BEFORE the locking read (#31608) + // + // The seed used to be speculative: `SELECT … FOR UPDATE` on the missing + // row, then an INSERT, recovering from the loser's unique violation. On + // MySQL 8 (InnoDB, REPEATABLE READ) that order deadlocks by construction — + // measured: the locking read on a missing key takes a next-key lock on the + // gap (`lock_mode X` on the supremum), gap locks do not conflict with each + // other, so every cold writer holds one, and each INSERT then waits on the + // others' gap lock for its insert intention. InnoDB answers + // `ER_LOCK_DEADLOCK` and rolls back the victim's WHOLE transaction, not to + // the savepoint (`ROLLBACK TO SAVEPOINT` then answers + // `ER_SP_DOES_NOT_EXIST`, which knex's MySQL client swallows). The recovery + // statements ran on regardless, in autocommit: the `FOR UPDATE` lock ended + // with its own statement, and + // every victim read the winner's counter and wrote the same `last_value + 1` + // — a lost update, issued as duplicate numbers. + // + // So: a plain read decides whether the 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; and 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`. The conflict target is + // left out on purpose: `ON CONFLICT (cols)` raises `42P10` against the + // interim four-column key an incomplete `ensureSequencesKeyHashShape` + // migration leaves (see `attemptWithoutPoisoning`); the bare form matches + // whichever unique key the table has. + // - MySQL: a no-op `ON DUPLICATE KEY UPDATE`, NOT `INSERT IGNORE`. Measured + // on 8.0 at 16 cold writers: `INSERT IGNORE` takes a SHARED lock on the + // duplicate, two losers holding it each wait to upgrade it for the + // `FOR UPDATE` below, and InnoDB rolls one back (8 to 14 deadlocks a + // burst). `ON DUPLICATE KEY UPDATE` takes the EXCLUSIVE lock at once, so + // the losers queue behind the seeder: 0 deadlocks. It also leaves every + // other error loud, where `IGNORE` downgrades them to warnings. + const issue = (): Promise => + runner.transaction(async (trx) => { + const present = await trx(SEQUENCES_TABLE).where(key).first(); + if (!present) { + const seedMax = await this.scanMaxNumericTail( + trx, + tableName, + field, + prefix, + tenantField, + resolvedTenantId === GLOBAL_TENANT ? null : resolvedTenantId, + suffix, + ); + const seed = trx(SEQUENCES_TABLE).insert({ ...insertRow, last_value: seedMax }).onConflict(); + await (this.isMysql ? seed.merge({ object: trx.ref('object') }) : seed.ignore()); + } - if (!existing) { - const seedMax = await this.scanMaxNumericTail( - trx, - tableName, - field, - prefix, - tenantField, - resolvedTenantId === GLOBAL_TENANT ? null : resolvedTenantId, - suffix, - ); - const initial = seedMax + 1; - const inserted = await this.attemptWithoutPoisoning(trx, (scoped) => - scoped(SEQUENCES_TABLE).insert({ ...insertRow, last_value: initial }), + // Lock the row (no-op on SQLite, real lock on Postgres/MySQL). + // + // Under a savepoint, so a lock-level failure on Postgres — deadlock + // (40P01), lock/statement timeout (55P03/57014) — does not turn into a + // `25P02` from the fallback SELECT and mask the real error. A failure + // that rolled back the whole transaction has no fallback: nothing the + // SELECT below reads would be locked any more, and its UPDATE would + // autocommit outside any transaction. + let existing: any; + const locked = await this.attemptWithoutPoisoning(trx, (scoped) => + scoped(SEQUENCES_TABLE).where(key).forUpdate().first(), ); - if (inserted.ok) return initial; - // Another writer raced us to the first INSERT. Fall through to - // the UPDATE path with the now-present row. This `SELECT … FOR UPDATE` - // blocks until the winner commits, so it sees the committed counter. - existing = await trx(SEQUENCES_TABLE).where(key).forUpdate().first(); - if (!existing) throw inserted.error; + if (locked.ok) { + existing = locked.value; + } else { + if (rollsBackWholeTransaction(locked.error)) throw locked.error; + // Fall back to a plain SELECT then rely on transaction isolation. + existing = await trx(SEQUENCES_TABLE).where(key).first(); + } + if (!existing) { + throw new Error( + `Cannot issue autonumber "${object}.${field}": its counter row in ${SEQUENCES_TABLE} ` + + `was seeded but is gone (deleted while this number was being issued).`, + ); + } + + const next = Number(existing.last_value) + 1; + await trx(SEQUENCES_TABLE).where(key).update({ last_value: next, updated_at: this.knex.fn.now() }); + return next; + }); + + // ⛔ Never retried inside a caller's transaction: the deadlock already rolled + // that transaction back, and the caller's earlier writes with it, so + // anything issued after it would autocommit outside the caller's unit of + // work. The caller gets the driver's own error to retry its whole unit. + if (parentTrx) return issue(); + return issueOwningTransaction(issue); +} + +/** + * How many times an issue the driver owns the transaction of is attempted when + * the server rolled that transaction back. Each retry starts from nothing, so + * it cannot double-issue; the bound only keeps a pathological lock storm from + * spinning forever, and then the server's own error is what surfaces. + */ +const WHOLE_ISSUE_ATTEMPTS = 5; + +/** Run `issue` (a whole transaction the driver owns), again while the server rolls it back. */ +async function issueOwningTransaction(issue: () => Promise): Promise { + for (let attempt = 1; ; attempt++) { + try { + return await issue(); + } catch (error) { + if (attempt >= WHOLE_ISSUE_ATTEMPTS || !rollsBackWholeTransaction(error)) throw error; } + } +} - const next = Number(existing.last_value) + 1; - await trx(SEQUENCES_TABLE).where(key).update({ last_value: next, updated_at: this.knex.fn.now() }); - return next; - }); +/** + * Did the server roll back the WHOLE transaction, savepoints included? + * + * MySQL's `ER_LOCK_DEADLOCK` (errno 1213) does (measured on 8.0: a later + * `ROLLBACK TO SAVEPOINT` answers `ER_SP_DOES_NOT_EXIST`, and later statements + * autocommit). knex's MySQL client swallows that savepoint error and rejects + * with the deadlock itself, so the deadlock is what reaches this check. Postgres's deadlock (`40P01`) and lock timeouts abort only the + * current savepoint, which `attemptWithoutPoisoning` already recovers, so they + * are not this class and keep their existing handling. + */ +function rollsBackWholeTransaction(error: unknown): boolean { + const e = error as { code?: unknown; errno?: unknown } | null; + return !!e && (e.code === 'ER_LOCK_DEADLOCK' || e.errno === 1213); } /** The body of `SqlDriver#fillAutoNumberFields`; the method's docblock there is its contract. */ diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index fdfc8f83036..9ba8b0dc9c4 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -2322,9 +2322,11 @@ export class SqlDriver implements IDataDriver { // [#25521 cut 11] The body moved to `sql-driver-autonumber.ts` (see `AutonumberHost`). const readKnex = () => this.knex; const readSequencesHasKeyHash = () => this.sequencesHasKeyHash; + const readIsMysql = () => this.isMysql; const host: ThisParameterType = { attemptWithoutPoisoning: (...a) => this.attemptWithoutPoisoning(...a), ensureSequencesTable: (...a) => this.ensureSequencesTable(...a), + get isMysql() { return readIsMysql(); }, get knex() { return readKnex(); }, resolveSequenceTenantId: (...a) => this.resolveSequenceTenantId(...a), scanMaxNumericTail: (...a) => this.scanMaxNumericTail(...a),