Skip to content

Commit 371e5f1

Browse files
fix(spec, objectql, driver-sql): a predicate delete with a cascade locks the rows it walks (#34517)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9UbesJS6dTPnENK2P5ytLpg)_ Fixes #34373 Clause-②: yes (widening: DriverOptions.lockRows and DriverCapabilities.lockRows) Metadata-protocol: added Skills-docs: none — a driver capability and an engine→driver option; no skill teaches DriverOptions or DriverCapabilities ## 维护者速读 - 改了什么:带级联的谓词删除(`delete(obj, { where, multi: true })`)在删除事务里先给命中的行加锁再删;SQL 驱动声明新能力位 `lockRows`,`find()` 在事务内发 `FOR UPDATE`。 - 为什么改:原先先读命中 id、走级联、再按 id 删,调用方的条件(如「只删仍是 pending 的」)不在最终 DELETE 上;并发提交把行改出条件后,这行照样被删、还被计数。 - 风险与回滚:只有声明 `lockRows` 的驱动在事务内才加锁,其它驱动和 `split` 计划行为不变;回滚即回退本 PR,spec 只多两个可选键。 - 先看:`packages/objectql/src/engine-delete-and-aggregate.ts` 的级联分支(约 750–775 行)和 `packages/drivers/driver-sql/src/sql-driver-crud.ts` 的 `lockRowsIfAsked`。 - 两分钟验证:设好 `OS_TEST_POSTGRES_URL` 后跑 `pnpm --filter @objectstack/driver-sql exec vitest run src/sql-driver-34373-lock-rows.test.ts`,看两种并发次序都不会删掉被改出条件的行。 - 需要你做的:无,等审核席复审后由席位转 ready。 ## What changes A predicate delete on an object that delete-family lookups reference reads the matched ids, walks the cascade, then deletes those rows by `id $in`, so the caller's predicate is not on the final DELETE. A concurrent commit between the read and the delete that moved a row out of the predicate (`{ id, source: 'idp_pending' }` → `active`) was deleted anyway, and counted. - **spec** (`packages/spec/src/data/driver.zod.ts`): - `DriverOptions.lockRows` (hunk `@@ -113,0 +114,23 @@`, after `bypassTenantAudit`): on a `find()` inside a `transaction`, lock the returned rows until the transaction ends. - `DriverCapabilities.lockRows` (hunk `@@ -340,0 +367,35 @@`, after `aggregationFilter`) and its header bullet (hunk `@@ -162,0 +186,3 @@`): the driver's `find()` honours that option; absence = `false`. - **Precedent**: the bit follows `aggregationFilter` — `packages/spec/src/data/driver.zod.ts:339` on main, read by the engine at `packages/objectql/src/engine-delete-and-aggregate.ts:1443` (`drv?.supports?.aggregationFilter === true`), changeset `.changeset/33698-measure-filter-pushdown.md`: one optional capability bit, landed together with its engine reader, absence = the engine keeps its own path. - Collision note: #33876 also adds a `DriverCapabilities` bit next to `aggregationFilter`. The hunk at `+367` is the one that meets it; the `DriverOptions` hunk and the header bullet are independent. - **objectql** (`engine-delete-and-aggregate.ts`, the cascade arm of `runPredicateDelete`): when the unit has a transaction handle and the driver declares `supports.lockRows`, the matched-row read carries `lockRows: true`. Rows deleted are still exactly the rows walked. - **objectql refusal** (`engine-driver-options.ts` `buildDriverOptions`, new `lock-rows-refusal-error.ts`, `engine.ts` host gets `getDriver`): `lockRows` arriving at the engine→driver hop from any option bag is refused before a driver runs — `NOT_IMPLEMENTED` / 501 when the object's driver does not declare the bit, `PRECONDITION_REQUIRED` / 428 when no transaction reaches that driver. A lock request is never dropped silently. The read and delete verbs already refuse `lockRows` from a caller as an unknown option (`rejectUnknownEngineOptions`), unchanged. - **driver-sql** (`sql-driver-crud.ts` `lockRowsIfAsked`, `sql-driver.ts` `supports.lockRows: true`): `find()`/`findOne()` add `forUpdate()` (PG/MySQL/Oracle `FOR UPDATE`, MSSQL `UPDLOCK`, SQLite nothing — the database lock keeps the promise, see Verification). `lockRows` without a transaction → `PRECONDITION_REQUIRED` / 428. What keeps the window: a driver without the bit (memory, MongoDB, OData), and a cascade that cannot run in one transaction (`split` plan, no transactions). ## Tests - New `packages/drivers/driver-sql/src/sql-driver-34373-lock-rows.test.ts`: the 428 refusal; live PG/MySQL row-lock cells (writer after the locked read waits; locked read behind a writer waits and does not return the moved row); SQLite two-connection pins for WAL (`SQLITE_BUSY_SNAPSHOT` on the transaction's delete, row kept as moved) and rollback journal (writer `SQLITE_BUSY`, delete stands). - New `describe('[#34373] …')` in `packages/objectql/src/engine-cascade-delete-atomic.test.ts`: locked read with the bit; none without the bit or without transactions; the verbs' existing refusal of `lockRows`; 501 and 428 with code + status; the in-transaction pass. - Tests changed: - `packages/objectql/src/engine-cascade-delete-atomic.test.ts` — the shared harness `makeDriver` takes `{ transactional, lockRows }` and records a `reads` ledger; existing cases unchanged. - `packages/spec/src/data/driver.test.ts` — `LIVE_BITS` gains `lockRows`; the shape pin renamed to `6 live bits + 31 tombstones`; accept/refuse cases for both keys. ## Acceptance notes The card's scenario (guarded predicate delete vs a concurrent move) is read end to end below against live PostgreSQL 16, at head and with the lock stripped. Review follow-ups (contract review 6933706748 nits N1–N3 and the PostgreSQL UPDATE-privilege note): filed #34549. ## Verification All readings on a shared cloud box; heavy runs under `scripts/pm/os-verify-lock.sh`. Live PostgreSQL 16 local (`OS_TEST_POSTGRES_URL`), server zone `Asia/Shanghai`, process `TZ=America/New_York` for the full driver-sql suite (its timezone fixtures require both skews). MySQL, SQL Server and Oracle were **not** measured here; `Temporal Conformance (live PG + MySQL)` runs the live cells on main's full battery; it is skipped on this pull request by its own `if:`, so no check-run on this PR executes the live PostgreSQL or MySQL lock cells — the PostgreSQL reading here is local. <details><summary>Suites</summary> - `@objectstack/spec` vitest: 937 files, 28629 passed, 1 todo. - `@objectstack/objectql` vitest: 605 files, 13516 passed. - `@objectstack/driver-sql` vitest (live PG + SQLite): 267 files passed, 4 skipped; 5459 passed, 128 skipped (MySQL / MSSQL cells NOT RUN). - `sql-driver-34373-lock-rows.test.ts`: 7 passed, 1 skipped (MySQL cell). - `tsc --noEmit` for spec, objectql, driver-sql: clean. `pnpm --filter @objectstack/spec check:generated`: 14/14 current after the docs regeneration. </details> <details><summary>End to end: ObjectQL engine + SqlDriver on live PostgreSQL</summary> A temporary test (not committed) booted `ObjectQL` with a real `SqlDriver`, a `ticket` object and a `master_detail` `note` child (so the delete takes the cascade arm), inserted one `pending` ticket with one note, and wrapped `find` so that right after the delete's matched-row read a second driver (its own pool) runs `update(ticket, { status: 'active' })` and is given 400 ms. Then `engine.delete('ticket', { where: { status: 'pending' }, multi: true })`. | run | lock requested | writer committed before the delete | removed | row after | | --- | --- | --- | --- | --- | | head | yes | **no** (waited on the row lock) | 1 | gone (deleted while still `pending`; the move then found nothing) | | lock stripped before the driver | — | **yes** (`active` committed) | 1 | gone: **the `active` row was deleted** — the card's defect | </details> <details><summary>Ablation readings (each restored, tree clean after)</summary> - A1 `sql-driver-crud.ts` `return builder.forUpdate();` → `return builder;`: both live-PG row-lock pins red. - A2 `engine-delete-and-aggregate.ts` `{ ...writeOptions, lockRows: true }` → `writeOptions`: "reads the matched rows with lockRows …" red (1 of 27). - A3 the `engine-driver-options.ts` refusal guard disabled: the 501 and 428 pins red (2 of 27). - A4 `sql-driver-crud.ts` `if (!options.transaction)` → `if (false)`: "answers PRECONDITION_REQUIRED / 428" red. </details> <details><summary>SQLite, two connections on one file (measured)</summary> - WAL (the file default `connect()` applies): the other connection's update commits; the transaction's own `deleteMany` fails `SQLITE_BUSY_SNAPSHOT`; after rollback the row is `active` (not deleted). - Rollback journal: the other connection's update fails `SQLITE_BUSY` after the busy timeout; the transaction's delete removes the row as matched. </details> <details><summary>Overlap with in-flight work</summary> `git merge-tree --write-tree` of this head against #34439 (`7c80b9db`, shares `packages/objectql/src/engine.ts`) and against branch `claude/issue-34412-before-hook-side-write-unit` (`320f1f86`, shares `engine-delete-and-aggregate.ts`): both clean, exit 0. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English (the 维护者速读 section excepted by the dispatch order). - [x] The *Before Submitting* list in CONTRIBUTING.md is done. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01ADHkmRukLEFGv24PSBTaHb <!-- signed: repo:objectstack#2 · os-steve · session_01ADHkmRukLEFGv24PSBTaHb --> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent 4176c95 commit 371e5f1

15 files changed

Lines changed: 590 additions & 10 deletions
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
---
2+
'@objectstack/spec': minor
3+
'@objectstack/objectql': patch
4+
'@objectstack/driver-sql': patch
5+
---
6+
7+
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)
8+
9+
Clause-②: yes (widening: DriverOptions.lockRows and DriverCapabilities.lockRows)
10+
Metadata-protocol: added
11+
12+
**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.
13+
14+
**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.
15+
16+
- `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`).
17+
- `DriverCapabilities` gains `lockRows`: the driver's `find()` honours that option. Absence means `false`, and the engine sends no lock request to such a driver.
18+
- `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.
19+
- 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.
20+
21+
**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.

‎content/docs/references/data/driver-nosql.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ const result = AggregationPipelineSchema.parse(data);
166166
| **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) |
167167
| **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) |
168168
| **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) |
169+
| **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) |
169170
| **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. |
170171
| **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. |
171172
| **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. |

‎content/docs/references/data/driver-sql.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ const result = DataTypeMappingSchema.parse(data);
7979
| **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) |
8080
| **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) |
8181
| **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) |
82+
| **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) |
8283
| **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. |
8384
| **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. |
8485
| **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. |

‎content/docs/references/data/driver.mdx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ const result = DriverCapabilitiesSchema.parse(data);
3333
| **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) |
3434
| **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) |
3535
| **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) |
36+
| **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) |
3637
| **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. |
3738
| **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. |
3839
| **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);
8990
| **batchSchemaSync** | `boolean` | optional | Supports batched schema sync to reduce schema DDL round-trips (absence = false) |
9091
| **transactionsUnsupported** | `boolean` | optional | Transport cannot honour transactions even though `beginTransaction` is inherited (absence = false) |
9192
| **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) |
93+
| **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) |
9294
| **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. |
9395
| **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. |
9496
| **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);
149151
| **timezone** | `string` | optional | Business reference timezone (IANA) for date-dependent generation, e.g. autonumber date tokens |
150152
| **preserveAudit** | `boolean` | optional | Historical import: keep a supplied updated_at instead of force-stamping now (from ExecutionContext.preserveAudit) |
151153
| **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) |
154+
| **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 |
152155

153156

154157
---

0 commit comments

Comments
 (0)