From 6bdb737af89e8cb00b56e297821900bae053578a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:34:55 +0000 Subject: [PATCH 1/5] fix(objectql): a predicate delete with a cascade locks its matched rows inside the unit of work The cascade arm reads the matched ids, walks the cascade, then deletes by id, so the caller's predicate never reaches the DELETE. Inside the unit of work, a driver declaring the new DriverCapabilities.lockRows now takes that read with the new DriverOptions.lockRows (SELECT ... FOR UPDATE in driver-sql), so no concurrent commit can move a matched row out of the predicate before the delete. Claude-Session: https://claude.ai/code/session_01ADHkmRukLEFGv24PSBTaHb Co-authored-by: Claude --- .../drivers/driver-sql/src/sql-driver-crud.ts | 21 +++++++- packages/drivers/driver-sql/src/sql-driver.ts | 7 +++ .../src/engine-delete-and-aggregate.ts | 17 +++++- packages/spec/src/data/driver.test.ts | 28 +++++++++- packages/spec/src/data/driver.zod.ts | 54 +++++++++++++++++++ 5 files changed, 122 insertions(+), 5 deletions(-) diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 4303b18518f..525653f80ee 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -41,6 +41,23 @@ import { import type { SqlDriver } from './sql-driver.js'; import { oracleUuidReadForm } from './sql-driver-oracle-dialect.js'; +/** + * [`DriverOptions.lockRows`] Lock the rows a `find()` returns until its + * transaction ends, the promise `supports.lockRows` makes for this driver. + * + * Only with a `transaction`: a read outside one has nothing to hold the lock + * to (on PostgreSQL a bare `FOR UPDATE` releases at the statement's own + * implicit commit), so the key is ignored there. knex compiles `forUpdate()` + * per dialect: `FOR UPDATE` on PostgreSQL, MySQL and Oracle, the `UPDLOCK` + * table hint on SQL Server, and nothing at all on SQLite, whose single-connection + * pool and database lock already keep a concurrent commit out of an open + * transaction (the capability's TSDoc in `data/driver.zod.ts`). + */ +function lockRowsIfAsked(builder: Knex.QueryBuilder, options?: DriverOptions): Knex.QueryBuilder { + if (options?.lockRows === true && options.transaction) return builder.forUpdate(); + return builder; +} + /** * The `SqlDriver` members the bodies of {@link CrudFacet} read — every one of * them, and no other. Each is typed AS the class member (an indexed access on @@ -169,12 +186,12 @@ export class CrudFacet { if (window.offset !== null) b.offset(window.offset); const rows = window.top ?? window.fetch; if (rows !== null) b.limit(rows); - return b; + return lockRowsIfAsked(b, options); } if (query.offset !== undefined) b.offset(query.offset); if (query.limit !== undefined) b.limit(query.limit); - return b; + return lockRowsIfAsked(b, options); }; const builder = buildBase(); diff --git a/packages/drivers/driver-sql/src/sql-driver.ts b/packages/drivers/driver-sql/src/sql-driver.ts index 806e2c46c22..b32d25d8bd8 100644 --- a/packages/drivers/driver-sql/src/sql-driver.ts +++ b/packages/drivers/driver-sql/src/sql-driver.ts @@ -393,6 +393,13 @@ export class SqlDriver implements IDataDriver { // collation's, as for this datasource's `where` (the latitude the bit's // TSDoc in `data/driver.zod.ts` states, measured dialects named there). aggregationFilter: true, + // `find()` honours `DriverOptions.lockRows` inside a transaction (see + // `lockRowsIfAsked` in `sql-driver-crud.ts`): `FOR UPDATE` / `UPDLOCK`, + // and on SQLite the single-connection pool and the database lock. A + // subclass whose transport takes no transaction handle (TursoDriver's + // remote mode, `transactionsUnsupported`) is never sent the key: the + // engine sends it only inside a transaction. + lockRows: true, }; } diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 7c7aad63c3f..e907c48179f 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -750,11 +750,26 @@ export class DeleteAndAggregateFacet { // as the by-id branch deletes its id after reading its // pre-image under that scope. The unit of work is the by-id // branch's, for the same reasons (#7413). + // + // [#34373] Deleting by id keeps the caller's predicate off the + // final statement, so the read is where the predicate has to + // keep holding: a concurrent commit that moved a matched row + // out of it ("delete only if still pending") between this read + // and the delete would otherwise be deleted anyway, and counted. + // Inside the unit of work, a driver that declares + // `supports.lockRows` takes the read with `lockRows`, so no + // other writer commits a change to a matched row until the + // unit ends. A driver without the bit, or no open transaction + // (the `'split'` plan, a driver with no transactions), reads + // unlocked and keeps that window (`DriverCapabilities.lockRows`). const runPredicateDelete = async (writeContext?: ExecutionContext): Promise => { const writeOptions = this.buildDriverOptions(object, writeContext, hookContext.input.options as any); + const readOptions = writeOptions?.transaction != null && driver.supports?.lockRows === true + ? { ...writeOptions, lockRows: true } + : writeOptions; // [#27581] The same read carries the secret columns, so the // handles released are those of the rows deleted. - const matched = ((await driver.find(object, { ...opCtx.ast!, fields: ['id', ...summaryKeyColumns, ...secretColumns] }, writeOptions)) ?? []) as Array>; + const matched = ((await driver.find(object, { ...opCtx.ast!, fields: ['id', ...summaryKeyColumns, ...secretColumns] }, readOptions)) ?? []) as Array>; const matchedIds = matched.map((row) => row?.id).filter((v): v is string | number => v != null); if (summaryKeyColumns.length > 0) summaryPriorRows = withoutDeletedSelfParents(object, matched, matchedIds, this.getSummaryDescriptors(object)); deletedSecrets = deletedSecretSlots(deleteSchema, matched); diff --git a/packages/spec/src/data/driver.test.ts b/packages/spec/src/data/driver.test.ts index fe9a8032e73..4146ec6896d 100644 --- a/packages/spec/src/data/driver.test.ts +++ b/packages/spec/src/data/driver.test.ts @@ -61,6 +61,9 @@ const RETIRED_BITS = [ * * `aggregationFilter` is the fifth, under the same rule: `engine.aggregate` * reads it (with method presence) to send a per-measure filter to the driver. + * + * `lockRows` is the sixth: a predicate delete's cascade arm reads it (with an + * open transaction) to send its matched-row read with `DriverOptions.lockRows`. */ const LIVE_BITS = [ 'queryDateGranularity', @@ -68,6 +71,7 @@ const LIVE_BITS = [ 'batchSchemaSync', 'transactionsUnsupported', 'aggregationFilter', + 'lockRows', ] as const; describe('DriverCapabilitiesSchema', () => { @@ -78,6 +82,7 @@ describe('DriverCapabilitiesSchema', () => { batchSchemaSync: true, transactionsUnsupported: true, aggregationFilter: true, + lockRows: true, }; expect(() => DriverCapabilitiesSchema.parse(capabilities)).not.toThrow(); @@ -95,13 +100,19 @@ describe('DriverCapabilitiesSchema', () => { expect(parsed).not.toHaveProperty('transactionsUnsupported'); // Absent = the engine aggregates a filtered measure in memory, as before the bit. expect(parsed).not.toHaveProperty('aggregationFilter'); + // Absent = the engine sends no lock request with a predicate delete's read. + expect(parsed).not.toHaveProperty('lockRows'); }); it('refuses a non-boolean aggregationFilter', () => { expect(DriverCapabilitiesSchema.safeParse({ aggregationFilter: 'yes' }).success).toBe(false); }); - it('declares exactly the audited shape: 5 live bits + 31 tombstones', () => { + it('refuses a non-boolean lockRows', () => { + expect(DriverCapabilitiesSchema.safeParse({ lockRows: 'yes' }).success).toBe(false); + }); + + it('declares exactly the audited shape: 6 live bits + 31 tombstones', () => { const shape = (DriverCapabilitiesSchema as unknown as { shape: Record }).shape; const keys = Object.keys(shape).sort(); expect(keys).toEqual([...RETIRED_BITS, ...LIVE_BITS].slice().sort()); @@ -202,7 +213,7 @@ describe('tsc channel: the retired bits are unwritable in DriverCapabilities', ( const props = new Map(capsType.getProperties().map((p) => [p.getName(), p])); // Anti-vacuity: the walked shape is the audited key set — 31 tombstones - // plus the live bits (5 since `aggregationFilter`). + // plus the live bits (6 since `lockRows`). expect([...props.keys()].sort()).toEqual([...RETIRED_BITS, ...LIVE_BITS].slice().sort()); const decl = capsAlias!.declarations?.[0]; @@ -465,3 +476,16 @@ describe('driverSupportsTransactions — a driver that cannot honour transaction expect(driverSupportsTransactions({ ...withMethod, supports: { transactionsUnsupported: undefined } })).toBe(true); }); }); + +// `DriverOptions.lockRows` — the lock request a predicate delete's matched-row +// read carries to a driver declaring `supports.lockRows`. A declared key, so the +// engine's closed driver-option hop (`pickDeclaredDriverOptions`) passes it. +describe('DriverOptions.lockRows', () => { + it('keeps a boolean lockRows', () => { + expect(DriverOptionsSchema.parse({ lockRows: true }).lockRows).toBe(true); + }); + + it('refuses a non-boolean lockRows', () => { + expect(DriverOptionsSchema.safeParse({ lockRows: 'yes' }).success).toBe(false); + }); +}); diff --git a/packages/spec/src/data/driver.zod.ts b/packages/spec/src/data/driver.zod.ts index 7c7871df30a..51e27cb508d 100644 --- a/packages/spec/src/data/driver.zod.ts +++ b/packages/spec/src/data/driver.zod.ts @@ -111,6 +111,25 @@ export const DriverOptionsSchema = lazySchema(() => z.object({ * rows a write touches. */ bypassTenantAudit: z.boolean().optional().describe('Suppress the driver tenant-audit warning for a deliberately global write on a tenant-scoped object (diagnostics only — never changes what the write touches)'), + + /** + * Lock the rows a read returns against concurrent writers until the + * `transaction` it runs in ends (SQL `SELECT … FOR UPDATE`). + * + * Meaningful on `find()` only, and only with `transaction` set: a read + * outside a transaction has nothing to hold the lock to, so a driver ignores + * the key there. A driver honours it only when it declares + * `DriverCapabilities.lockRows`, and the engine sends it only to such a + * driver. + * + * The engine's one sender is a predicate delete whose target is referenced by + * delete-family lookups: it reads the matched ids, walks the cascade, then + * deletes those rows by id. Under the lock no concurrent commit can move a + * matched row out of the caller's predicate between that read and the + * delete, so a guard such as "delete only if still pending" holds for the + * whole unit of work. + */ + lockRows: z.boolean().optional().describe('find() inside a transaction: lock the returned rows against concurrent writers until the transaction ends (SELECT … FOR UPDATE); honoured only by a driver declaring supports.lockRows'), })); /** @@ -160,6 +179,9 @@ const capRemoved = (key: string, mechanism: string) => * `aggregate()`: the engine ANDs it with method presence, because a driver * can carry `aggregate()` without compiling that key (and a subclass can * inherit a compiler its own transport refuses). + * - `lockRows` — opt-IN for `DriverOptions.lockRows` on `find()`: the engine + * sends the lock request on a predicate delete's matched-row read only when + * the bit is set and the read runs inside a transaction. * * Everything else IS the method: aggregate pushdown gates on * `typeof driver.aggregate === 'function'`, schema sync on @@ -338,6 +360,38 @@ export const DriverCapabilitiesSchema = lazySchema(() => z.object({ */ aggregationFilter: z.boolean().optional().describe('`aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine\'s in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory)'), + /** + * This driver's `find()` honours `DriverOptions.lockRows` inside a + * transaction. + * + * The promise: when `find()` runs with both `transaction` and `lockRows` + * set, no other writer can commit a change to a row that read returned + * until that transaction ends. The writer waits, or one side fails loudly; + * it never commits in between. PostgreSQL and MySQL take row locks + * (`FOR UPDATE`), SQL Server an update lock (`UPDLOCK`). SQLite has no row + * locks and needs none: `driver-sql`'s pool holds one connection, so a + * second writer through this driver waits for it, and a writer in another + * process meets the database lock (busy) rather than slipping a commit + * between the read and the transaction's own write. + * + * What the engine does with it: a predicate delete on an object that + * delete-family lookups reference reads the matched ids inside the unit of + * work, walks the cascade, and deletes those rows by id. With the bit set it + * sends that read with `lockRows`, so the caller's predicate cannot stop + * holding for a matched row before the delete. Without it, or outside a + * transaction (the `'split'` cascade plan, or a driver with no + * transactions), the read takes no lock and a concurrent commit between the + * read and the delete is not seen: the memory, MongoDB and OData drivers + * keep that window. + * + * Why a bit and not the option alone: an option a driver silently ignores is + * a lock the engine believes it holds and does not. The bit is the driver's + * promise; the engine ANDs it with the open transaction. + * + * Optional; absence means `false`, like `batchSchemaSync`. + */ + lockRows: z.boolean().optional().describe('`find()` honours `DriverOptions.lockRows` inside a transaction: no concurrent commit changes a returned row until the transaction ends (absence = false: the engine sends no lock request)'), + // ============================================================================ // Retired capability bits (#4634, ADR-0049 enforce-or-remove) — 17.0.0 // ============================================================================ From 03d36aef427a61e6a155f90882fe8c0200a25e81 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:41:12 +0000 Subject: [PATCH 2/5] fix(objectql): refuse a lockRows the engine cannot honour; pin the cascade arm's locked read Claude-Session: https://claude.ai/code/session_01ADHkmRukLEFGv24PSBTaHb Co-authored-by: Claude --- .../drivers/driver-sql/src/sql-driver-crud.ts | 39 ++++-- .../src/engine-cascade-delete-atomic.test.ts | 114 +++++++++++++++++- .../objectql/src/engine-driver-options.ts | 19 ++- packages/objectql/src/engine.ts | 1 + .../objectql/src/lock-rows-refusal-error.ts | 54 +++++++++ packages/spec/authorable-surface/data.json | 2 + packages/spec/src/data/driver.zod.ts | 13 +- 7 files changed, 220 insertions(+), 22 deletions(-) create mode 100644 packages/objectql/src/lock-rows-refusal-error.ts diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 525653f80ee..8578cbffdb8 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -40,22 +40,37 @@ import { } from './sql-driver-top-level.js'; import type { SqlDriver } from './sql-driver.js'; import { oracleUuidReadForm } from './sql-driver-oracle-dialect.js'; +import { StandardErrorCode } from '@objectstack/spec/api'; /** * [`DriverOptions.lockRows`] Lock the rows a `find()` returns until its * transaction ends, the promise `supports.lockRows` makes for this driver. * - * Only with a `transaction`: a read outside one has nothing to hold the lock - * to (on PostgreSQL a bare `FOR UPDATE` releases at the statement's own - * implicit commit), so the key is ignored there. knex compiles `forUpdate()` - * per dialect: `FOR UPDATE` on PostgreSQL, MySQL and Oracle, the `UPDLOCK` - * table hint on SQL Server, and nothing at all on SQLite, whose single-connection - * pool and database lock already keep a concurrent commit out of an open - * transaction (the capability's TSDoc in `data/driver.zod.ts`). + * knex compiles `forUpdate()` per dialect: `FOR UPDATE` on PostgreSQL, MySQL + * and Oracle, the `UPDLOCK` table hint on SQL Server, and nothing at all on + * SQLite, whose single-connection pool and database lock already keep a + * concurrent commit out of an open transaction (the capability's TSDoc in + * `data/driver.zod.ts`). + * + * A request with no `transaction` is refused, PRECONDITION_REQUIRED / 428: a + * read outside a transaction has nothing to hold the lock to (on PostgreSQL a + * bare `FOR UPDATE` releases at the statement's own implicit commit), and + * answering it as if the rows were locked is the one wrong answer. The engine + * refuses the same request before it reaches a driver; this is the answer a + * direct caller gets. */ -function lockRowsIfAsked(builder: Knex.QueryBuilder, options?: DriverOptions): Knex.QueryBuilder { - if (options?.lockRows === true && options.transaction) return builder.forUpdate(); - return builder; +function lockRowsIfAsked(builder: Knex.QueryBuilder, object: string, options?: DriverOptions): Knex.QueryBuilder { + if (options?.lockRows !== true) return builder; + if (!options.transaction) { + const err = new Error( + `Cannot lock the rows of "${object}" outside a transaction: a row lock is held until the transaction ` + + 'ends, and this read runs in none. Pass the open transaction with lockRows, or drop lockRows.', + ) as Error & { code?: string; status?: number }; + err.code = StandardErrorCode.enum.PRECONDITION_REQUIRED; + err.status = 428; + throw err; + } + return builder.forUpdate(); } /** @@ -186,12 +201,12 @@ export class CrudFacet { if (window.offset !== null) b.offset(window.offset); const rows = window.top ?? window.fetch; if (rows !== null) b.limit(rows); - return lockRowsIfAsked(b, options); + return lockRowsIfAsked(b, object, options); } if (query.offset !== undefined) b.offset(query.offset); if (query.limit !== undefined) b.limit(query.limit); - return lockRowsIfAsked(b, options); + return lockRowsIfAsked(b, object, options); }; const builder = buildBase(); diff --git a/packages/objectql/src/engine-cascade-delete-atomic.test.ts b/packages/objectql/src/engine-cascade-delete-atomic.test.ts index 90ed383135a..c43bf9faa83 100644 --- a/packages/objectql/src/engine-cascade-delete-atomic.test.ts +++ b/packages/objectql/src/engine-cascade-delete-atomic.test.ts @@ -47,8 +47,11 @@ function recordingLogger() { * `transactional: false` omits `beginTransaction` entirely — the shape the * declared degrade (ADR-0119 D1) exists for. Every in-tree driver implements * it; test doubles and foreign engines are what reach that path. + * + * `lockRows: true` declares `supports.lockRows` (#34373): `reads` records the + * options each `find()` carried, so a pin can ask which read asked for a lock. */ -function makeDriver(opts: { transactional?: boolean } = {}) { +function makeDriver(opts: { transactional?: boolean; lockRows?: boolean } = {}) { const stores = new Map>>(); const storeFor = (o: string) => { let s = stores.get(o); @@ -61,6 +64,8 @@ function makeDriver(opts: { transactional?: boolean } = {}) { const begun: unknown[] = []; const committed: unknown[] = []; const rolledBack: unknown[] = []; + /** [#34373] Every `find()`, with the options it carried. */ + const reads: Array<{ object: string; fields: unknown; options: any }> = []; const snapshots = new Map>>>(); let nextId = 0; @@ -82,15 +87,17 @@ function makeDriver(opts: { transactional?: boolean } = {}) { const driver: any = { name: 'primary', version: '0.0.0', - supports: {}, + supports: opts.lockRows ? { lockRows: true } : {}, writes, + reads, begun, committed, rolledBack, rowsOf: (o: string) => Array.from(storeFor(o).values()), async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, async syncSchema() {}, - async find(o: string, ast: any) { + async find(o: string, ast: any, options?: any) { + reads.push({ object: o, fields: ast?.fields, options }); return Array.from(storeFor(o).values()).filter((r) => matches(r, ast?.where)); }, async findOne(o: string, ast: any) { @@ -227,7 +234,7 @@ const loner = { async function makeEngine( objects: any[], - opts: { transactional?: boolean } = {}, + opts: { transactional?: boolean; lockRows?: boolean } = {}, ) { const rec = recordingLogger(); const engine = new ObjectQL({ logger: rec.logger } as any); @@ -711,3 +718,102 @@ describe('hook firing is unchanged by the transaction wrap (#7413)', () => { expect(events.filter((e) => e === 'parent:afterDelete')).toHaveLength(0); }); }); + +// --------------------------------------------------------------------------- +// [#34373] The cascade arm deletes by id, so the read is where the caller's +// predicate has to keep holding: inside the unit of work it is taken with +// `lockRows` on a driver that declares `supports.lockRows`. A caller's own +// `lockRows` that cannot hold is refused before any driver runs. +// --------------------------------------------------------------------------- + +describe('[#34373] a predicate delete with a cascade locks the rows it walks', () => { + /** The reads of `parent` that asked for a lock. */ + const lockedReads = (driver: any) => driver.reads.filter((r: any) => r.options?.lockRows === true); + + it('reads the matched rows with lockRows, on the unit\'s own handle, when the driver declares the bit', async () => { + const { engine, driver } = await makeEngine([parent, detail, link], { lockRows: true }); + const p1 = await engine.insert('parent', { name: 'doomed' }); + const p2 = await engine.insert('parent', { name: 'doomed' }); + const kept = await engine.insert('parent', { name: 'kept' }); + await engine.insert('detail', { parent: p1.id }); + await engine.insert('link', { parent: p2.id }); + driver.reads.length = 0; + driver.writes.length = 0; + + const removed = await engine.delete('parent', { where: { name: 'doomed' }, multi: true }); + + expect(removed).toBe(2); + expect(driver.rowsOf('parent').map((r: any) => r.id)).toEqual([kept.id]); + expect(driver.begun).toHaveLength(1); + const handle = driver.begun[0]; + // Exactly one read asked for a lock: the matched-row read of the root + // object, inside the unit, before any write of the walk or the delete. + const locked = lockedReads(driver); + expect(locked).toHaveLength(1); + expect(locked[0].object).toBe('parent'); + expect(locked[0].options.transaction).toBe(handle); + expect(locked[0].fields).toContain('id'); + for (const w of driver.writes) expect(w.transaction).toBe(handle); + }); + + it('sends no lock request to a driver that does not declare supports.lockRows', async () => { + const { engine, driver } = await makeEngine([parent, detail]); + const p = await engine.insert('parent', { name: 'doomed' }); + await engine.insert('detail', { parent: p.id }); + driver.reads.length = 0; + + expect(await engine.delete('parent', { where: { name: 'doomed' }, multi: true })).toBe(1); + expect(driver.begun).toHaveLength(1); + expect(lockedReads(driver)).toHaveLength(0); + }); + + it('sends no lock request when no transaction opens (a driver with no beginTransaction)', async () => { + const { engine, driver } = await makeEngine([parent, detail], { transactional: false, lockRows: true }); + const p = await engine.insert('parent', { name: 'doomed' }); + await engine.insert('detail', { parent: p.id }); + driver.reads.length = 0; + + expect(await engine.delete('parent', { where: { name: 'doomed' }, multi: true })).toBe(1); + expect(lockedReads(driver)).toHaveLength(0); + }); + + it('refuses a caller\'s lockRows on an object whose driver cannot lock: NOT_IMPLEMENTED / 501, nothing deleted', async () => { + const { engine, driver } = await makeEngine([loner]); + await engine.insert('loner', { name: 'solo' }); + driver.writes.length = 0; + + await expect(engine.delete('loner', { where: { name: 'solo' }, multi: true, lockRows: true } as any)) + .rejects.toMatchObject({ code: 'NOT_IMPLEMENTED', status: 501, object: 'loner' }); + expect(driver.rowsOf('loner')).toHaveLength(1); + expect(driver.writes).toHaveLength(0); + }); + + it('refuses a caller\'s lockRows outside a transaction: PRECONDITION_REQUIRED / 428, nothing read or deleted', async () => { + const { engine, driver } = await makeEngine([loner], { lockRows: true }); + await engine.insert('loner', { name: 'solo' }); + driver.reads.length = 0; + driver.writes.length = 0; + + await expect(engine.find('loner', { where: { name: 'solo' }, lockRows: true } as any)) + .rejects.toMatchObject({ code: 'PRECONDITION_REQUIRED', status: 428, object: 'loner' }); + await expect(engine.delete('loner', { where: { name: 'solo' }, multi: true, lockRows: true } as any)) + .rejects.toMatchObject({ code: 'PRECONDITION_REQUIRED', status: 428, object: 'loner' }); + expect(driver.reads).toHaveLength(0); + expect(driver.writes).toHaveLength(0); + expect(driver.rowsOf('loner')).toHaveLength(1); + }); + + it('hands a caller\'s lockRows inside engine.transaction() to a driver that declares the bit', async () => { + const { engine, driver } = await makeEngine([loner], { lockRows: true }); + await engine.insert('loner', { name: 'solo' }); + driver.reads.length = 0; + + const rows = await engine.transaction(async () => + engine.find('loner', { where: { name: 'solo' }, lockRows: true } as any)); + + expect(rows).toHaveLength(1); + const locked = lockedReads(driver); + expect(locked).toHaveLength(1); + expect(locked[0].options.transaction).toBe(driver.begun[0]); + }); +}); diff --git a/packages/objectql/src/engine-driver-options.ts b/packages/objectql/src/engine-driver-options.ts index 04a6025d4ed..f33f15093c6 100644 --- a/packages/objectql/src/engine-driver-options.ts +++ b/packages/objectql/src/engine-driver-options.ts @@ -81,6 +81,7 @@ import { type TenantLayer0Verdict, } from '@objectstack/spec/security'; import { isFederatedObject } from './federated-object.js'; +import { LockRowsRefusedError } from './lock-rows-refusal-error.js'; import type { ObjectQL } from './engine.js'; /** @@ -96,6 +97,7 @@ export interface DriverOptionsHost { readonly _registry: ObjectQL['_registry']; readonly tenancyPostureProvider: ObjectQL['tenancyPostureProvider']; isClosedUnitHandle: ObjectQL['isClosedUnitHandle']; + getDriver: ObjectQL['getDriver']; transactionCoversDriverFor: ObjectQL['transactionCoversDriverFor']; driverWriteTarget: ObjectQL['driverWriteTarget']; driverReadScope: ObjectQL['driverReadScope']; @@ -287,7 +289,7 @@ export function mergeDriverOptionsIntoHookView( * this helper does not mask the system path. */ export function buildDriverOptions( - this: Pick, + this: Pick, object: string, execCtx?: ExecutionContext, base?: any, @@ -356,6 +358,21 @@ export function buildDriverOptions( // `bypassTenantAudit` / `transaction` still win below), never the rest of // the bag it rode in on. See {@link pickDeclaredDriverOptions}. const declared = pickDeclaredDriverOptions(base); + // [#34373] A caller's `lockRows` is a promise it will act on, so it reaches a + // driver only where it holds: the object's driver declares + // `supports.lockRows`, and a transaction reaches that driver for the call + // (the open unit's handle, or the caller's own). Otherwise it is refused + // here, before any driver runs, rather than read unlocked in silence. See + // {@link LockRowsRefusedError}. + if (declared?.lockRows === true) { + const driver = this.getDriver(object); + if (driver?.supports?.lockRows !== true) { + throw new LockRowsRefusedError(object, 'driver-cannot-lock', driver?.name); + } + if (!hasTx && declared.transaction === undefined) { + throw new LockRowsRefusedError(object, 'no-transaction', driver.name); + } + } if (!hasTx && !hasTenant && !isSystem && !hasTz && !preserveAudit && !wallExempt) return declared; const opts: any = declared ?? {}; if (hasTx && opts.transaction === undefined) { diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 8d789a8785f..b8b7dbd9372 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -1954,6 +1954,7 @@ export class ObjectQL implements IObjectQLEngine { const readRegistry = () => this._registry; const host: ThisParameterType = { isClosedUnitHandle: (...a) => this.isClosedUnitHandle(...a), + getDriver: (...a) => this.getDriver(...a), get txStore() { return readTxStore(); }, transactionCoversDriverFor: (...a) => this.transactionCoversDriverFor(...a), get _registry() { return readRegistry(); }, diff --git a/packages/objectql/src/lock-rows-refusal-error.ts b/packages/objectql/src/lock-rows-refusal-error.ts new file mode 100644 index 00000000000..0c69a5c59d2 --- /dev/null +++ b/packages/objectql/src/lock-rows-refusal-error.ts @@ -0,0 +1,54 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The refusal of a `DriverOptions.lockRows` request the engine cannot honour. + * + * A lock request is a promise the caller acts on: "no other writer commits a + * change to these rows until my transaction ends". Handing it to a driver that + * ignores it, or sending it with no transaction to hold the lock to, would + * answer the read as if the rows were locked while they are not. So the engine + * refuses, before the driver is called, in the two shapes that cannot hold: + * + * - the object's driver does not declare `supports.lockRows`: + * `NOT_IMPLEMENTED`, 501 — this backend does not implement that declared + * capability, the answer a driver gives a spec-declared aggregate function + * it cannot compile; + * - no transaction reaches the driver for the call: `PRECONDITION_REQUIRED`, + * 428 — the lock needs a unit of work, and the request carries none. + * + * The engine's own sender (a predicate delete's matched-row read) checks both + * before it asks, so this is the answer only a caller's explicit `lockRows` + * can draw. `@objectstack/types`' error classification reads the declared + * `code` and `status`. + * + * ⛔ Not exported from the package entry: an in-process caller branches on + * `code`, which survives the dual build where `instanceof` does not. + */ +export class LockRowsRefusedError extends Error { + readonly code: 'NOT_IMPLEMENTED' | 'PRECONDITION_REQUIRED'; + readonly status: 501 | 428; + /** The same number under ADR-0112 D5's spelling. */ + readonly httpStatus: 501 | 428; + + constructor( + /** The object whose read asked for the lock. */ + public readonly object: string, + /** Why the lock cannot be held. */ + public readonly reason: 'driver-cannot-lock' | 'no-transaction', + /** The object's driver, as it names itself. */ + driverName?: string, + ) { + super( + reason === 'driver-cannot-lock' + ? `Cannot lock the rows of "${object}": its driver${driverName ? ` (${driverName})` : ''} does not ` + + 'declare supports.lockRows, so it would read them unlocked. Drop lockRows, or keep this object ' + + 'on a driver that can lock rows.' + : `Cannot lock the rows of "${object}" outside a transaction: a row lock is held until the ` + + 'transaction ends, and this read runs in none. Run it inside engine.transaction(), or drop lockRows.', + ); + this.name = 'LockRowsRefusedError'; + this.code = reason === 'driver-cannot-lock' ? 'NOT_IMPLEMENTED' : 'PRECONDITION_REQUIRED'; + this.status = reason === 'driver-cannot-lock' ? 501 : 428; + this.httpStatus = this.status; + } +} diff --git a/packages/spec/authorable-surface/data.json b/packages/spec/authorable-surface/data.json index f99d4facb2d..9ae69f7d795 100644 --- a/packages/spec/authorable-surface/data.json +++ b/packages/spec/authorable-surface/data.json @@ -200,6 +200,7 @@ "data/DriverCapabilities:joins [RETIRED]", "data/DriverCapabilities:jsonFields [RETIRED]", "data/DriverCapabilities:jsonQuery [RETIRED]", + "data/DriverCapabilities:lockRows", "data/DriverCapabilities:migrations [RETIRED]", "data/DriverCapabilities:preparedStatements [RETIRED]", "data/DriverCapabilities:queryAggregations [RETIRED]", @@ -230,6 +231,7 @@ "data/DriverDefinition:id", "data/DriverDefinition:label", "data/DriverOptions:bypassTenantAudit", + "data/DriverOptions:lockRows", "data/DriverOptions:preserveAudit", "data/DriverOptions:skipCache", "data/DriverOptions:tenantId", diff --git a/packages/spec/src/data/driver.zod.ts b/packages/spec/src/data/driver.zod.ts index 51e27cb508d..fb1ba1d723f 100644 --- a/packages/spec/src/data/driver.zod.ts +++ b/packages/spec/src/data/driver.zod.ts @@ -116,11 +116,14 @@ export const DriverOptionsSchema = lazySchema(() => z.object({ * Lock the rows a read returns against concurrent writers until the * `transaction` it runs in ends (SQL `SELECT … FOR UPDATE`). * - * Meaningful on `find()` only, and only with `transaction` set: a read - * outside a transaction has nothing to hold the lock to, so a driver ignores - * the key there. A driver honours it only when it declares - * `DriverCapabilities.lockRows`, and the engine sends it only to such a - * driver. + * A request on the rows a read returns (`find()`, `findOne()`), and only + * with `transaction` set: a read outside a transaction has nothing to hold + * the lock to. A driver honours it only when it declares + * `DriverCapabilities.lockRows`. The engine never answers a request it + * cannot honour as if the rows were locked: a caller's `lockRows` on an + * object whose driver lacks the bit is refused `NOT_IMPLEMENTED` (501), and + * one with no transaction reaching that driver `PRECONDITION_REQUIRED` + * (428), before any driver runs. * * The engine's one sender is a predicate delete whose target is referenced by * delete-family lookups: it reads the matched ids, walks the cascade, then From 65322975e9cf79501f39af203ce944dbd2fa0357 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:47:56 +0000 Subject: [PATCH 3/5] test(driver-sql): pin lockRows per dialect; measured SQLite two-connection answers Claude-Session: https://claude.ai/code/session_01ADHkmRukLEFGv24PSBTaHb Co-authored-by: Claude --- .../34373-predicate-delete-lock-rows.md | 21 ++ .../src/sql-driver-34373-lock-rows.test.ts | 222 ++++++++++++++++++ .../drivers/driver-sql/src/sql-driver-crud.ts | 6 +- .../src/engine-cascade-delete-atomic.test.ts | 52 ++-- packages/spec/src/data/driver.zod.ts | 36 +-- 5 files changed, 298 insertions(+), 39 deletions(-) create mode 100644 .changeset/34373-predicate-delete-lock-rows.md create mode 100644 packages/drivers/driver-sql/src/sql-driver-34373-lock-rows.test.ts diff --git a/.changeset/34373-predicate-delete-lock-rows.md b/.changeset/34373-predicate-delete-lock-rows.md new file mode 100644 index 00000000000..63507d76164 --- /dev/null +++ b/.changeset/34373-predicate-delete-lock-rows.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': minor +'@objectstack/objectql': patch +'@objectstack/driver-sql': patch +--- + +fix(spec, objectql, driver-sql): a predicate delete with a cascade locks the rows it walks, so a concurrent commit cannot move one out of the predicate before the delete (#34373) + +Clause-②: yes (widening: DriverOptions.lockRows and DriverCapabilities.lockRows) +Metadata-protocol: added + +**The defect.** A predicate delete (`delete(object, { where, multi: true })`, a flow's `delete_record` with `multi: true`) on an object that delete-family lookups reference reads the matched ids, walks the cascade, then deletes those rows by id. The caller's predicate is not on the final DELETE, so a guard such as `{ id, source: 'idp_pending' }` ("delete only if still pending") held only at the read: a concurrent commit that moved the row out of the predicate between the read and the delete was deleted anyway, and counted. + +**The fix.** Inside the delete's unit of work, the matched-row read now takes a lock on a driver that can lock, so no other writer can change a matched row behind the unit: it waits until the unit ends, or one side fails. The rows deleted are still exactly the rows walked; nothing changes for a delete that meets no concurrent writer. + +- `DriverOptions` (`@objectstack/spec/data`) gains `lockRows`: on a read inside a `transaction`, lock the returned rows against concurrent writers until the transaction ends (SQL `SELECT … FOR UPDATE`). +- `DriverCapabilities` gains `lockRows`: the driver's `find()` honours that option. Absence means `false`, and the engine sends no lock request to such a driver. +- `driver-sql` declares the bit. PostgreSQL and MySQL take row locks (`FOR UPDATE`), SQL Server an update lock (`UPDLOCK`). SQLite compiles nothing: its single-connection pool and database lock already keep another writer from changing a returned row behind the transaction. A second writer through the same driver waits; one on another connection either fails `SQLITE_BUSY` (rollback journal) or commits and makes the transaction's own delete fail `SQLITE_BUSY_SNAPSHOT` (WAL), so the moved row is never deleted. A `find()` with `lockRows` and no transaction is refused `PRECONDITION_REQUIRED` / 428. +- The engine's read and delete verbs do not take `lockRows` from a caller (an option they do not execute, as before). Any other option bag that carries it to the engine's driver hop is refused there, before any driver runs: an object whose driver does not declare the bit answers `NOT_IMPLEMENTED` / 501, and a request with no transaction reaching that driver `PRECONDITION_REQUIRED` / 428. + +**What keeps the window.** A driver without the bit (memory, MongoDB, OData), and a cascade that cannot run in one transaction (the `split` plan, a driver with no transactions), read unlocked as before. diff --git a/packages/drivers/driver-sql/src/sql-driver-34373-lock-rows.test.ts b/packages/drivers/driver-sql/src/sql-driver-34373-lock-rows.test.ts new file mode 100644 index 00000000000..4c69f73c18a --- /dev/null +++ b/packages/drivers/driver-sql/src/sql-driver-34373-lock-rows.test.ts @@ -0,0 +1,222 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #34373 — `DriverOptions.lockRows` on `find()`, the promise + * `supports.lockRows` makes for this driver: inside a transaction, no other + * writer commits a change to a row the read returned until that transaction + * ends. + * + * The engine's sender is a predicate delete on an object that delete-family + * lookups reference: it reads the matched ids, walks the cascade, then deletes + * those rows by id, so the caller's predicate ("delete only if still pending") + * is not on the final DELETE. Without the lock a concurrent commit between the + * read and the delete moves the row out of the predicate and the row is + * deleted anyway. These pins hold the driver half of that, per dialect: + * + * - **PostgreSQL / MySQL** take row locks (`FOR UPDATE`). Two orders, both + * measured live: a writer that comes AFTER the locked read waits until the + * reader's transaction ends; a writer that holds the row BEFORE the read makes + * the read wait, and the read then answers the committed row as the writer + * left it, so a row moved out of the predicate is not returned. + * - **SQLite** has no row lock and compiles `forUpdate()` to nothing. Its + * promise is kept by the database: a writer in another connection that + * commits between the read and the transaction's own write makes that write + * fail (busy), never succeed over the moved row. Measured on a file database + * with two drivers. + * - **Every dialect**: a lock request with no transaction is refused, + * `PRECONDITION_REQUIRED` / 428, rather than read unlocked. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { SqlDriver } from '../src/index.js'; +import { DIALECT_CELLS, declareDialectCell, type DialectCell } from './live-dialect-matrix.testkit.js'; + +const TABLE = 'os34373_lock_rows'; +const SHAPE = { name: TABLE, fields: { status: { type: 'string' } } } as any; +/** Long enough for a writer that is NOT blocked to finish on any measured cell. */ +const SETTLE_MS = 400; + +/** A promise's state, read without awaiting it. */ +function track(p: Promise) { + const state = { settled: false, value: undefined as T | undefined, error: undefined as unknown }; + const done = p.then( + (v) => { state.settled = true; state.value = v; return v; }, + (e) => { state.settled = true; state.error = e; throw e; }, + ); + return { state, done }; +} + +const pause = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +describe('sql-driver — lockRows without a transaction is refused (#34373)', () => { + let driver: SqlDriver; + beforeEach(async () => { + driver = new SqlDriver(DIALECT_CELLS[0]!.config()); + await driver.initObjects([SHAPE]); + await driver.create(TABLE, { id: 'r1', status: 'pending' }); + }); + afterEach(async () => { await driver.disconnect(); }); + + it('declares supports.lockRows', () => { + expect(driver.supports.lockRows).toBe(true); + }); + + it('answers PRECONDITION_REQUIRED / 428 and reads nothing', async () => { + await expect(driver.find(TABLE, { where: { status: 'pending' } }, { lockRows: true })) + .rejects.toMatchObject({ code: 'PRECONDITION_REQUIRED', status: 428 }); + await expect(driver.findOne(TABLE, { where: { id: 'r1' } }, { lockRows: true })) + .rejects.toMatchObject({ code: 'PRECONDITION_REQUIRED', status: 428 }); + }); + + it('inside a transaction answers the same rows a plain read does', async () => { + const trx = await driver.beginTransaction(); + try { + const locked = await driver.find(TABLE, { where: { status: 'pending' }, fields: ['id'] }, { transaction: trx, lockRows: true }); + expect(locked.map((r) => r.id)).toEqual(['r1']); + } finally { + await driver.commit(trx); + } + }); +}); + +function rowLockSuite(cell: DialectCell) { + describe(`sql-driver — lockRows takes row locks (${cell.label}) [#34373]`, () => { + let driver: SqlDriver; + /** A second driver: its own pool, so its writes are another session's. */ + let writer: SqlDriver; + + beforeEach(async () => { + driver = new SqlDriver(cell.config()); + writer = new SqlDriver(cell.config()); + await driver.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await driver.initObjects([SHAPE]); + await writer.initObjects([SHAPE]); + await driver.create(TABLE, { id: 'r1', status: 'pending' }); + }); + + afterEach(async () => { + await driver.execute(`drop table if exists ${TABLE}`).catch(() => {}); + await writer.disconnect(); + await driver.disconnect(); + }); + + it('a writer after the locked read waits until the reader commits, then finds the row gone', async () => { + const trx = await driver.beginTransaction(); + const matched = await driver.find(TABLE, { where: { status: 'pending' }, fields: ['id'] }, { transaction: trx, lockRows: true }); + expect(matched.map((r) => r.id)).toEqual(['r1']); + + // The concurrent commit the card describes: move the row out of the + // predicate between the read and the delete. + const move = track(writer.update(TABLE, 'r1', { status: 'active' })); + await pause(SETTLE_MS); + expect(move.state.settled, 'the writer must wait for the locked row').toBe(false); + + const removed = await driver.deleteMany(TABLE, { object: TABLE, where: { id: { $in: ['r1'] } } } as any, { transaction: trx }); + expect(removed).toBe(1); + await driver.commit(trx); + + // The writer ran after the delete committed: the row it meant to move + // is gone, so nothing was deleted out of the predicate. + await move.done.catch(() => undefined); + expect(await writer.findOne(TABLE, { where: { id: 'r1' } })).toBeNull(); + }, 60_000); + + it('a read behind a writer that holds the row waits, then does not return a row moved out of the predicate', async () => { + const wtrx = await writer.beginTransaction(); + await writer.update(TABLE, 'r1', { status: 'active' }, { transaction: wtrx }); + + const trx = await driver.beginTransaction(); + const read = track(driver.find(TABLE, { where: { status: 'pending' }, fields: ['id'] }, { transaction: trx, lockRows: true })); + await pause(SETTLE_MS); + expect(read.state.settled, 'the locked read must wait for the writer').toBe(false); + + await writer.commit(wtrx); + const matched = await read.done; + // Re-checked against the committed row: no longer pending, not matched, + // so the delete that follows has nothing to remove. + expect(matched).toEqual([]); + await driver.commit(trx); + expect(await writer.findOne(TABLE, { where: { id: 'r1' } })).toMatchObject({ id: 'r1', status: 'active' }); + }, 60_000); + }); +} + +for (const cell of DIALECT_CELLS) { + if (cell.id === 'sqlite') continue; + declareDialectCell(cell, 'lockRows row locks (#34373)', rowLockSuite); +} + +/** + * SQLite, two drivers on one file: two connections, as two processes would + * hold. Both journal modes measured; neither lets the moved row be deleted. + */ +describe('sql-driver — lockRows on SQLite: a commit from another connection cannot slip in (#34373)', () => { + let dir: string; + let driver: SqlDriver; + let writer: SqlDriver; + + async function open(journal: 'wal' | 'delete') { + dir = mkdtempSync(join(tmpdir(), 'os34373-')); + const config = () => ({ + client: 'better-sqlite3', + connection: { filename: join(dir, 'db.sqlite') }, + useNullAsDefault: true, + sqliteJournalMode: journal, + }); + driver = new SqlDriver(config() as any); + writer = new SqlDriver(config() as any); + // `connect()` applies the journal mode, as a booted datasource does. + await driver.connect(); + await writer.connect(); + await driver.initObjects([SHAPE]); + await writer.initObjects([SHAPE]); + await driver.create(TABLE, { id: 'r1', status: 'pending' }); + const mode = await driver.execute('PRAGMA journal_mode') as Array<{ journal_mode: string }>; + expect(mode[0]?.journal_mode).toBe(journal); + } + + afterEach(async () => { + await writer.disconnect(); + await driver.disconnect(); + rmSync(dir, { recursive: true, force: true }); + }); + + it('WAL (the file default): the other connection commits, and the transaction\'s own delete is refused busy; the row is kept as moved', async () => { + await open('wal'); + const trx = await driver.beginTransaction(); + const matched = await driver.find(TABLE, { where: { status: 'pending' }, fields: ['id'] }, { transaction: trx, lockRows: true }); + expect(matched.map((r) => r.id)).toEqual(['r1']); + + try { + await writer.update(TABLE, 'r1', { status: 'active' }); + } catch (e) { + await driver.rollback(trx); + throw e; + } + await expect(driver.deleteMany(TABLE, { object: TABLE, where: { id: { $in: ['r1'] } } } as any, { transaction: trx })) + .rejects.toMatchObject({ code: 'SQLITE_BUSY_SNAPSHOT' }); + await driver.rollback(trx); + expect(await writer.findOne(TABLE, { where: { id: 'r1' } })).toMatchObject({ id: 'r1', status: 'active' }); + }, 60_000); + + it('rollback journal: the other connection\'s write is refused busy, and the transaction\'s delete stands', async () => { + await open('delete'); + const trx = await driver.beginTransaction(); + const matched = await driver.find(TABLE, { where: { status: 'pending' }, fields: ['id'] }, { transaction: trx, lockRows: true }); + expect(matched.map((r) => r.id)).toEqual(['r1']); + + // Waits out the busy timeout against the reader's lock, then fails. + try { + await expect(writer.update(TABLE, 'r1', { status: 'active' })).rejects.toMatchObject({ code: 'SQLITE_BUSY' }); + expect(await driver.deleteMany(TABLE, { object: TABLE, where: { id: { $in: ['r1'] } } } as any, { transaction: trx })).toBe(1); + } catch (e) { + await driver.rollback(trx); + throw e; + } + await driver.commit(trx); + expect(await writer.findOne(TABLE, { where: { id: 'r1' } })).toBeNull(); + }, 60_000); +}); diff --git a/packages/drivers/driver-sql/src/sql-driver-crud.ts b/packages/drivers/driver-sql/src/sql-driver-crud.ts index 8578cbffdb8..8650d66a611 100644 --- a/packages/drivers/driver-sql/src/sql-driver-crud.ts +++ b/packages/drivers/driver-sql/src/sql-driver-crud.ts @@ -48,9 +48,9 @@ import { StandardErrorCode } from '@objectstack/spec/api'; * * knex compiles `forUpdate()` per dialect: `FOR UPDATE` on PostgreSQL, MySQL * and Oracle, the `UPDLOCK` table hint on SQL Server, and nothing at all on - * SQLite, whose single-connection pool and database lock already keep a - * concurrent commit out of an open transaction (the capability's TSDoc in - * `data/driver.zod.ts`). + * SQLite, whose single-connection pool and database lock already keep another + * writer from changing a returned row behind the transaction: it waits, or one + * side fails busy (the capability's TSDoc in `data/driver.zod.ts`). * * A request with no `transaction` is refused, PRECONDITION_REQUIRED / 428: a * read outside a transaction has nothing to hold the lock to (on PostgreSQL a diff --git a/packages/objectql/src/engine-cascade-delete-atomic.test.ts b/packages/objectql/src/engine-cascade-delete-atomic.test.ts index c43bf9faa83..bc234aa49de 100644 --- a/packages/objectql/src/engine-cascade-delete-atomic.test.ts +++ b/packages/objectql/src/engine-cascade-delete-atomic.test.ts @@ -777,43 +777,55 @@ describe('[#34373] a predicate delete with a cascade locks the rows it walks', ( expect(lockedReads(driver)).toHaveLength(0); }); - it('refuses a caller\'s lockRows on an object whose driver cannot lock: NOT_IMPLEMENTED / 501, nothing deleted', async () => { - const { engine, driver } = await makeEngine([loner]); + // A caller cannot ask for the lock through the read and delete verbs: their + // option sets are closed, and `lockRows` is not on them, so it is refused as + // an option the engine does not execute. Unchanged by this card; pinned so + // the one sender stays the engine's own. + it('the find and delete verbs refuse a caller\'s lockRows as an option they do not execute', async () => { + const { engine, driver } = await makeEngine([loner], { lockRows: true }); await engine.insert('loner', { name: 'solo' }); + driver.reads.length = 0; driver.writes.length = 0; + await expect(engine.find('loner', { where: { name: 'solo' }, lockRows: true } as any)) + .rejects.toThrow(/does not recognise option 'lockRows'/); await expect(engine.delete('loner', { where: { name: 'solo' }, multi: true, lockRows: true } as any)) + .rejects.toThrow(/does not recognise option 'lockRows'/); + expect(driver.reads).toHaveLength(0); + expect(driver.writes).toHaveLength(0); + }); + + // A bag the engine hands on without a closed set (an insert's options) meets + // the engine -> driver hop's own check: a lock that cannot hold is refused + // before any driver runs. + it('refuses a lockRows its object\'s driver cannot honour: NOT_IMPLEMENTED / 501, nothing written', async () => { + const { engine, driver } = await makeEngine([loner]); + driver.writes.length = 0; + + await expect(engine.insert('loner', { name: 'solo' }, { lockRows: true } as any)) .rejects.toMatchObject({ code: 'NOT_IMPLEMENTED', status: 501, object: 'loner' }); - expect(driver.rowsOf('loner')).toHaveLength(1); expect(driver.writes).toHaveLength(0); + expect(driver.rowsOf('loner')).toHaveLength(0); }); - it('refuses a caller\'s lockRows outside a transaction: PRECONDITION_REQUIRED / 428, nothing read or deleted', async () => { + it('refuses a lockRows with no transaction to hold it: PRECONDITION_REQUIRED / 428, nothing written', async () => { const { engine, driver } = await makeEngine([loner], { lockRows: true }); - await engine.insert('loner', { name: 'solo' }); - driver.reads.length = 0; driver.writes.length = 0; - await expect(engine.find('loner', { where: { name: 'solo' }, lockRows: true } as any)) - .rejects.toMatchObject({ code: 'PRECONDITION_REQUIRED', status: 428, object: 'loner' }); - await expect(engine.delete('loner', { where: { name: 'solo' }, multi: true, lockRows: true } as any)) + await expect(engine.insert('loner', { name: 'solo' }, { lockRows: true } as any)) .rejects.toMatchObject({ code: 'PRECONDITION_REQUIRED', status: 428, object: 'loner' }); - expect(driver.reads).toHaveLength(0); expect(driver.writes).toHaveLength(0); - expect(driver.rowsOf('loner')).toHaveLength(1); + expect(driver.rowsOf('loner')).toHaveLength(0); }); - it('hands a caller\'s lockRows inside engine.transaction() to a driver that declares the bit', async () => { + it('lets the same lockRows through inside engine.transaction() on a driver that declares the bit', async () => { const { engine, driver } = await makeEngine([loner], { lockRows: true }); - await engine.insert('loner', { name: 'solo' }); - driver.reads.length = 0; + driver.writes.length = 0; - const rows = await engine.transaction(async () => - engine.find('loner', { where: { name: 'solo' }, lockRows: true } as any)); + await engine.transaction(async () => engine.insert('loner', { name: 'solo' }, { lockRows: true } as any)); - expect(rows).toHaveLength(1); - const locked = lockedReads(driver); - expect(locked).toHaveLength(1); - expect(locked[0].options.transaction).toBe(driver.begun[0]); + expect(driver.rowsOf('loner')).toHaveLength(1); + expect(driver.writes.filter((w: any) => w.op === 'create')).toHaveLength(1); + expect(driver.writes[0].transaction).toBe(driver.begun[0]); }); }); diff --git a/packages/spec/src/data/driver.zod.ts b/packages/spec/src/data/driver.zod.ts index fb1ba1d723f..a47cbcf362c 100644 --- a/packages/spec/src/data/driver.zod.ts +++ b/packages/spec/src/data/driver.zod.ts @@ -120,17 +120,18 @@ export const DriverOptionsSchema = lazySchema(() => z.object({ * with `transaction` set: a read outside a transaction has nothing to hold * the lock to. A driver honours it only when it declares * `DriverCapabilities.lockRows`. The engine never answers a request it - * cannot honour as if the rows were locked: a caller's `lockRows` on an - * object whose driver lacks the bit is refused `NOT_IMPLEMENTED` (501), and - * one with no transaction reaching that driver `PRECONDITION_REQUIRED` - * (428), before any driver runs. + * cannot honour as if the rows were locked: its read and delete verbs do not + * take the key from a caller, and any other option bag that carries it to + * the engine -> driver hop is refused there, before any driver runs: + * `NOT_IMPLEMENTED` (501) when the object's driver lacks the bit, + * `PRECONDITION_REQUIRED` (428) when no transaction reaches that driver. * * The engine's one sender is a predicate delete whose target is referenced by * delete-family lookups: it reads the matched ids, walks the cascade, then - * deletes those rows by id. Under the lock no concurrent commit can move a + * deletes those rows by id. Under the lock a concurrent writer cannot move a * matched row out of the caller's predicate between that read and the - * delete, so a guard such as "delete only if still pending" holds for the - * whole unit of work. + * delete and still see the row deleted, so a guard such as "delete only if + * still pending" holds for the whole unit of work. */ lockRows: z.boolean().optional().describe('find() inside a transaction: lock the returned rows against concurrent writers until the transaction ends (SELECT … FOR UPDATE); honoured only by a driver declaring supports.lockRows'), })); @@ -368,14 +369,17 @@ export const DriverCapabilitiesSchema = lazySchema(() => z.object({ * transaction. * * The promise: when `find()` runs with both `transaction` and `lockRows` - * set, no other writer can commit a change to a row that read returned - * until that transaction ends. The writer waits, or one side fails loudly; - * it never commits in between. PostgreSQL and MySQL take row locks - * (`FOR UPDATE`), SQL Server an update lock (`UPDLOCK`). SQLite has no row - * locks and needs none: `driver-sql`'s pool holds one connection, so a - * second writer through this driver waits for it, and a writer in another - * process meets the database lock (busy) rather than slipping a commit - * between the read and the transaction's own write. + * set, no other writer changes a row that read returned behind the + * transaction's back. Either the writer waits until the transaction ends, + * or one of the two fails loudly; a writer's commit is never followed by a + * successful write of the transaction over the changed row. PostgreSQL and + * MySQL take row locks (`FOR UPDATE`): the writer waits. SQL Server takes an + * update lock (`UPDLOCK`). SQLite has no row locks and needs none: + * `driver-sql`'s pool holds one connection, so a second writer through the + * same driver waits for it, and a writer on another connection meets the + * database lock: in WAL mode (the file default) it commits and the + * transaction's own next write fails `SQLITE_BUSY_SNAPSHOT`; under a + * rollback journal the writer fails `SQLITE_BUSY`. * * What the engine does with it: a predicate delete on an object that * delete-family lookups reference reads the matched ids inside the unit of @@ -393,7 +397,7 @@ export const DriverCapabilitiesSchema = lazySchema(() => z.object({ * * Optional; absence means `false`, like `batchSchemaSync`. */ - lockRows: z.boolean().optional().describe('`find()` honours `DriverOptions.lockRows` inside a transaction: no concurrent commit changes a returned row until the transaction ends (absence = false: the engine sends no lock request)'), + lockRows: z.boolean().optional().describe('`find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request)'), // ============================================================================ // Retired capability bits (#4634, ADR-0049 enforce-or-remove) — 17.0.0 From eaf5495cc508262800c9af94076339be2883d414 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:58:19 +0000 Subject: [PATCH 4/5] docs(spec): regenerate the driver references for lockRows Claude-Session: https://claude.ai/code/session_01ADHkmRukLEFGv24PSBTaHb Co-authored-by: Claude --- content/docs/references/data/driver-nosql.mdx | 1 + content/docs/references/data/driver-sql.mdx | 1 + content/docs/references/data/driver.mdx | 3 +++ 3 files changed, 5 insertions(+) diff --git a/content/docs/references/data/driver-nosql.mdx b/content/docs/references/data/driver-nosql.mdx index 81eb356ce1f..41101b01ad1 100644 --- a/content/docs/references/data/driver-nosql.mdx +++ b/content/docs/references/data/driver-nosql.mdx @@ -166,6 +166,7 @@ const result = AggregationPipelineSchema.parse(data); | **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) | | **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) | | **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | +| **lockRows** | `boolean` | optional | `find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request) | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | diff --git a/content/docs/references/data/driver-sql.mdx b/content/docs/references/data/driver-sql.mdx index 0e33d1f5635..fc16d64faef 100644 --- a/content/docs/references/data/driver-sql.mdx +++ b/content/docs/references/data/driver-sql.mdx @@ -79,6 +79,7 @@ const result = DataTypeMappingSchema.parse(data); | **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) | | **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) | | **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | +| **lockRows** | `boolean` | optional | `find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request) | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | diff --git a/content/docs/references/data/driver.mdx b/content/docs/references/data/driver.mdx index 707842e7435..38b95675c7d 100644 --- a/content/docs/references/data/driver.mdx +++ b/content/docs/references/data/driver.mdx @@ -33,6 +33,7 @@ const result = DriverCapabilitiesSchema.parse(data); | **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) | | **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) | | **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | +| **lockRows** | `boolean` | optional | `find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request) | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | @@ -89,6 +90,7 @@ const result = DriverCapabilitiesSchema.parse(data); | **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) | | **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) | | **aggregationFilter** | `boolean` | optional | `aggregate()` evaluates a per-measure `aggregations[].filter` itself, with the engine's in-memory answer, except that text compares by the backend collation as in `where` (absence = false: the engine aggregates filtered measures in memory) | +| **lockRows** | `boolean` | optional | `find()` honours `DriverOptions.lockRows` inside a transaction: no other writer changes a returned row behind the transaction (it waits, or one side fails) (absence = false: the engine sends no lock request) | | **create** | `never` | optional | [REMOVED] `DriverCapabilities.create` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `create`/`find`/`findOne`/`update`/`delete` are REQUIRED `IDataDriver` methods and the engine calls them unconditionally. Delete the key. | | **read** | `never` | optional | [REMOVED] `DriverCapabilities.read` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: reads go through the REQUIRED `find`/`findOne`/`count` methods, called unconditionally. Delete the key. | | **update** | `never` | optional | [REMOVED] `DriverCapabilities.update` was removed in @objectstack/spec 17.0.0 (ADR-0049 enforce-or-remove) — no code in any repository ever read it, so its value never changed which code path ran. CRUD is not optional for a driver: `update`/`upsert` are REQUIRED `IDataDriver` methods, called unconditionally. Delete the key. | @@ -149,6 +151,7 @@ const result = DriverCapabilitiesSchema.parse(data); | **timezone** | `string` | optional | Business reference timezone (IANA) for date-dependent generation, e.g. autonumber date tokens | | **preserveAudit** | `boolean` | optional | Historical import: keep a supplied updated_at instead of force-stamping now (from ExecutionContext.preserveAudit) | | **bypassTenantAudit** | `boolean` | optional | Suppress the driver tenant-audit warning for a deliberately global write on a tenant-scoped object (diagnostics only — never changes what the write touches) | +| **lockRows** | `boolean` | optional | find() inside a transaction: lock the returned rows against concurrent writers until the transaction ends (SELECT … FOR UPDATE); honoured only by a driver declaring supports.lockRows | --- From 7148349e5a6927e129b1b8adb485e5d6480ea309 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:44:57 +0000 Subject: [PATCH 5/5] test(objectql): type the off-contract lockRows option bags in the refusal pins Claude-Session: https://claude.ai/code/session_01ADHkmRukLEFGv24PSBTaHb Co-authored-by: Claude --- .../objectql/src/engine-cascade-delete-atomic.test.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/engine-cascade-delete-atomic.test.ts b/packages/objectql/src/engine-cascade-delete-atomic.test.ts index bc234aa49de..ddd4edfb653 100644 --- a/packages/objectql/src/engine-cascade-delete-atomic.test.ts +++ b/packages/objectql/src/engine-cascade-delete-atomic.test.ts @@ -24,6 +24,7 @@ */ import { describe, it, expect } from 'vitest'; +import type { DataEngineInsertOptions, EngineDeleteOptions, EngineQueryOptions } from '@objectstack/spec/data'; import { ObjectQL } from './engine.js'; type Recorded = { level: 'debug' | 'info' | 'warn' | 'error'; message: string }; @@ -787,9 +788,9 @@ describe('[#34373] a predicate delete with a cascade locks the rows it walks', ( driver.reads.length = 0; driver.writes.length = 0; - await expect(engine.find('loner', { where: { name: 'solo' }, lockRows: true } as any)) + await expect(engine.find('loner', { where: { name: 'solo' }, lockRows: true } as unknown as EngineQueryOptions)) .rejects.toThrow(/does not recognise option 'lockRows'/); - await expect(engine.delete('loner', { where: { name: 'solo' }, multi: true, lockRows: true } as any)) + await expect(engine.delete('loner', { where: { name: 'solo' }, multi: true, lockRows: true } as unknown as EngineDeleteOptions)) .rejects.toThrow(/does not recognise option 'lockRows'/); expect(driver.reads).toHaveLength(0); expect(driver.writes).toHaveLength(0); @@ -802,7 +803,7 @@ describe('[#34373] a predicate delete with a cascade locks the rows it walks', ( const { engine, driver } = await makeEngine([loner]); driver.writes.length = 0; - await expect(engine.insert('loner', { name: 'solo' }, { lockRows: true } as any)) + await expect(engine.insert('loner', { name: 'solo' }, { lockRows: true } as unknown as DataEngineInsertOptions)) .rejects.toMatchObject({ code: 'NOT_IMPLEMENTED', status: 501, object: 'loner' }); expect(driver.writes).toHaveLength(0); expect(driver.rowsOf('loner')).toHaveLength(0); @@ -812,7 +813,7 @@ describe('[#34373] a predicate delete with a cascade locks the rows it walks', ( const { engine, driver } = await makeEngine([loner], { lockRows: true }); driver.writes.length = 0; - await expect(engine.insert('loner', { name: 'solo' }, { lockRows: true } as any)) + await expect(engine.insert('loner', { name: 'solo' }, { lockRows: true } as unknown as DataEngineInsertOptions)) .rejects.toMatchObject({ code: 'PRECONDITION_REQUIRED', status: 428, object: 'loner' }); expect(driver.writes).toHaveLength(0); expect(driver.rowsOf('loner')).toHaveLength(0); @@ -822,7 +823,7 @@ describe('[#34373] a predicate delete with a cascade locks the rows it walks', ( const { engine, driver } = await makeEngine([loner], { lockRows: true }); driver.writes.length = 0; - await engine.transaction(async () => engine.insert('loner', { name: 'solo' }, { lockRows: true } as any)); + await engine.transaction(async () => engine.insert('loner', { name: 'solo' }, { lockRows: true } as unknown as DataEngineInsertOptions)); expect(driver.rowsOf('loner')).toHaveLength(1); expect(driver.writes.filter((w: any) => w.op === 'create')).toHaveLength(1);