Skip to content

perf(objectql)!: a cascade delete removes a relation's children as one predicate delete per chunk - #33887

Merged
objectstack-fleet[bot] merged 16 commits into
mainfrom
claude/area-A4-33699
Nov 16, 2026
Merged

objectstack-fleet[bot] merged 16 commits into
mainfrom
claude/area-A4-33699

Conversation

@objectstack-fleet

@objectstack-fleet objectstack-fleet Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Steedos · project thread

Part of #33699

Clause-②: no (narrowing) — the published hook dispatch shape for cascaded children changes (dispatch.mode 'record' → 'per-row', options.multi, before-hooks run before the set delete); BREAKING banner + ADR-0087 disposition in the changeset; one CONTRACT_REVIEW_TIER review owed before the queue
Metadata-protocol: none
Skills-docs: none — no skills/** file teaches a cascaded child's dispatch.mode, referentialCascadeDelete or a sibling-count hook (git grep of dispatch.mode, referentialCascadeDelete and per-row over skills/: the only hits teach predicate writes in general and stay true); the spec's own hook docs are updated here

No longer waiting on #33928 (as of 5ed247661): it landed on main as #34033 and is in this tree by the merge at 321a8668f. Ruling 6893661036 precondition (1), the #33782 parity pins merged as #33927, is met: all 8 cases green at 5ed247661, in Test Core (8/8) and locally. CONTRACT_REVIEW_TIER record 6908865874 on 5ed247661: PASS.

c1 stays open on #33699. Ruling 6893104201's c1 (the walk's collect probe, re-probe and recycle-bin snapshot read the same child rows) is not done here, so this PR does not close the card.

维护者速读

  • 改了什么:删除一条记录时,级联删除的子记录不再逐条删除,而是每 500 条一批、一条 DELETE … WHERE id IN (…) 删掉;每个子记录的删除前后钩子、实时事件、回收站、权限拒绝回滚都保留。
  • 为什么改:删除一个带 10 条明细的商机,今天要 155 条 SQL,随明细数线性增长;本 PR 实测降到 58 条(SQLite 与 PostgreSQL 相同,其中 1 条是按调用者读权限核对本批子记录),中位耗时约减半。
  • 风险与回滚:级联子记录的钩子上下文从 dispatch.mode: 'record' 变为 'per-row'(带 options.multi),同批子记录共用一个 dispatch.scope,前后两个阶段各拿一个新的 ctx,所以挂在 ctx 上的临时值到不了删除后钩子(改放 ctx.dispatch.scope,按 ctx.input.id 分键);同批删除前钩子全部先跑、再统一删除。调用者无权删除或无权读取的子记录、以及级联途中由钩子新写入的子记录,都退回今天的逐条删除。回滚 = revert 本 PR。
  • 先看:packages/objectql/src/engine-cascade-planning.ts(deleteCascadedChildren:只批量已收集的成员,其余与被收窄的批次逐条删除)、packages/objectql/src/engine-delete-and-aggregate.ts(谓词删除分支里的范围核对与逐行实时事件)、changeset 的 FROM → TO 段。
  • 两分钟验证:pnpm --filter @objectstack/objectql exec vitest run src/engine-cascade-delete-batch.test.ts,预期 15 个用例全绿(Tests 15 passed (15))。
  • 需要你做的:无,席位落地。

What changes

Ruling 6893661036 (option F1), replacing point 4 of ruling 6893104201; points 1–3 stand.

  • The walk (engine-cascade-planning.ts): for a cascade relation the walk now collects the relation's dependents across the whole root set and hands them to deleteCascadedChildren, which issues ONE predicate delete per chunk of 500 (REFERENCE_PROBE_BATCH, under MAX_BULK_PER_ROW_HOOK_ROWS = 10,000) through the public delete(): where: { id: { $in: chunk } }, multi: true. The chunk therefore runs every child's beforeDelete (per-row, ADR-0058 Addendum II), one deleteMany, then every child's afterDelete. A child's own children are walked by the predicate arm's existing cascadeDeleteRelations (objectql: since #26930 a predicate delete walks every matched row one by one; 1,001 rows cost ~1.7 s (18×), and rest's nested-object-door cap test now nears its 5 s budget in the merge queue #27004), joining the root's set, so grandchildren are batched too.
  • The marker (engine-top-level.ts, engine-middleware-and-context.ts, surface amendment 6893212568): the cascade-issued token gains an optional id set, and claimReferentialCascadeDelete matches a predicate delete whose where is exactly { id: { $in } } naming that set. Every per-row context, both phases, carries referentialCascadeDelete: true.
  • Security parity, point 2 (engine-delete-and-aggregate.ts): a claimed cascade batch always reads its doomed rows through the middleware-composed AST. If a requested child is missing (a scope that narrows a predicate delete where it refuses the by-id one), the engine throws an engine-internal CascadeBatchNarrowed before any hook or write; the walk catches only that and deletes the chunk by id, so the caller meets today's refusal and envelope and the cascade rolls back. A driver with no deleteMany (or a floored external driver) keeps the by-id path. One cascade can show both shapes.
  • Realtime, point 1: a cascade batch publishes one data.record.deleted per child from its pre-image, never the bulk data.records.deleted.
  • Point 3: no new refusal; the bulk per-row hook ceiling is asserted only when the child has delete-side hooks, and a chunk never exceeds 500.
  • Spec prose: the HookContext.dispatch.mode and referentialCascadeDelete TSDoc now say a cascaded child is 'per-row' with multi, and that the token can name an id set. No .describe() and no schema shape changed (check:docs green, nothing regenerated).
  • SQL shape emitted (SQLite driver log, DEBUG=knex:query, warm delete): inside the transaction, one doomed read select * from bench_line_item where id in (?, x10), then one delete from bench_line_item where id in (?, x10); the sharing cleanup now runs once per chunk (select/delete from sys_record_share … record_id in (?, x10), same for sys_share_link); the audit pair stays per child.
  • A dependent the collected set never held (engine-cascade-planning.ts, record 6899834361 S2): only cascadeSet.members are batched; a row a hook of the same cascade wrote after the set was collected is deleted by id, as the root of its own cascade, with its own recycle-bin entry, as before the batch.

What a hook on a cascaded child sees (FROM → TO, as in the changeset)

  • FROM ctx.dispatch.mode: 'record' and ctx.input.options { where: { id } } TO ctx.dispatch.mode: 'per-row', with ctx.dispatch.index its position in the chunk and ctx.input.options carrying where: { id: { $in: [...] } } and multi: true. ctx.input.id and ctx.previous still name the child's own row, and ctx.referentialCascadeDelete is still true on every per-row context, in both phases, grandchildren included.
  • FROM ctx.result in a cascaded child's afterDelete being the driver's by-id answer TO ctx.result absent, as on every per-row delete context. Read ctx.previous for the deleted row.
  • FROM ctx.dispatch.scope one scratch object per cascaded child TO one object shared by every child of the chunk, in both phases (the scratch of one caller write, which the chunk now is).
  • FROM one context object for a cascaded child's beforeDelete and afterDelete TO a fresh context per row per phase, so a value a beforeDelete handler leaves on ctx no longer reaches that child's afterDelete. Keep cross-phase state in ctx.dispatch.scope, keyed by ctx.input.id.
  • The one behaviour that flips: the chunk runs every child's beforeDelete, then the one set delete, then every child's afterDelete. Before, each child ran before → delete → after in turn. So a beforeDelete hook that counts a child's remaining siblings now sees them ALL present, where it used to see one fewer at each step. Judge the whole batch instead: on ctx.input.options.multi === true read the target set from ctx.input.options.where (the shipped last-administrator guard does exactly this, and reaches the same verdict as before), or use ctx.referentialCascadeDelete === true to tell the cascade from a hand delete.
  • A chunk the caller's scope narrows falls back to today's by-id deletes for that chunk, so the caller still meets the same refusal and the whole cascade rolls back: a child the caller may not delete, which a predicate delete would skip, and a child the caller may not read, which the by-id delete refuses through its re-read of the row (the cascade asks the caller's read door for each chunk's ids before batching it). Such a chunk keeps today's shape, 'record' with no multi, so one cascade can show both shapes. A driver with no deleteMany, a floored external driver, and a cascade into the organization object (deleted by id or not at all) keep the by-id path too, and so does a child the walk finds that the cascade's collected set never held (a row a hook of the same cascade wrote after the set was collected): it is deleted as the root of its own cascade, with its own recycle-bin entry, as before.

Tests

  • packages/objectql/src/engine-cascade-delete-batch.test.ts (15 cases, a driver that rolls back for real and logs its writes): before x N, one deleteMany, after x N with the write count observed from inside each hook; dispatch.mode: 'per-row', index 0..N-1, options.multi, previous = own row, the marker on every per-row context; dispatch.scope is one object across the chunk's six dispatches, a value left on ctx in beforeDelete does not reach afterDelete, and the same value kept in dispatch.scope keyed by input.id does, with the by-id shape as control (three scopes, the ctx stash arrives); the sibling-count flip ([3, 3, 3]); grandchildren batched and marked; 501 children = two set deletes (500 + 1); realtime per-row; rollback on a before-phase and an after-phase refusal; the narrowed-chunk fallback (today's 403 envelope, nothing deleted, only 'record' dispatches ran); an allowed fallback keeping today's shape beside a batched relation; no deleteMany keeps by-id; the read-door fallbacks (hidden and refused, hidden and allowed, all readable as control); a cascade into the organization object deleted by id.
  • packages/objectql/src/recycle-bin/capture.test.ts, new top-level describe: a cascade dependent a hook of the same cascade writes after the set was collected is deleted by id with a recycle-bin entry of its own (note/n9), while the collected members stay rows of the root entry (account/acc1, contact/c1, contact/c2, note/n1).
  • packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts (test(plugin-security): security-parity pins for cascade delete across child-delete shapes #33927, on main, not edited here): 8 of 8 green on this head.
  • packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts: a child hidden by a select-class policy and admitted by a delete-class policy refuses the parent's delete on both legs; control deletes on both.
  • packages/plugins/plugin-auth/src/last-admin-guard.test.ts, top-level describe [F1]: the shipped last-administrator guard reaches the same verdict on the batch and on the by-id path, refused and allowed.
  • packages/objectql/src/engine-cascade-summary-rollback.test.ts: one expectation re-triaged (see Acceptance notes).

Acceptance notes

  • The one fixture re-triaged: on a runtime that cannot roll back, a refusal raised after a chunk's set delete (a failed roll-up recompute) now finds the whole chunk deleted, where the per-child walk had deleted only the children before the refusal. The changeset says so.
  • Not done here, from ruling 6893104201's c1: the walk's collect probe, re-probe and the recycle-bin snapshot still read the same child rows. Behaviour-neutral, left on the card.
  • The spec's dispatch.mode TSDoc lists the by-id fallbacks and does not name the dependent the collected set never held (S2 of record 6899834361): left as is so this round moves no packages/spec text; the changeset names it.
  • Surface, named explicitly: packages/plugins/plugin-auth/src/last-admin-guard.test.ts and packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts (test-only, outside the claim's objectql file surface, both ordered by a ruling or a prior record). packages/objectql/src/recycle-bin/capture.test.ts is inside it.

Verification

Head 5ed247661: origin/main at 31eb2aeda merged (321a8668f, 128 commits, no textual conflict; hook.zod.ts auto-merged), then 74ef4e4bc (S2) and 5ed247661 (S1). The net diff against origin/main is the same changed lines as before the merge (diffed: identical +/- line sets over the same 10 files), plus this round's three files. Interplay read: #34033 now judges a multi: true write by the bulk write scope unless the engine runs it by id, so the batch's { where: { id: { $in } }, multi: true } is no longer refused as a by-id write of [object Object]; a row the sharing write scope narrows out is answered by CascadeBatchNarrowed and goes by id, as before. #33782 is closed; its pins are the #33927 file above.

Which shape each parity case took (one-off probe, not committed)

A temporary object-less beforeDelete recorder was added to the parity file through scripts/ablation-replace.mjs and removed (restored blob equals HEAD, git diff HEAD empty); 8 of 8 green with it. The four cases that land run batched: f_all (12 lines, 2 notes), m1, m2, h1, every child per-row multi=true marker=true. The four refused cases fall back: r1, f_u (unreadable child, the read door misses it) and r2, f_e (edit-shared child, readable, so the batch's write-scope read misses it and CascadeBatchNarrowed crosses the real security and sharing chain back to the walk); each shows _a as record, then the refusal at _b's by-id delete. So every refusal in the file comes from today's by-id door, and none from the batch.

Local suites and gates at 5ed2476
  • Under the verify lock (VERDICT command-exit 0): objectql build exit 0; pnpm --filter @objectstack/objectql test Test Files 600 passed (600), Tests 13369 passed (13369); objectql typecheck exit 0 (test layer 39 files / 233 errors / 64 signatures held, unchanged); pnpm --filter @objectstack/plugin-security test Test Files 272 passed (272), Tests 6724 passed, 45 skipped (6769); pnpm --filter @objectstack/plugin-sharing test Test Files 75 passed (75), Tests 1581 passed (1581); last-admin-guard.test.ts 114 passed.
  • Parity file alone: Test Files 1 passed (1), Tests 8 passed (8).
  • node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack at 5ed247661 derived 99 commands (11 paths vs merge base 31eb2aeda; it flagged origin/main one commit ahead, 8898b4e39, which changed scripts/check-facade-delegation-only.mjs, a family not in this list). Run: the 80 non-spec commands exit 0 (check:test-source-alias, check:cross-package-test-inputs, check:nul-bytes, check:durability-log-level, check:engine-double-contract, the changeset and ADR-0087 gates among them); the 17 @objectstack/spec families exit 0. spec check:generated: 13 of 14 current; check:test-typecheck (spec) died in tsc with no diagnostics while the dogfood battery held the box; its re-run under the lock never acquired it (exit 99), so it is NOT MEASURED here and read from CI: TypeScript Type Check, which runs every spec artifact gate, is success on this head. This round touched no packages/spec file. check:type-check-debt and check:dual-build-cjs-loads: NOT MEASURED here, CI's (the first needs the whole workspace typechecked, the second every package built). CI families are read from the PR's check-runs on this head, not re-run here.
  • eslint --no-inline-config over the three files this round touched: exit 0. Control-byte self-scan of the four files: no hit.
  • Dogfood battery (pnpm --filter @objectstack/dogfood test under the verify lock, no shard, no path, after pnpm --filter '@objectstack/dogfood^...' build exit 0 at 5ed247661): VERDICT command-exit 0, Test Files 471 passed, 3 skipped (474); Tests 3988 passed, 42 skipped (4030); no failure. CI on 5ed247661: 67 check-runs, 56 success, 11 skipped, none failed; Test Core 1/8 to 8/8, Lint & Repo Gates, TypeScript Type Check, Build Core, Governed Surface Queue Guard success (the queue-only dogfood shards skipped on the PR event).
Pins red first, and ablations (each restored to HEAD's blob, git diff HEAD empty)

All through scripts/ablation-replace.mjs (anchor 1 to 0, blob moved, restored). No rebuild leg: objectql's own tests import its source, and plugin-security aliases @objectstack/objectql to source.

  1. S2 pin before the fix: red, expected [ 'account/acc1' ] to deeply equal [ 'account/acc1', 'note/n9' ] (the late row deleted with no entry). Green after 74ef4e4bc.
  2. Ablation of the S2 term (const members = chunk;, blob daa43fc8a to 28aa50b34): 1 failed / 42 passed over the two objectql files, the same message. Restored.
  3. Ablation of the batch for pin (a) (if (false && batchable …): the dispatch.scope case red, expected 3 to be 1 (one scope per child, the FROM row). Restored.

Update at 5ed247661 (record 6899834361)

Fix round for the CONTRACT_REVIEW_TIER record 6899834361 (VERDICT: FAIL, head 616735ceb), by session session_01QsR2jUg7BKfRBcTPyMxbLh; S1 and S2 folded into this main-merge round after #34033, as the seat ruled.

Commits this round:

  • 321a8668f: merge of origin/main at 31eb2aeda (128 commits, no textual conflict; git show --remerge-diff of the merge is empty). The PR's own changed lines against main are identical before and after the merge.
  • 74ef4e4bc: the member filter. deleteCascadedChildren batches only cascadeSet.members; a dependent the collected set never held is deleted by id, as the root of its own cascade, with its own recycle-bin entry. Pin in recycle-bin/capture.test.ts.
  • 5ed247661: the two FROM to TO changeset rows (dispatch.scope shared per chunk; a fresh context per row per phase, with the remedy), the fallback sentence for the dependent the collected set never held, and the both-shapes dispatch.scope pin in engine-cascade-delete-batch.test.ts.
finding disposition evidence
M1 · 4 of the 8 #33927 parity cases red (plugin-sharing judged the batch as a by-id write) closed by #34033 + the merge 8 of 8 green at 5ed247661; the shape probe above shows the four landed cases batched and the four refused cases refused by the by-id door. Test Core is CI's on this head.
S1 · FROM to TO lacks dispatch.scope and the fresh ctx per phase fixed Two changeset bullets (.changeset/33699-cascade-delete-batch.md lines 21 and 22) with the remedy: keep cross-phase state in ctx.dispatch.scope, keyed by ctx.input.id. Pin (a): engine-cascade-delete-batch.test.ts line 199, both shapes.
S2 · a probe-found row the collect phase never held lost its own recycle-bin entry fixed One term: deleteCascadedChildren batches only cascadeSet.members (engine-cascade-planning.ts line 1461); a non-member goes by id as the root of its own cascade. Pin: recycle-bin/capture.test.ts line 544, red before the fix, red under the ablation.
N1 · CascadeBatchNarrowed across the real chain pinned only by the #33927 cases read, nothing to change Those cases are green here, and r2/f_e are the narrowed fallback crossing the real security and sharing chain (shape probe above).

Nits of record 6908865874 (PASS on 5ed247661), accepted and not changed, so the reviewed head stands:

  • N1 · the dispatch.mode TSDoc in hook.zod.ts lists four by-id cases, not the fifth (a child the collected set never held): accepted. The changeset and the code carry the fifth, and a spec text edit would move the head the record passed.
  • N2 · the S2 pin runs the batched shape only: accepted. Before the batch, every cascaded child went by id, so the by-id leg is the path that has always written that entry; the pin plus its ablation hold the one term that changed.
Earlier heads (kept as written)

Verification

Head 89dff98f6 (origin/main merged twice; the second merge touched objectql transactions, so the objectql suite was re-run on it). Bench numbers are from my own runs of packages/qa/dogfood/bench/sql-perf/bench.mjs --scale 100000 --only cascade_delete_opportunity on this box (shared, 5 deletes each, one opportunity with 10 line items, admin): statement counts exact, milliseconds indicative. "Before" = objectql source at base 1e65a389e built into the same tree; "after" = this branch.

dialect before statements after statements before p50 / p95 ms after p50 / p95 ms (run 1 · run 2)
SQLite 155 (166 cold) 57 (68 cold) 131.2 / 169.7 66.4 / 115.2 · 76.1 / 148.5
PostgreSQL 16 (private cluster, fsync off) 155 (166 cold) 57 (68 cold) 243.0 / 312.5 89.5 / 166.3 · 85.3 / 145.3
SQLite, fix round with the read-door proof (7d2730a95) 155 (166 cold) 58 (69 cold) 131.2 / 169.7 100.0 / 177.4
PostgreSQL 16, fix round with the read-door proof (7d2730a95) 155 (166 cold) 58 (69 cold) 243.0 / 312.5 135.2 / 236.4
Local suites and gates
  • pnpm --filter @objectstack/objectql exec vitest run at 89dff98f6: Test Files 598 passed (598), Tests 13168 passed (13168); VERDICT command-exit 0. objectql typecheck at 89dff98f6 exit 0.
  • pnpm --filter @objectstack/plugin-auth exec vitest run at a1e04815b: Test Files 277 passed (277), Tests 5472 passed, 10 skipped; VERDICT command-exit 0. At 89dff98f6: last-admin-guard.test.ts + remove-user-atomicity.test.ts, 120 passed.
  • typecheck: objectql exit 0 (test layer 39 files / 233 errors held, unchanged), plugin-auth exit 0; spec check:test-typecheck exit 0.
  • node scripts/pm/dispatch-gates.mjs --commands: 96 families, all run at cb2cafef6; 94 exit 0. check:query-options-erasure exit 1 (test surface 236 to 237, an as any on an option bag in the new test) fixed in d31c13d0a, re-run exit 0. check:dual-build-cjs-loads exit 3 (prerequisite: not every package built here), NOT MEASURED, CI's. --ran reconciliation: 96 derived, 96 run, 0 unrun.
  • At d31c13d0a with this body as the event: check-adr-0087-registration 0, check-changeset-no-major 0, check-closing-keyword-parity 0, check-empty-changeset 0, check-partof-closing-keyword 0; plus check:nul-bytes, check:cross-package-test-inputs, check:test-source-alias, check:doc-authoring, check:issue-citations all 0; eslint over the eight touched files exit 0.
  • Spec: pnpm --filter @objectstack/spec check:generated after a spec build: every artifact current (check:docs green; TSDoc only, nothing regenerated).
Ablations (each red, then restored to HEAD's blob, git diff HEAD empty)

All through scripts/ablation-replace.mjs (anchor 1 to 0, blob moved, restored).

  1. Delete the CascadeBatchNarrowed throw: the narrowed child is silently skipped and the parent delete succeeds. 2 of 10 red ("expected undefined to be 'PERMISSION_DENIED'"; the both-shapes case).
  2. Make the token never match an id set (if (issued.ids != null) return undefined): 5 of 10 red (the marker, realtime and fallback all key on the claim). A first attempt whose replacement contained its anchor was refused by the tool as a no-op and re-run.
  3. Route the batch back to the bulk realtime event: 1 of 10 red (['data.records.deleted'] instead of three data.record.deleted).
  4. Dispatch the batch's before-hooks without multi (the "record shape, batched befores" the ruling rejects), objectql rebuilt so plugin-auth's dist import carries it: [batch] … BOTH administrative memberships is refused red ("promise resolved true instead of rejecting": the guard judged each membership with its sibling still present and the last administrators were deleted). Restored, rebuilt, ablation-dist-preflight --absent ok, 4 of 4 green.

Update at 616735ceb (review 6896079092)

Fix round for the CONTRACT_REVIEW_TIER review 6896079092 (VERDICT: FAIL) and review 6896089195, by session session_01QsR2jUg7BKfRBcTPyMxbLh (the earlier body above is kept as written). Commits: 4029ca241 (M1, S1, N1 to N4), bb5e34b5d (the read-seam guard and the walk's host type, the two CI reds of 4029ca241), eab93bab0 and 7d2730a95 (merges of main; the second brought in the #33927 parity pins), 616735ceb (changeset count).

finding disposition evidence
M1 · the batch drops the read scope the by-id child delete enforces fixed The reviewer's reading holds, measured: the new pin is red on the batch leg at 89dff98f6 (objectql source of that head, { kind: 'landed' }, the hidden child deleted) and green on the by-id leg (403). Fix: before a chunk is batched, the walk asks the caller's read door (find(child, { where: { id: { $in: chunk } }, fields: ['id'] }) under the walk's context) and deletes the chunk by id when any id is missing, so the by-id path gives today's answer. A read the door refuses (declared 4xx) also routes to by-id; a store fault propagates.
S1 · a cascade into sys_organization newly refused 409 fixed childName !== ORGANIZATION_OBJECT in batchable; pinned in objectql. No other refusal of the same one-term shape found (list in Acceptance notes of this update).
N1 · dispatch.mode fallbacks fixed TSDoc names all four by-id cases (narrowed or unreadable chunk, no deleteMany, floored external driver, the organization object) and says the before-hooks run before the set delete per chunk of 500 within one relation.
N2 · stale "ctx.input identical" fixed referentialCascadeDelete "Why a declared key" now says ctx.user/ctx.session are identical and ctx.input/ctx.dispatch tell nothing apart either.
N3 · changeset FROM to TO omits ctx.result fixed New FROM to TO bullet: ctx.result in a cascaded child's afterDelete, the driver's by-id answer, is now absent; read ctx.previous. The dispatch.mode value is stated as the code sets it, 'per-row'.
N4 · "the caller's scope" fixed The comment in engine-delete-and-aggregate.ts says the doomed read is the caller's WRITE scope and that the read scope is proven by the walk.
c1 not done, carried Closing keyword changed to Part of #33699; c1 stays open on the card.
Tests and ablations at this head
  • packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts (new, real ObjectQL + SqlDriver + SecurityPlugin, both legs: the batch, and the by-id path with deleteMany hidden): a child hidden by a select-class policy and admitted by a delete-class using policy (public_read_write, no owner_id) makes the parent's delete answer 403 PERMISSION_DENIED with nothing deleted, on both legs; control: readable deletable children are deleted (per-row on the batch, record by id). 4 of 4 green.
  • packages/objectql/src/engine-cascade-delete-batch.test.ts, 4 new cases (14 total, green): a child the read door hides and the by-id delete refuses (403, nothing deleted, no batch hook ran); hidden and allowed by id (deleted by id, record); every child readable (batched); a cascade into the organization object deleted by id, record, marked.
  • Ablation 1, the read-door proof removed (if (batchable) {), via scripts/ablation-replace.mjs (anchor 1 to 0, blob e80908231 to 0c3d9ff28): plugin-security pin 1 failed / 3 passed ([batch] case: { kind: 'landed' }), objectql 2 failed / 12 passed. Restored, blob equals HEAD, git diff HEAD empty.
  • Ablation 2, the organization exclusion removed (true;): objectql 1 failed / 13 passed, the refusal Organizations are deleted one at a time, by id from organizationPredicateDeleteRefusal. Restored, blob equals HEAD, git diff HEAD empty.
  • No rebuild leg was needed: plugin-security's vitest config aliases @objectstack/objectql to its source.
  • Suites at 7d2730a95 under the verify lock: objectql (local project) 599 files, 13255 passed, typecheck exit 0; plugin-security 270 files, 6705 passed, 45 skipped, 4 failed (the parity cases above), typecheck exit 0; plugin-auth 277 files, 5499 passed, 10 skipped, typecheck exit 0.
  • Dogfood battery (pnpm --filter @objectstack/dogfood test under the verify lock, no shard, no path; the tree of 616735ceb, whose last commit changes only the changeset): VERDICT command-exit 0, Test Files 467 passed, 3 skipped (470); Tests 3959 passed, 42 skipped (4001); no failure. The log also carries 20 Schema sync FAILED lines for showcase_invoice (sqlite-wasm refuses add column with a non-constant default); that is log output, not a failed test, and this diff does not touch schema sync.
  • Gates: dispatch-gates --commands derived 98 commands at 7d2730a95; all 98 ran with exit 0 (96 in the sweep, check:type-check-debt and check:dual-build-cjs-loads under the lock); dispatch-gates --ran reconciles 98 derived, 98 run, 0 NOT MEASURED, 0 UNRUN. dispatch-gates --tier exit 0. check-durability-degradation-log-level exit 0 and objectql typecheck exit 0, the two CI reds of 4029ca241. pnpm lint exit 0 at eab93bab0. Body gates on this body (changeset-no-major, closing-keyword-parity, adr-0087-registration, empty-changeset, partof-closing-keyword) exit 0. CI families are read from the PR's check-runs, not re-run here.

Acceptance notes of this update: refusals the predicate arm raises and the by-id arm does not, read for S1: organizationPredicateDeleteRefusal (fixed here); the unscoped-multi shape check (not reached: the batch carries a predicate); the bulk per-row hook ceiling (a chunk is 500, the ceiling 10,000); plugin-security's predicate read cap (skipped for a nested write) and its caller-predicate guard (the predicate names id only); the credential-column guard (id is not one). None is of the one-term shape. One refusal found outside objectql, of a different shape: plugin-sharing's inferTargetId, above, carried by #33928.

🤖 Generated with Claude Code

https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh

@github-actions github-actions Bot added size/l documentation Improvements or additions to documentation protocol:data tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface labels Nov 15, 2026
@github-actions

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

📓 Docs Drift Check

This PR changes 2 package(s): @objectstack/objectql, @objectstack/spec, touching 24 documentable anchor(s).

38 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: node scripts/docs-audit/affected-docs.mjs --json 5a755791a90b2651be20dd0b9059b806abbafd4a.

⛔ 7 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails.

What this run could not see
  • 1 cross-cutting symbol(s) contributed no route anchor: recordId (4 routes)
  • 2 name(s) were too generic to anchor anything (single lowercase words)
  • the SDK route bridge reached 65 of 247 client-bound route-ledger rows — the other 182 have no registrar path: tail to select them, so pages documenting THEIR client methods cannot appear above, on this or any run. Of those 182: 0 are remediable by widening that discovery convention (an in-repo file declares the path; the convention did not scan it); 59 are structural — on a ledger where NOT ONE row is declared in-repo, so no discovery change reaches them at any price; 123 are undecided (no in-repo declaration, on a ledger that has other in-repo registrars — absence and an unreadable spelling are not distinguishable here). The rows themselves: node scripts/docs-audit/affected-docs.mjs --bridge-coverage
  • a page that states a rule by its inputs shares no identifier with the emitter that implements the rule, so an emitter-only diff cannot list it — not on this run and not on any run. Measured on fix(driver-sql): emit varchar(maxLength) for a text field a declared index keys on #11430: content/docs/protocol/objectql/types.mdx documents the text-family column mapping by the ObjectQL type names it maps FROM (text / textarea / html) while the diff changed createColumn; it went unlisted, and it was the page that diff falsified, in four places. No shared token exists to detect this on, so a rule your change carries has to be re-read by hand in the pages that restate it.
  • a key NAME is not a key, so the hand re-read the line above prescribes can land on the wrong schema. The same spelling is authorable on one governed type and a [REMOVED] tombstone on another for each of active, aria, joins, objects, template, tools and version (censused on [finding] tools is a key on BOTH AgentSchema (tombstoned, dead) and SkillSchema (live, cloud-attested), so a name-based search attributes skill examples to the agent key — it produced a false stop-the-line alarm on PR #19059 #19093 over the liveness ledger's governed types, top-level keys); nothing in a search result distinguishes the two, so a grep hit on a LIVE example reads as evidence about the DEAD key. Measured on fix(spec): the agent.tools liveness row says dead — it claimed live on a key the schema tombstoned #19059: content/docs/ai/agents.mdx was reported as contradicting the agent.tools tombstone over its tools: example at :161, which is inside the defineSkill({ block opened at :155 — the page was already correct. Settle ownership by PARSING the value against both schemas, never by the name: that literal PASSES SkillSchema, and as an AgentSchema it FAILS at tools with the tombstone prescription. ⛔ These names are not the whole class — a key retired through a .strict() guidance map leaves no tombstone in the walked shape and none of them here (tool.category, live as AIToolDefinition.category).

Coarse fallback — 175 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): node scripts/docs-audit/affected-docs.mjs --json 5a755791a90b2651be20dd0b9059b806abbafd4a → packageMentionDocs.

Which tree this was computed on

This run read content/docs from f043f22b3bd61fbfe476f7ff03b1dd5f07a2d2e6 — the merge of head 0b9b5c002d90ba121ea8215fffd65a091750f706 into base 5a755791a90b2651be20dd0b9059b806abbafd4a, which is what actions/checkout gives a pull_request run. Not the PR head.

A worktree cut from an older main holds a different content/docs, so re-deriving there can legitimately return a different list — that is a different tree, not a wrong row. To answer on the same tree:

# while this PR is open — GitHub drops the merge commit once it closes
git fetch origin f043f22b3bd61fbfe476f7ff03b1dd5f07a2d2e6 && git checkout f043f22b3bd61fbfe476f7ff03b1dd5f07a2d2e6
# afterwards, rebuild it from the two parents, which stay fetchable
git fetch origin 5a755791a90b2651be20dd0b9059b806abbafd4a 0b9b5c002d90ba121ea8215fffd65a091750f706 && git checkout -B drift-repro 5a755791a90b2651be20dd0b9059b806abbafd4a && git merge --no-ff 0b9b5c002d90ba121ea8215fffd65a091750f706

node scripts/docs-audit/affected-docs.mjs --json 5a755791a90b2651be20dd0b9059b806abbafd4a

⚠️ That checkout carried uncommitted changes, so the commit above does not fully identify what was read.

Advisory only, and a precision-first one (#9192): a page is listed because it names a
symbol, wire route or SDK method this diff touched — not because it mentions a changed
package. Each row says which anchor put it there, so a wrong row is reportable rather than
merely annoying. To re-verify, run the docs-accuracy-audit workflow scoped to these files:
node scripts/docs-audit/affected-docs.mjs 5a755791a90b2651be20dd0b9059b806abbafd4a → pass the list as
args.docs, on the commit named under Which tree this was computed on.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh

Request: review · PR #33887 · area S2 (A4) · Fixes #33699 · head 89dff98f61dd45bc47bef8b17d358db26676a759 · reviewer review-b

Test Core (3/8) red at this head, judged not this PR's: the only failure is packages/mcp mcp-file-tools.test.ts:950, a CPU-budget timing case; its imports do not reach the diff (objectql cascade/delete, recycle-bin), and it passes 47/47 locally. One re-run of the failed jobs follows; a second failure is treated as real.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

domain:server#5 · zhuangjianguo · session_01QsR2jTyY9BGjj9WBi7QgH6

Review claim · head 89dff98 · 2026-11-15T14:13Z

Contract-review-claim: session_01QsR2jTyY9BGjj9WBi7QgH6 · head 89dff98 · 2026-11-15T14:13Z

review (review-b, areas S2+S4): the verdict and the CONTRACT_REVIEW_TIER record (face narrowing + schema: packages/spec/src/data/hook.zod.ts) follow on this PR.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

domain:server#5 · zhuangjianguo · session_01QsR2jTyY9BGjj9WBi7QgH6

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 89dff98f61dd45bc47bef8b17d358db26676a759
Local-runs: none
Scope: packages/spec/src/data/hook.zod.ts, packages/objectql/src/engine-cascade-planning.ts, packages/objectql/src/engine-delete-and-aggregate.ts, packages/objectql/src/engine-middleware-and-context.ts, packages/objectql/src/engine-top-level.ts, packages/objectql/src/engine-cascade-delete-batch.test.ts, packages/objectql/src/engine-cascade-summary-rollback.test.ts, packages/plugins/plugin-auth/src/last-admin-guard.test.ts + packages/objectql/src/engine-cascade-planning.ts, packages/objectql/src/engine-delete-and-aggregate.ts, packages/objectql/src/engine-middleware-and-context.ts, packages/objectql/src/engine-top-level.ts

Inputs read: card #33699 body and all 10 comments (rulings 6893104201 and 6893661036, reports 6892420600, 6893257535, 6895711951), the PR body, the net diff 45dee177..89dff98f (9 files), the 66 check-runs on the head. Code outside the diff was read on origin/main, never reviewed: plugin-security security-plugin-authz-middleware.ts, security-plugin-addressed-writes.ts, security-plugin-rls-filter.ts; plugin-sharing sharing-plugin.ts, record-share-cascade.ts; plugin-auth last-admin-guard.ts; objectql engine-hook-dispatch.ts, recycle-bin/capture.ts.

① Derived judgments

  • Accept-set of packages/spec: unchanged. Named right. hook.zod.ts moves two TSDoc blocks only (dispatch.mode, referentialCascadeDelete); no z. shape, no .describe() string, no generated artifact. Spec property liveness, Flag docs affected by code changes, Type Check · consumer gates are green.
  • Published runtime contract of HookContext for a cascaded child delete: narrowed. Named right, with one omission (N3). dispatch.mode 'record' → 'per-row', dispatch.index 0..N-1 within the chunk, one shared dispatch.scope per chunk, input.options from { where: { id } } to { where: { id: { $in } }, multi: true }, and the chunk's beforeDeletes all run before its one set delete. The changeset and the dispatch.mode TSDoc say so. Not named: ctx.result in afterDelete moves from the driver's by-id answer to absent (buildPerRowAfterContexts passes no payload on a delete).
  • Public package surface of @objectstack/objectql: unchanged. Named right. CascadeBatchNarrowed, cascadeBatchIdsOf and the ids member of CascadeIssuedDelete are exported from engine-top-level.ts to its sibling section modules only; src/index.ts does not re-export that module.
  • Realtime, recycle bin, hook ceiling: unchanged. Named right. A claimed batch publishes one data.record.deleted per pre-image row; openRecycleBinCapture is reached only on the by-id branch and a child that joins cascadeDeleteSets opens none, so the bin stays one entry per root; a chunk is REFERENCE_PROBE_BATCH (500), under MAX_BULK_PER_ROW_HOOK_ROWS and under every plugin bound I read (last-admin DEFAULT_MAX_SCAN 1000, comment MULTI_WRITE_AUTH_LIMIT 1000, PREDICATE_WRITE_READABLE_ID_CAP 10,000).
  • "A permission refusal rolls the whole cascade back" (changeset, Unchanged): named WRONG for one direction. See M1.
  • Gate verdicts. 65 of 66 check-runs are success or skipped. Test Core (3/8) (run 132839243301) was in_progress when this record was written: it is not a verdict yet, and report 6895711951's triage of its earlier failure (an @objectstack/mcp CPU-budget case) is the dev's account, not a check-run conclusion. The adopting seat reads its conclusion before anything is queued.

② Semver level

  • .changeset/33699-cascade-delete-batch.md: @objectstack/objectql patch, @objectstack/spec patch. Right. Metadata-protocol: none is right: no authorable key, accepted value, requirement, default or meaning of an authored key moves; what moves is an engine-produced context a handler reads. AGENTS.md step 3: none takes patch, and a breaking non-protocol change ships patch with its BREAKING banner and ADR-0087 disposition. Both are present: the **BREAKING** paragraph with a FROM → TO mapping and the remedy, and exactly one adr-0087: not-required (no-migration-prescription) marker whose reason is true of the diff. Check Changeset is green.
  • Clause-②: no (narrowing) is the right arm: a hook that read dispatch.mode === 'record', a by-id input.options, or its siblings' absence on a cascaded child loses that. The line is byte-identical in the changeset, the PR body and claim 6893695718. The ! in the title matches.
  • Ruling 6893661036 "Declare it" is met in the changeset: the dispatch.mode change, the sibling-count flip with options.multi / referentialCascadeDelete as the remedy, and the fallback keeping today's shape so one cascade can show both.

③ Boundary flags

  • open_questions: empty in report 6895711951. Nothing to answer.
  • Deviation, plugin-auth test outside the objectql claim surface: accepted. It is the proof ruling 6893661036 leans on (the shipped guard judges the whole batch), it is test-only, and objectql cannot import plugin-auth.
  • Deviation, lint over touched files only and downstream suites left to CI: answered by the head's check-runs (Lint · ESLint, Lint & Repo Gates, Test Core 1, 2, 4 to 8 of 8 green), except shard 3/8, open as in ①.
  • Deviation, check:dual-build-cjs-loads not measured locally: answered, Build Core is green.
  • Deviation, the bench "before" run stamped with the branch commit: accepted. 155 statements matches the independent reading on the card at d7e1a5aa (6892420600); 57 is the dev's own run. Ruling precondition (2), a measured count replacing the estimate, is met.
  • Deviation, changeset Clause-② line corrected before pr_create: verified verbatim at this head.
  • Ruling precondition (1) is NOT met: escalate to the seat. security parity: a cascade delete through the predicate-delete arm still refuses (and rolls back) on a child the caller may not delete — pins for #33699 #33782 is open, labelled pm:dispatched, with no PR. The PR body says landing waits on it and the PR is a draft; that holds the queue, it does not answer M1.
  • Out-of-scope finding "never more rows ... security parity: a cascade delete through the predicate-delete arm still refuses (and rolls back) on a child the caller may not delete — pins for #33699 #33782's pin, noted, not filed": not accepted as carried. It is a property of this diff's own claim, and I found a concrete path. See M1.
  • Out-of-scope finding c1 "noted, not filed": escalate to the seat. Ruling 6893104201 bound this card to "plus c1 (the engine merges its three identical reads)", ruling 6893661036 kept everything but point 4, and Fixes #33699 closes the card with c1 undone and no carrier. It needs a follow-up card, or the closing keyword changed, before merge. No effect on the contract.
  • Security label: no hits path is under skills/** or ui/skills/**; nothing to add on that rule.

④ Design judgment

The narrowing itself holds against ruling 6893661036 (F1). deleteCascadedChildren issues delete(child, { where: { id: { $in: chunk } }, multi: true, context }) per 500 dependents; the predicate arm gives each row dispatch.mode: 'per-row', runs every beforeDelete, one set delete, then every afterDelete. The token claim is exact: claimReferentialCascadeDelete matches only a where that is precisely { id: { $in } } over the same id set, is taken before any middleware or hook, and is single-use, so a hook's own delete inside the dispatch is never marked; a by-id token refuses an object-shaped target as before. Grandchildren join the root's set through cascadeDeleteSets and get a token of their own. The entered bookkeeping covers a row reached by two paths and a member an earlier chunk's walk removed. The throw site of CascadeBatchNarrowed is before the first hook dispatch and outside the write try, and no middleware I read wraps what next() raises, so the walk's instanceof holds.

Consumers that relied on per-row cascade hooks, read against the new shape:

  • plugin-auth last-admin guard (resolveTargetIds): asks options.multi first and resolves the target set from options.where, so a chunk is judged whole; with two chunks the last one refuses. Same verdict as the by-id walk. The diff's [F1] describe pins both legs on a real SQLite engine.
  • plugin-sharing record-share-cascade / rule-hooks, service-storage file-reference-lifecycle: once-per-write work at dispatch.index === 0 off the shared dispatch.scope; correct for a chunk.
  • plugin-audit writeAudit, record-change triggers, membership-ended-session: per row off previous; unchanged.
  • plugin-sharing primary-bu-projection (afterDelete, reads remaining memberships): intermediate writes differ, final state equal.
  • Roll-ups: the batch hands recomputeSummaries the matched rows' foreign keys, once per chunk; the non-rollback outcome the changeset declares is the re-triaged fixture.

Findings

  • M1 · must-fix · the batch drops the read scope the by-id child delete enforces, so a child today's cascade refuses can be deleted. Read, not run.

  • S1 · should-fix · a cascade whose child object is sys_organization is newly refused. delete() throws organizationPredicateDeleteRefusal (409 DELETE_RESTRICTED) for any organization delete not by id, before any hook. deleteCascadedChildren catches CascadeBatchNarrowed only, so that chunk no longer reaches the by-id path, where the per-organization delete (refuseOrganizationDeleteWhileOwned, plugin-auth's clean-up) used to run. No shipped relation cascades into sys_organization (parent_organization_id is a plain lookup), so this needs an authored cascade relation on it; but it is a new refusal of a delete that works today, against ruling point (3), and the fix is one term in batchable. The general shape: any refusal the predicate arm raises that the by-id arm does not is now the cascade's answer.

  • N1 · nit · hook.zod.ts, dispatch.mode bullet, incomplete against the engine. It names one fallback ("a chunk the caller's scope narrows is deleted by id instead and keeps 'record'"). The engine has two more: a driver with no deleteMany, and a floored external driver; on those every cascaded child stays 'record'. And "every child's beforeDelete runs before any of them is gone" is true per chunk of 500 within one relation, not across chunks or relations; the changeset says "the chunk", the spec does not.

  • N2 · nit · hook.zod.ts, referentialCascadeDelete, "Why a declared key" is now stale. "ctx.user, ctx.session and ctx.input are identical between a child the cascade removes and a user's hand delete of that same child" no longer holds on the batch path: ctx.input.options differs (multi, the chunk predicate), and so does dispatch.mode. The key's contract is untouched.

  • N3 · nit · changeset FROM → TO omits ctx.result. In a cascaded child's afterDelete it was the driver's by-id answer and is now absent, as on every per-row delete context.

  • N4 · nit · the engine-delete-and-aggregate.ts comment "The read ran through the AST the middleware chain composed, so it is the caller's scope" overstates: it is the caller's WRITE scope. This is the sentence M1 turns on; it should say which scope once M1 is settled.

N1 to N4 ride the re-push M1 forces; none of them alone would hold the round.

Implemented-by: claude/area-A4-33699
Reviewed-by: session_01QsR2jTyY9BGjj9WBi7QgH6

VERDICT: FAIL

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

domain:server#5 · zhuangjianguo · session_01QsR2jTyY9BGjj9WBi7QgH6

Review — FAIL

Head-sha: 89dff98f61dd45bc47bef8b17d358db26676a759
Area: S2 / A4 · Fixes #33699
Contract-review record: #33887 (comment) (CONTRACT_REVIEW_TIER: schema face packages/spec/src/data/hook.zod.ts plus the narrowing face, from an isolated run). Its verdict is FAIL.

  1. M1 · must-fix · a nested cascade batch skips the read-door check. addressedPredicateWrite returns false when nested is true. I spot-checked this in packages/plugins/plugin-security/src/security-plugin-addressed-writes.ts, around lines 122–137. So a cascaded chunk deleted by predicate never passes through readableRowsScopeForPredicateWrite.
    • What goes wrong: a child that select-class RLS hides, but that a delete-class using policy admits, is now deleted. On the old by-id leg the same child refused with 403 and the whole delete rolled back.
    • What it contradicts: rulings 6893104201 (2) and 6893661036, epic [Epic] SQL performance: push the work down to the database on SQL drivers — SQL first, no slow paths kept for driver parity #33631, and the changeset's "Unchanged" line.
    • To clear it, do one of these:
      • check the chunk's ids against the read door, fall back to by-id for any chunk that check narrows, and add a both-legs pin on a real plugin-security stack; or
      • add a pin that refutes the scenario.
  2. S1 · should-fix · a cascade into sys_organization is newly refused. organizationPredicateDeleteRefusal (409 DELETE_RESTRICTED) fires before the by-id fallback, and deleteCascadedChildren catches only CascadeBatchNarrowed. This is a new refusal of a delete that works today. The fix is one term in batchable.
  3. N1–N4 · nits (details in the record). They can ride the re-push that M1 forces:
    • N1: the fallback list under dispatch.mode is incomplete (it misses the no-deleteMany driver and the floored external driver), and "before any of them is gone" holds per chunk.
    • N2: the "Why a declared key" text on referentialCascadeDelete is stale.
    • N3: the changeset FROM → TO omits that ctx.result in a cascaded afterDelete is now absent.
    • N4: "the caller's scope" should say "the caller's write scope".
  4. Precondition · seat's call. Ruling precondition (1) is not met. security parity: a cascade delete through the predicate-delete arm still refuses (and rolls back) on a child the caller may not delete — pins for #33699 #33782, the security parity pins card, is still an open issue with no PR. This PR should not land ahead of it unless the seat waives that.
  5. Scope versus Fixes. c1 (merging the three identical reads) is not done, but Fixes #33699 closes the card. Either do c1 here, or change the keyword to Part of #33699 and name where c1 goes.
  6. Clause-② / Metadata-protocol. The claim says Clause-②: no (narrowing). The record confirms that reading: dispatch.mode gains 'batch' on cascaded children and ctx.result goes away. This is BREAKING-shaped, so the changeset's FROM → TO has to be complete (see N3) before it can pass.
  7. File surface. In surface, apart from packages/plugins/plugin-auth/src/last-admin-guard.test.ts, which is a test-only edit outside the declared surface. It is acceptable, but name it in the claim's surface on the re-push.
  8. Check-runs at review time: 54 success, 11 skipped, and Test Core (3/8) still in progress.

On the re-push, a delta review covers only M1, S1 and items 4 and 5. The record's re-review is scoped to the same items.

…unk before batching it

A by-id child delete re-reads its row through the read door, so a child the
caller cannot read refuses and the cascade rolls back. A nested predicate
delete carries the write-class scope only, so the walk now asks the read door
for each chunk's ids and deletes the chunk by id when any is missing. A
cascade into the organization object keeps the by-id path. Pinned on a real
security stack on both legs; spec TSDoc and changeset name every fallback and
the absent afterDelete result.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh
@github-actions github-actions Bot added size/xl and removed size/l labels Nov 15, 2026
…r refuses

A refused read routes the chunk to the by-id path; the catch now says so at
debug instead of answering silently, which the read-seam invention guard
requires. The walk's host type names find.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh

Blocked-by: #33928 (PR #34033, area S1). Test Core (8/8) is red at 7d2730a956c55bf529fcb29d1cc53ba819c79a2d, and it was red at eab93bab too, on the same 4 cases in packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts (blocks 2, 3, 3, 4). Each expects landed and gets 403 FORBIDDEN.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW

Contract-review-claim: session_01L9qibxTeW8xHnxoHxWNHWW · head — · 2026-11-15T19:01Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW

Contract-review-claim: session_01L9qibxTeW8xHnxoHxWNHWW · head 616735c · 2026-11-15T19:02Z

This claim replaces the one above it from this seat, which named no head.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 616735ceb85dcd23b446d4fa6d5175b90aa0a4ed
Local-runs: none
Scope: packages/spec/src/data/hook.zod.ts, packages/objectql/src/engine-cascade-planning.ts, packages/objectql/src/engine-delete-and-aggregate.ts, packages/objectql/src/engine-middleware-and-context.ts, packages/objectql/src/engine-top-level.ts, packages/objectql/src/engine-cascade-delete-batch.test.ts, packages/objectql/src/engine-cascade-summary-rollback.test.ts, packages/plugins/plugin-auth/src/last-admin-guard.test.ts, packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts + packages/objectql/src/engine-cascade-planning.ts, packages/objectql/src/engine-delete-and-aggregate.ts, packages/objectql/src/engine-middleware-and-context.ts, packages/objectql/src/engine-top-level.ts

Read at 2026-11-15T19:15Z. First review of this head by this seat, taken on patrol as owed; claim: comment 6899642842; prior record 6896079092 (FAIL) is on an earlier head. Independence: implemented in a zhuangjianguo lane; neither dispatched nor implemented by os-tesla.

Inputs read: card #33699 body and all 12 comments (rulings 6893104201 and 6893661036, surface amendment 6893212568, reports 6895711951 and 6899217909), the PR body, all 7 PR comments (record 6896079092 and review 6896089195 included), the net diff a3aa1d29..616735ce (10 files), the changeset, and the 71 check-runs on this head with the logs of the two failed Test Core shards. Code outside the diff was read at this head, never reviewed: plugin-security security-plugin-authz-middleware.ts (steps 2.7, 2.9, 3); plugin-sharing sharing-plugin.ts (the write middleware, inferTargetId) and sharing-service.ts (checkDelete, admitsByIdWrite, buildWriteFilter); objectql recycle-bin/capture.ts, engine-delete-cascade.ts (collectCascadeDeleteSet), engine-hooks-and-functions.ts (opensAfterAbortUnit), engine-hook-dispatch.ts; service-storage attachment-lifecycle.ts; content/docs/automation/hooks.mdx, content/docs/references/data/hook.mdx; AGENTS.md step 3.

Prior findings (record 6896079092), judged on this tree:

  • M1 (read scope dropped by the batch): closed. readDoorReturnsChunk asks the public find() under the walk's context for the chunk's ids before the batch is issued; any id missing, or a declared 4xx from the read door, sends the chunk to the by-id path, and a store fault propagates. Together with the doomed read through the delete-class AST this is the conjunction the by-id leg's step 2.7 re-read asks, and where no write-class filter binds the by-id path gives today's answer. Pinned on a real ObjectQL + SqlDriver + SecurityPlugin stack on both legs with a control (cascade-batch-read-scope.test.ts, 4 of 4 green in Test Core 8/8 on this head).
  • S1 (a cascade into the organization object newly refused): closed for the organization object (childName !== ORGANIZATION_OBJECT in batchable, pinned with the marker). Its general shape, "any refusal the predicate arm raises that the by-id arm does not is now the cascade's answer", is open: it is M1 below.
  • N1, N2, N4: closed, read in hook.zod.ts and the engine-delete-and-aggregate.ts comment at this head.
  • N3 (FROM to TO omits ctx.result): closed for ctx.result; changed into S1 below, which names two more rows the mapping lacks.
  • Boundary item, ruling precondition (1): changed, still open. The test(plugin-security): security-parity pins for cascade delete across child-delete shapes #33927 pins are in this tree and 4 of their 8 cases are red on this head. See M1.
  • Boundary item, c1 under a closing keyword: closed. The body reads Part of #33699 and names c1 as what stays on the card.

① Derived judgments

  • Accept-set of packages/spec: unchanged. Named right. hook.zod.ts moves three TSDoc blocks (dispatch.mode, the referentialCascadeDelete "why a declared key" paragraph, the token sentence). No z. shape and no .describe() string moves, so no generated JSON schema, baseline or reference page moves: content/docs/references/data/hook.mdx still projects the unchanged .describe(). Spec property liveness, Flag docs affected by code changes, Type Check · consumer gates are green. No spec test is owed for prose.
  • Published runtime contract of HookContext on a cascaded child delete: narrowed. Named right, with two rows missing (S1). Named: dispatch.mode 'record' to 'per-row', dispatch.index, input.options with multi: true, ctx.result absent, the before-phase of a chunk running whole ahead of its one set delete, the four by-id fallbacks. Not named: dispatch.scope is now one object shared by the chunk's children, and each phase of each child gets a fresh context object.
  • Public package surface of @objectstack/objectql: unchanged. Named right. CascadeBatchNarrowed and cascadeBatchIdsOf reach sibling section modules only.
  • Hand-written docs and skills: nothing stale found. No page under content/docs or skills teaches a cascaded child's dispatch.mode or a sibling-count delete hook; hooks.mdx row "a by-id delete() that cascades" stays true. Skills-docs: none holds.
  • "A cascade the caller may complete still completes" (ruling 6893104201 point 3; changeset, Unchanged): NOT kept by this tree. See M1.
  • "The recycle bin keeps one entry per root": true as written; one population loses its entry. See S2.

② Semver level

  • @objectstack/objectql patch, @objectstack/spec patch: right. Metadata-protocol: none is right (no authorable key, value, requirement or default moves), and AGENTS.md step 3 gives a breaking non-protocol change patch with its banner and disposition. The **BREAKING** paragraph, the FROM to TO list, the remedy (options.multi, referentialCascadeDelete) and exactly one adr-0087: not-required (no-migration-prescription) marker are present; the marker's reason is true of the diff. Clause-②: no (narrowing) is the right arm and is byte-identical in the changeset and the PR body; the title carries !. Check Changeset and PR-body guards are green. The mapping is incomplete by S1.
  • CI on this head: 55 success, 13 skipped, 3 failure. It is not green.
    • Test Core (8/8) failure: packages/plugins/plugin-security/src/cascade-delete-security-parity.test.ts, 4 of 8 failed, each expected { kind: 'refused' } to deeply equal { kind: 'landed' } with 403 FORBIDDEN. This is the diff's own behaviour on the stock stack: M1.
    • Test Core (7/8) failure: @objectstack/scenarios test/runner/run-date.test.ts, 3 cases Test timed out in 5000ms. The package is not in the diff and nothing in the log ties it to a delete; I did not judge it further. It still has to be green on the head that lands.
    • Test Core (the aggregate) failure follows from the two.

③ Boundary flags

  • open_questions: empty in report 6899217909.
  • Deviation, two test files outside the objectql claim surface (last-admin-guard.test.ts, cascade-batch-read-scope.test.ts): accepted, both test-only, both named in the PR body, and both are proofs a ruling or the prior record ordered.
  • Deviation, pnpm lint and the gate sweep run on earlier commits than the head: answered by this head's check-runs (lint and repo gates green).
  • Deviation, the branch is behind main by the lane's own count and was not merged again: consistent with the declared land order, and it means this head is not the head that lands. A fresh record is owed on the merged head whatever this one says.
  • Ruling 6893661036 precondition (1): not met on this tree. The pins merged (test(plugin-security): security-parity pins for cascade delete across child-delete shapes #33927) and are here, red. A precondition of pins is met by pins that pass.
  • Ruling precondition (2), the measured statement count: met (155 to 58, in the changeset).
  • Part of #33699: what is left is named. c1 stays on the card, in the body, the report and the keyword. Ruling 6893104201 bound the card to the cascade arm plus c1, so the set_null batch in the card's original Target is not this card's remainder.
  • Out-of-scope finding "plugin-sharing inferTargetId, carrier plugin-sharing: a write whose id is an operator object (where:{id:{$in:[…]}}) is gated as a by-id write of the row "[object Object]", so a member's multi delete of rows it owns is refused #33928": accepted as carried, and it is exactly why this head cannot pass (M1). The lane's choice not to reshape the predicate around it is the PM's order and I do not reopen it.
  • Security label: the rule this change must keep is stated in ④; I found no path on which this tree breaks it, and one direction is not demonstrated by a passing test at this head.

④ Design judgment

The batch itself, against ruling 6893661036 (F1), read in the cited code.

  • Rows deleted. The walk collects a relation's cascade dependents over the whole root set (deduplicated, so a multi-valued child naming two roots goes once), filters each chunk against entered at issue time, and issues delete(child, { where: { id: { $in } }, multi: true }). The predicate arm deletes exactly the rows its scoped read returned, and the claimed batch refuses to proceed (CascadeBatchNarrowed, before any hook or write) unless that read returned every id asked for. So a batch removes the chunk or nothing; a short chunk goes by id and answers as today.
  • Nested cascades, restrict and set_null siblings. A member chunk joins the root's set through cascadeDeleteSets, so the child's own relations are walked once for the chunk with the same restrict, set_null and required-escalation judgments as the by-id child delete, and grandchildren are batched in turn. Relation order is unchanged, and the pre-write refuseRestrictsInsideOwnCascade is untouched. A row reached by two paths or by a self-reference is entered before the chunk's own walk and removed once.
  • Multi-valued relations: the probe attribution and the member-removal write are untouched; only the cascade limb moved.
  • Chunk boundaries: 500 per statement, under the per-row hook ceiling, pinned at 501.
  • Transaction and partial failure: the batch runs inside the root's unit as the by-id child did; a before-phase or after-phase refusal rolls the cascade back (pinned on a driver that really rolls back). On a runtime that cannot roll back the whole chunk is gone where one child was; the changeset says so and the re-triaged fixture pins it.
  • Recycle bin: the root's capture snapshots the collected set before the walk and a member opens no entry on either shape. One population differs: S2.
  • Hooks: each child's beforeDelete and afterDelete run once with previous its own row and the marker in both phases (pinned, grandchildren included). The token claim is exact-set, single-use and taken before any middleware, so a hook's own delete is not marked.
  • Roll-ups: the batch hands recomputeSummaries the matched rows once per chunk; same parents recomputed.
  • Realtime: one data.record.deleted per child from its pre-image, never the bulk event (pinned).
  • Audit and share clean-up per child: per row off previous; the test that proves it on the full stack (test(plugin-security): security-parity pins for cascade delete across child-delete shapes #33927 block 4) is one of the four red cases, so on this head it is read, not demonstrated.
  • Security rules of the child. The rule: a cascade batch deletes no child the by-id delete of that child would refuse (delete permission, row scope, tenant wall), and refuses the whole cascade where the by-id delete refuses. Read scope and row-level write scope: kept, by the read-door proof plus the narrowed-batch check, on the plugin-security axis. Tenant wall: the same Layer 0 predicate rides the batch's AST and driver options. Record sharing: I found no path on which this tree deletes a child the by-id sharing gate refuses, and the parity block that would show it ("never more rows") is red at this head, so that direction is not demonstrated here.

Findings

  • M1 (must-fix) — continues the general shape of prior S1 and the prior precondition flag. At this head a cascade the caller is entitled to complete is refused on the stock stack: with plugin-sharing loaded, the batch on an owner-scoped child answers 403 FORBIDDEN where today's by-id cascade lands. The refusal is not CascadeBatchNarrowed, so the walk does not fall back and the parent delete fails. Four merged test(plugin-security): security-parity pins for cascade delete across child-delete shapes #33927 parity cases are red for it in Test Core (8/8), including the completes-case, the never-more-rows block and the per-child audit case. This breaks ruling 6893104201 point (3) (no new refusal), the changeset's own account of what is unchanged, and ruling 6893661036 precondition (1). The defect that turns the batch into a refusal sits in plugin-sharing and is carried by plugin-sharing: a write whose id is an operator object (where:{id:{$in:[…]}}) is gated as a by-id write of the row "[object Object]", so a member's multi delete of rows it owns is refused #33928; this diff is what makes a cascade reach it, so the tree at this head is what fails. Clears with: plugin-sharing: a write whose id is an operator object (where:{id:{$in:[…]}}) is gated as a by-id write of the row "[object Object]", so a member's multi delete of rows it owns is refused #33928 merged, main merged into this branch, all 8 parity cases and Test Core green on that head, and a fresh record on that head that re-reads the four cases now green for a refusal as well, since at this head a refusal can come from either door.
  • S1 (should-fix) — continues prior N3. The BREAKING changeset's FROM to TO lacks two rows a delete-hook author can meet silently: (a) ctx.dispatch.scope FROM one scratch object per cascaded child TO one object shared by every child of the chunk, both phases; (b) FROM the same context object in a child's beforeDelete and afterDelete TO a fresh context per row per phase, so a value a beforeDelete handler leaves on ctx no longer reaches that child's afterDelete (the spec's own scope bullet says such stashes stop arriving on a per-row dispatch; it now applies to cascaded children). Remedy line to add: keep cross-phase state in ctx.dispatch.scope, keyed by ctx.input.id. A pin for (a) in engine-cascade-delete-batch.test.ts would make the row true by test.
  • S2 (should-fix) — new; read, not run. A cascade dependent the walk's probe finds that the collect phase did not hold (a row a hook of this same cascade wrote or re-pointed after the set was collected) used to be deleted by id as the root of its own cascade, with its own recycle-bin entry; batched, it is deleted with no entry, because the predicate arm opens none. Clears with either one term in deleteCascadedChildren sending non-members of cascadeSet.members down the by-id path, with a pin, or a both-shapes pin showing today's by-id path writes no entry for such a row either.
  • N1 (nit) — new. The four by-id fallbacks are pinned on a bare engine with stand-in middleware; CascadeBatchNarrowed crossing the real security and sharing middleware chain back to the walk's instanceof is pinned only by the test(plugin-security): security-parity pins for cascade delete across child-delete shapes #33927 cases, which this head cannot read. Nothing to change in this diff beyond M1's re-read.

Tests otherwise pin each behaviour with a control: order and shape (control: the by-id shape on the no-deleteMany leg), the sibling count, chunking, realtime, both rollback phases, the narrowed fallback refused and allowed, the read-door fallback refused, allowed and all-readable, the organization exclusion, and the last-administrator guard on both legs with an allowed case.

Implemented-by: claude/area-A4-33699
Reviewed-by: session_01L9qibxTeW8xHnxoHxWNHWW

VERDICT: FAIL

scbdzhwl pushed a commit to scbdzhwl/objectstack-analysis that referenced this pull request Nov 16, 2026
…reader over unrestricted hops (objectstack-ai#33897)

<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} -->
_Requested by **Steedos** · [project
thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbSUQWB2j9eHYsRcrCiq1X1C)_

**Do not land before objectstack-ai#33820 (ADR-0139 status-line amendment) merges.**

## 维护者速读

-
改了什么:对"受控于父对象"且主从字段必填的明细对象,只有同时持有明细"查看全部"、且每一级主对象读取范围都不受限的读者(典型是单租户管理员),读取时不再带父链子查询;其他读者完全不变;所有写操作(条件更新/删除、按
id 写、钩子里的读取)仍带父链,行为与 main 完全一致。
- 为什么改:这类读者的父链子查询挡不住任何有主记录的行,只拖慢管理员的列表、计数和汇总(卡上 1M 行实测快 29% 到 42%,本 PR
未重测)。
-
风险与回滚:该类读者的合计、计数、汇总可能包含孤儿行(主记录缺失或为空的明细),这是维护者裁决接受的;限制读者、仅有明细查看全部的读者、普通成员仍看不到孤儿行;回滚即
revert 本 PR。
- 先看:`engine-readable-ids-permission-formula.ts` 第 5
步、`readerViewsAllOf` 与
`READABLE_IDS_WRITE_IN_FLIGHT`;`engine-middleware-and-context.ts`
新增的写作用域;`security-plugin-cbp-read-filter.test.ts` 的反向钉子与写路径钉子。
- 两分钟验证:`pnpm --filter @objectstack/plugin-security exec vitest run
--maxWorkers=2 src/security-plugin-cbp-read-filter.test.ts`,预期 12 个测试全绿。
- 需要你做的:等 objectstack-ai#33820(ADR-0139 状态行修订)合并后再合并本 PR。

Fixes objectstack-ai#33696

Clause-②: no
Metadata-protocol: none

## Ruling

Ruling record 6893666857 (replaces 6893097935), quoted verbatim as it
binds this card:

> - The parent chain is dropped only for a reader who holds view-all on
the detail AND whose every master hop answers unrestricted (the engine's
per-hop scope, not `hasSuperuserReadBypass`), with a required master FK.
That reader sees null and dangling-FK rows inside its own tenant wall,
consistent with objectstack-ai#30905 ruling A. Every other reader, members included,
keeps the chain unchanged.
> - This deliberately lifts objectstack-ai#24932 ruling B item 4 and ADR-0139 D6's ⛔
for that reader class only. **The PR must not land before the ADR-0139
status-line amendment** (citing this record; ADR-0055's 10-22 note in
step) merges. That amendment is a docs/adr/** card for the skills lane,
which the seat files.
> - Pins: the three controlled-by-parent-leaf-switch tests are rewritten
for the view-all + unrestricted reader. Reverse pins stay: a reader with
a restricted master hop, and a reader with view-all on the detail only,
still never see null or dangling rows.
> - Release note: totals, counts and aggregates for that reader may
include orphan rows. A follow-up card to close the orphan sources
(option B of the original request) is owed as the PR's one loose-ends
card.
> - Multi-tenant deployments: a tenant admin's master scope is the
tenant wall, so it is not unrestricted. No speed-up there, by design;
widening that is a separate decision.

## Review 6895328067: route (a), write doors unchanged

The review found that the drop reached the write doors. The security
plugin's predicate-write narrowing, its 2.8 gate's predicate leg and its
step-2.7 by-id read all ask `ql.find`/`findOne` under the caller's
context. The seat ruled route (a), claim amendments 6895345175 and
6895620230: the write paths stay byte-identical to main. A write's
middleware chain now runs inside an engine async scope, and step 5 drops
nothing inside it. No plugin-security write-door source file changes.

## What changes

- `packages/objectql/src/engine-readable-ids-permission-formula.ts`:
`composeReadableIdsChain` gains step 5. A leaf over the REQUIRED master
of a `controlled_by_parent` object, in an AND position and as the whole
comparand of a `$in` on its `master_detail` field, is dropped instead of
composed. Two conditions must both hold:
- the master's answered scope is `undefined` (admitted, no row
condition), per hop: a nested scope left empty once its own leaves are
dropped answers `undefined`, so a chain drops whole only when every hop
is unrestricted;
- the caller holds View All (`viewAllRecords` or `modifyAllRecords`) on
the detail, read from `ISecurityService.getEffectiveObjectPermissions`
(`readerViewsAllOf`, asked once per read). A delegated caller, a service
without that member, or a call that throws keeps the chain. A failure
costs the subquery, never a row.

An optional master, a leaf inside `$or` or `$not`, and every
non-`controlled_by_parent` object compose exactly as before.
- `packages/objectql/src/engine-middleware-and-context.ts`: **approved
widening** (claim amendment 6895620230, `executeWithMiddleware` only,
+4/−1). For a write-epoch operation (insert, update, delete, purge,
restore), the middleware chain runs inside
`READABLE_IDS_WRITE_IN_FLIGHT`, an `AsyncLocalStorage` exported from
`engine-readable-ids-permission-formula.ts`. `readerViewsAllOf` answers
false inside it, so every read made while a write runs keeps the chain:
the security write-door reads, hook reads and cascade reads. It is an
async scope rather than a context stamp, for the reason
`SecurityPlugin.engineOperationScope` gives: a context is shared and
spread across those very reads.
- `packages/objectql/src/engine.ts`: **approved widening** (coordinator,
2 lines). The private `composeReadableIdsChain` host literal gains a
`_registry` getter, the same getter shape the neighbouring host literals
use.
- `packages/plugins/plugin-security/src/security-plugin.ts`: a
prose-only paragraph in the `computeControlledByParentFilter` docblock
(review should-fix 2). It says the drop is read-only and that write
paths keep the chain.
-
`packages/plugins/plugin-security/src/security-plugin-cbp-read-filter.ts`:
a docblock paragraph only. The leaf is still written for every caller,
and the engine drops it. View All on the detail alone never drops it.
-
`packages/plugins/plugin-security/src/controlled-by-parent-leaf-switch.test.ts`:
**approved widening**. The existing pins are unchanged. A new reader
(View All on the account, contact, quote and line objects) gets legs in
the three leaf-switch tests, and those legs see the dangling and null
rows and run one statement with no `in (select`.
- `.changeset/33696-drop-unrestricted-cbp-chain.md`: patch for
`@objectstack/objectql`, with the ruling's release-note sentence.

Perf, the card's measurement, not re-run here (1M rows): page SQLite 397
to 281 ms, PG 97 to 56 ms; total SQLite 217 to 136 ms, PG 78 to 54 ms.

## Tests

Pins on a real stack (`security-plugin-cbp-read-filter.test.ts`:
ObjectQL, SqlDriver on better-sqlite3, the real SecurityPlugin and
SharingService, orphan rows seeded through the driver), 8 tests:

- (a) View All on the detail over unrestricted hops: no parent-chain
subquery, every stored row including the orphans, count 7, `findOne` of
a dangling row. Plus parity on the rows whose chain resolves, and the
analytics door (the `getReadFilter` scope passed as `where`) composing
the same way.
- (b) a reader with a restricted master hop keeps the whole chain and
sees no orphan.
- (c) a reader with View All on the detail only keeps the whole chain
and sees no orphan.
- (d) a plain member keeps the chain over a restricted master and over
an unrestricted (`public_read_write`) one. The admin control on the same
object drops it.
- (e) isolated tenancy: org A and org B never read each other's rows,
and the tenant wall keeps the chain.
- An optional master keeps its leaf.

Write-door pins (review 6895328067, route (a)), in the same file, 4
tests. The View All admin reads over unrestricted hops, and the set it
writes holds orphans:

- a hook's read inside a write, under the caller's context, keeps the
chain and sees no orphan (control: the same caller's plain read drops
it);
- a predicate delete over a set holding an empty-required-master orphan
lands on the other row and leaves the orphan;
- a predicate update over a set holding an empty-master orphan and a
dangling-master orphan lands on the other row and leaves both;
- a by-id update of a dangling orphan and a by-id delete of an
empty-master orphan both still answer `RECORD_NOT_FOUND` / 404.

Measured on head 2c6025c's objectql source (the three objectql files
set back to 2c6025c, then restored with `git diff HEAD` empty), all 4
are red:

| Pin | Red on 2c6025c |
|---|---|
| hook read | it sees the 4 orphans (`line_a_ghost`,
`line_a_ghost_account`, `line_a_null`, `line_b_ghost`) |
| predicate delete | refused: `MISSING_REQUIRED_FIELD` / 422 |
| predicate update | refused: `MISSING_REQUIRED_FIELD` / 422 |
| by-id write | refused: `PERMISSION_DENIED` / 403, not
`RECORD_NOT_FOUND` / 404 |

On origin/main's objectql source, the 3 write pins pass and the hook
pin's write leg passes. Its plain-read control leg fails there, as it
should, because main drops nothing. Ablations (`ablation-replace`, every
restore checked as blob == HEAD):

- deleting the `READABLE_IDS_WRITE_IN_FLIGHT` guard in
`readerViewsAllOf` turns all 4 red;
- running a write's chain outside the scope in `executeWithMiddleware`
turns all 4 red.

Unit pins (`engine-readable-ids-nested-composition.test.ts`, a new
describe, 17 tests in the file): the drop at the root, in an `$and` and
in a merged-key position; a restricted hop keeps both leaves; `$or`,
optional and non-cbp positions compose; five kinds of caller without
View All on the detail keep the chain (no View All, View All on another
object, no service member, a service that throws, delegated); a
non-readable master gives `$in: []`.

Ablations, on the committed implementation (`node
scripts/ablation-replace.mjs`, every restore proven `blob == HEAD
8ec17d5` and `git diff HEAD` empty):

| Mutation | Real-stack pins red | Unit pins red |
|---|---|---|
| per-hop check removed (drop whenever the master answered) | (b), (c) |
restricted hop keeps; caller without View All keeps |
| `readerViewsAllOf` answers `true` | (d) | caller without View All
keeps |
| step 5 disabled | (a), parity, analytics, (d) admin control | drop at
root and `$and`; `$or`/optional/non-cbp |

<details><summary>Full suites</summary>

Runs were under `scripts/pm/os-verify-lock.sh`, with each exit captured
before any pipe.

On head `df3fb3b9` (the implementation plus origin/main at c59198f,
which includes objectstack-ai#33884's step-2.8 changes):

- `@objectstack/plugin-security`: `pnpm test` exit 0, 269/269 files,
6705 passed and 45 skipped. `typecheck` exit 0.
- `@objectstack/objectql`: `pnpm test` exit 0, 598/598 files, 13238
tests. `typecheck` exit 0.

On head `3089656f` (the same implementation, one main merge earlier),
the direct runtime dependents of objectql, after `pnpm --filter
'PKG^...' build` (exit 0). All exits 0:

- example-embed-objectql 1/1 files, 2 tests
- plugin-audit 94/94, 1541
- plugin-email 53/53, 1018
- plugin-pinyin-search 4/4, 39
- plugin-sharing 74/74, 1525
- plugin-webhooks 25/25, 307
- runtime 605/605, 10958 (19 skipped)
- scenarios 34/34, 859
- service-automation 282/282, 3982
- cloud-connection 82/82, 1224
- example-todo 9/9, 249
- plugin-dev 10/10, 89
- verify 52/52, 439
- cli `vitest run --project unit` 422/422 files, 6002 tests

The second main merge touches none of this PR's files.

Packages that depend on objectql only as a devDependency, the cli
integration tier, and dogfood are left to CI. The PR title has no `!`,
so the full dogfood battery is not owed.

</details>

## Acceptance notes

- Loose-ends card owed (the ruling's one): stop orphan rows at their
sources (option B of the original request). Measured sources: a
system-context insert or update that names a missing master is stored
(the documented residual in `engine-referential-integrity.ts`), and
promoting an optional master to required leaves rows with a NULL foreign
key. The seat files it.
- objectstack-ai#33820 (skills lane) carries the ADR-0139 status-line amendment. This
PR does not touch `docs/adr/**`.
- Under walled tenancy the tenant admin's master scope carries the
Layer-0 tenant equality, so nothing is dropped there, by design. Pin (e)
measures this.
- Open PR objectstack-ai#33652 (another seat) edits the same function in
`engine-readable-ids-permission-formula.ts`: the import line and the
final `composeReadableIdsLeaves` call. The two PRs conflict as text, and
whichever lands second rebases. They do not conflict in meaning. Its
planned relation-semi-join leaves are never asked into `chain.answers`,
and step 5 drops only a leaf whose master has an answer, so it leaves
them alone. objectstack-ai#33703 touches `engine.ts` far from this literal.

## Verification

- At head `df3fb3b9`, `dispatch-gates --commands --repo
objectstack-ai/objectstack` derived 77 gate families.
- 74 of them ran locally, every one exit 0. `--ran` reconciliation: "77
derived, 74 run, 0 NOT-MEASURED, 3 UNRUN". The 3 are whole-repo families
left to CI: `check:i18n`, `check:dual-build-cjs-loads`,
`check:type-check-debt`.
- `node scripts/check-nul-bytes.mjs` exit 0. `pnpm lint` (whole-repo
eslint) is left to CI.
- `git merge-tree --write-tree --name-only` from `df3fb3b9`:
- origin/main: clean. Main is now 18 commits ahead, and none of them
touches this PR's files.
- objectstack-ai#33887 (`engine-middleware-and-context.ts`, its
`claimReferentialCascadeDelete`): clean. This PR's hunk stays inside
`executeWithMiddleware`.
  - objectstack-ai#33884: merged into main as c59198f and included in this head.
- objectstack-ai#33652: conflicts in `engine-readable-ids-permission-formula.ts`, in
two hunks: the import block and the step-5 / final
`composeReadableIdsLeaves` lines. That overlap was known before. The two
changes do not conflict in meaning, and whichever lands second rebases.

---

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv
<!-- signed: domain:server#5 · zhuangjianguo ·
session_01QsR2jVPGBoi3MCGoKbW1Hv -->

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
…leted by id, keeping its own recycle-bin entry

The batch takes only the members the collect phase gathered. A row a hook
of the same cascade wrote after the set was collected goes by id, as the
root of its own cascade, as before the batch: a predicate delete opens no
recycle-bin entry and the root's entry snapshotted only the members.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh
…d each phase is a fresh context

The FROM -> TO names the two rows a delete-hook author meets silently, with
the remedy: keep cross-phase state in ctx.dispatch.scope keyed by
ctx.input.id. Pinned on both shapes in engine-cascade-delete-batch.test.ts.
The fallback list names the dependent the collected set never held.

Co-Authored-By: Claude <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh
@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW

Contract-review-claim: session_01L9qibxTeW8xHnxoHxWNHWW · head 5ed2476 · 2026-11-16T06:00Z

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW

Contract review

Served-tier: CONTRACT_REVIEW_TIER
Head-sha: 5ed2476610bd5cca57ca8a00412215da52354a77
Local-runs: none
Scope: packages/spec/src/data/hook.zod.ts, packages/objectql/src/engine-cascade-planning.ts, packages/objectql/src/engine-delete-and-aggregate.ts, packages/objectql/src/engine-middleware-and-context.ts, packages/objectql/src/engine-top-level.ts, packages/objectql/src/engine-cascade-delete-batch.test.ts, packages/objectql/src/engine-cascade-summary-rollback.test.ts, packages/objectql/src/recycle-bin/capture.test.ts, packages/plugins/plugin-auth/src/last-admin-guard.test.ts, packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts + packages/objectql/src/engine-cascade-planning.ts, packages/objectql/src/engine-delete-and-aggregate.ts, packages/objectql/src/engine-middleware-and-context.ts, packages/objectql/src/engine-top-level.ts

Read at 2026-11-16T06:10Z. Delta review of this head against FAIL 6899834361 at 616735c; claim: comment 6908703696; no lane request (owed per check-owed-reviews). Independence: implemented in a project thread for domain:server#5 (zhuangjianguo); reviewed by os-tesla, who neither dispatched nor implemented it.

Inputs read: card #33699 body and its 12 comments, the PR body, the 11 PR comments (records 6896079092 and 6899834361 included), the three first-parent commits 616735ce..5ed24766, the net diff 31eb2aed..5ed24766 (11 files), the changeset, and the 67 check-runs on this head with the Test Core 8/8 log. Code outside the diff was read at this head, never reviewed: objectql engine-delete-cascade.ts (collectCascadeDeleteSet), recycle-bin/capture.ts (openRecycleBinCapture), cascadeDeleteRelations; plugin-sharing sharing-plugin.ts (the write middleware, engineByIdTarget, the bulk branch); plugin-security cascade-delete-security-parity.test.ts (the #33927 pins).

What moved between the two heads, the PR's own work kept apart from main's.

Prior findings (record 6899834361), judged on this tree.

  • M1 (a cascade the caller may complete was refused on the stock stack; four test(plugin-security): security-parity pins for cascade delete across child-delete shapes #33927 pins red): closed. plugin-sharing: a write whose id is an operator object (where:{id:{$in:[…]}}) is gated as a by-id write of the row "[object Object]", so a member's multi delete of rows it owns is refused #33928 landed on main as fix(plugin-sharing)!: the write gate judges by id exactly the writes the engine runs by id #34033 and is in this tree by the merge. The sharing write gate now takes its by-id or bulk branch from the engine's own dispatch decision, so the batch is judged by the bulk write scope like every other predicate delete. cascade-delete-security-parity.test.ts is 8 of 8 green in Test Core (8/8) on this head, and Test Core is green. The re-read the clearing condition asked for, of the four refusal cases: at this head the batch can no longer be refused at that gate, so a refusal a caller meets is the by-id child delete's. Case 1.1 and the unreadable case of block 2 reach it through the read-door question; case 1.2 and the edit-shared case reach it through the narrowed batch, on the real security and sharing chain, and 1.2 asserts the cascade's refusal deep-equal to the caller's own by-id delete of that child. So their green is now evidence of the fallback, which it was not at 616735c.
  • S1 (two FROM to TO rows missing): closed. Both rows are in the changeset with the remedy line as asked, and the pin runs both shapes: batched, one dispatch.scope object across the chunk's six dispatches, a value left on ctx absent in afterDelete, the keyed scratch present; by id (no deleteMany), three scopes and the stash arriving.
  • S2 (a dependent the collected set never held lost its recycle-bin entry): closed by the first of the two offered ways. Non-members go by id as the root of their own cascade; openRecycleBinCapture opens an entry for exactly such a row. The pin seeds a grandchild from a batched child's beforeDelete, after the collect, and expects the entries account/acc1 and note/n9 with the root's snapshot unchanged. It discriminates: the test driver has deleteMany, so without the member filter the late row rides the batch and gets no entry.
  • N1 (the narrowed fallback crossing the real middleware chain pinned only by cases this seat could not read): closed with M1; those cases are green and read above.
  • Boundary item, ruling 6893661036 precondition (1): closed. The pins are in the tree and pass.
  • Boundary item, "this head is not the head that lands": closed for the merge that was owed; see ③ for main having moved again.

① Derived judgments

  • Accept-set of packages/spec: unchanged. Named right. The net diff of hook.zod.ts is TSDoc only (dispatch.mode, the referentialCascadeDelete paragraphs). No z. shape and no .describe() string moves in the PR's hunks; the three performedBy* keys in the file are main's (feat(spec, objectql, runtime): the in-product AI path can name itself on ExecutionContext.performedBy, and hooks see it on HookContext.provenance #34018) and are not in the net diff. Spec property liveness, Type Check · consumer gates, Lint · docs & code guards are green.
  • Published runtime contract of HookContext on a cascaded child delete: narrowed. Named right, now complete in the changeset. dispatch.mode, dispatch.index, input.options with multi, ctx.result absent, dispatch.scope shared by the chunk, a fresh context per row per phase, the before-phase of a chunk running whole, and five by-id fallbacks. The spec TSDoc names four of the five: N1.
  • Public package surface of @objectstack/objectql: unchanged. CascadeBatchNarrowed and cascadeBatchIdsOf still reach sibling section modules only.
  • "A cascade the caller may complete still completes": kept at this head, demonstrated by block 2 case 3, block 3 and block 4 of the parity suite on the full stack.
  • "The recycle bin keeps one entry per root": true, and the one population the last record named keeps its own entry, as before the batch.
  • Skills-docs: none: holds. No page under skills teaches a cascaded child's dispatch shape.

② Semver level

  • @objectstack/objectql patch, @objectstack/spec patch: right, for the reasons of record 6899834361, which this delta does not move. The **BREAKING** paragraph, the FROM to TO list with remedies, and exactly one adr-0087: not-required (no-migration-prescription) marker are present; Clause-②: no (narrowing) is the right arm and reads the same in the changeset and the PR body; the title carries !. Metadata-protocol: none is right.
  • CI on this head: 67 check-runs, 56 success, 11 skipped, 0 failure, none running. Test Core and all eight shards, Check Changeset, PR-body guards, Lint & Repo Gates, TypeScript Type Check are green. In Test Core (8/8): cascade-delete-security-parity.test.ts 8 tests, cascade-batch-read-scope.test.ts 4, last-admin-guard.test.ts 114, recycle-bin/capture.test.ts 28, engine-cascade-delete-batch.test.ts 15, engine-cascade-summary-rollback.test.ts 7, all passing. The run-date.test.ts timeouts of the prior head did not recur.
    CI completed before posting: 67 check-runs on this head, 56 success, 11 skipped, none failed.

③ Boundary flags

  • No report for this round. The two fix commits carry no card comment and no PR-body update, so open_questions and deviations for 74ef4e4bc and 5ed247661 are unstated; I read the commits and their messages instead. The PR body still describes 616735c: S1.
  • The base of the PR is 31eb2aed; main has moved 14 commits since, none touching a file of this diff. The merge queue judges the landing tree; this record judges this head.
  • Ruling 6893661036 precondition (2), the measured statement count (155 to 58): met at the prior head and not re-measured here. Read, the delta adds no statement: the member filter is an in-memory test of a set already collected.
  • Part of #33699 with c1 named as what stays on the card: unchanged, right.
  • Deviation, test files outside the objectql claim surface (last-admin-guard.test.ts, cascade-batch-read-scope.test.ts): accepted last round, unchanged. recycle-bin/capture.test.ts is inside the objectql surface.
  • Security label: the rule this change must keep is in ④. I found no path on which this tree breaks it, and both directions are now demonstrated by passing tests on the full stack at this head.

④ Design judgment

The delta, against ruling 6893661036 (F1) and ruling 6893104201, read in the cited code.

  • Which rows are batched. A chunk is first cleared of ids already entered, then split: the ids the root's collect phase holds are the batch, issued under a token naming exactly those ids, after the read-door question on exactly those ids; the rest are deleted by id in the loop that follows, which also takes the whole chunk when the batch is handed back as narrowed, and nothing when the batch landed and every id was a member. The token, the predicate and the entered set all name the same list, so the exact-set claim still holds and a landed batch is never re-deleted.
  • Which set is asked. deleteCascadedChildren receives the walk's own set: the root's for a root delete, and the inherited one for a member chunk or a member deleted by id, since cascadeDeleteRelations walks a joining member with the inherited set. A non-member deleted by id collects a fresh set and runs its walk inside it, so its own children are members there and are batched. collectCascadeDeleteSet is unconditional and uncapped and reads the relations with the probe the walk uses, so in a cascade no hook writes into, every dependent is a member and the batch is what it was at 616735c (the 501-children pin still shows two set deletes).
  • What a non-member gets. Today's answer in every respect I could read: its own by-id delete under the caller's context, its own refusal if the caller may not read or delete it (the cascade rolls back), 'record' dispatch with the marker, its own recycle-bin entry, its own nested cascade.
  • Order. Within a chunk the members now go before the non-members, where the by-id walk took them in probe order. No ruling or published text orders siblings of one relation, and no pin depends on it.
  • Security rules of the child. The rule is unchanged: a cascade batch deletes no child the by-id delete of that child would refuse (delete permission, row scope, record sharing, tenant wall), and refuses the whole cascade where the by-id delete refuses. The delta narrows what is batched and never widens it; a row it removes from the batch is judged by the by-id door itself. On record sharing the batch is now scoped by the delete-class bulk write scope, and a child that scope leaves out sends the chunk to the by-id door, which gives the caller's answer, the refusal or the delete. "Never fewer" and "never more" are both green on the full stack (blocks 2 and 3), and block 4 shows the per-child audit and share clean-up.
  • Main's merges against the batch. fix(objectql): an async after-hook fired inside a unit of work runs once the unit commits, and not at all when it rolls back #34043 (an async after-hook inside a unit runs at commit) and fix(objectql): a roll-up recompute stamps the master as the system, not the child's writer #34242 (the roll-up recompute's stamp) act below the per-row dispatch and the recompute call the batch already made; neither changes which rows a batch deletes or what a blocking hook sees. The write-scope run around a write's chain covers the walk's read-door question as it covers every read a write makes.

Findings

  • S1 (should-fix) — new. The PR body describes the tree at 616735c, not this one, and it is the text the maintainer reads and the squash commit carries: its head block and the 需要你做的 line say landing waits on plugin-sharing: a write whose id is an operator object (where:{id:{$in:[…]}}) is gated as a by-id write of the row "[object Object]", so a member's multi delete of rows it owns is refused #33928 and that four parity cases are red on this head; the two-minute check expects 14 cases where the file now has 15; and there is no update section for this round (the member filter, the fifth fallback, the two changeset rows, the two pins). Clears with a body edit, which does not move the head: drop or date the wait, correct the count, add the round's update with the dispositions of S1 and S2 of record 6899834361.
  • N1 (nit) — new, in the family of the first record's N1. The dispatch.mode TSDoc in hook.zod.ts lists four by-id cases as the whole list; the changeset and the code have a fifth (a child the cascade's collected set never held keeps 'record'). One clause there would make the spec text and the changeset agree.
  • N2 (nit) — new. The S2 pin runs the batched shape only. A by-id leg (the driver without deleteMany) expecting the same two entries would pin "as before" rather than state it.

No must-fix.

Implemented-by: claude/area-A4-33699
Reviewed-by: session_01L9qibxTeW8xHnxoHxWNHWW

VERDICT: PASS

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

domain:server#5 · zhuangjianguo · session_01QsR2jTyY9BGjj9WBi7QgH6

Review — PASS

Head-sha: 5ed2476610bd5cca57ca8a00412215da52354a77
Area: S2 / A4 · Part of #33699 · delta L1 against my FAIL 6896089195 at 89dff98f, scoped as that verdict set it: M1, S1, items 4 and 5, and the nits.

About the contract record. The face is CONTRACT_REVIEW_TIER, not TIER_DEFAULT: packages/spec/src/data/hook.zod.ts is a published-schema path, and Clause-②: no (narrowing). My record 6896079092 at 89dff98f was taken over by review#2. Its FAIL 6899834361 is at 616735ce and its delta PASS 6908865874 is at this head, and the newest record naming the head governs. So no TIER_DEFAULT record is owed and I am not posting one: it would be the wrong tier for this face.

  1. M1 (the batch dropped the read scope): cleared. deleteCascadedChildren now asks readDoorReturnsChunk before it claims a batch. That is a public find(child, { where: { id: { $in: members } }, fields: ['id'], context }) under the walk's context, so select-class RLS, the sharing read filter and middleware read visibility all compose onto it. Any member missing from the answer, or a declared 4xx refusal, hands the whole chunk to the by-id loop. The by-id loop re-reads each child through plugin-security step 2.7 and gives today's answer: a 403 that rolls the cascade back, or the delete. A 5xx or undeclared fault propagates and is not taken as "hidden". The pin is the scenario M1 named, on a real plugin-security stack, both legs (plugin-security/src/cascade-batch-read-scope.test.ts): "a child hidden by a select policy and admitted by a delete policy refuses the parent's delete 403, and nothing is deleted", plus the can-read-and-delete control. The #33927 parity suite (8/8, landed by fix(plugin-sharing)!: the write gate judges by id exactly the writes the engine runs by id #34033) is green in Test Core (8/8) on this head.
  2. S1 (sys_organization newly refused): cleared. batchable now includes childName !== ORGANIZATION_OBJECT, so an organization child always goes by id, where the per-organization clean-up runs. The docblock lists it among the by-id cases.
  3. Item 4 (precondition security parity: a cascade delete through the predicate-delete arm still refuses (and rolls back) on a child the caller may not delete — pins for #33699 #33782): met. The security-parity pins the ruling asked for arrived as the test(plugin-security): security-parity pins for cascade delete across child-delete shapes #33927 suite through fix(plugin-sharing)!: the write gate judges by id exactly the writes the engine runs by id #34033 on main, which this head merges (31eb2aed, --remerge-diff empty), and they pass on this head.
  4. Item 5 (scope versus Fixes): cleared. The body reads Part of #33699, and c1 stays on the card.
  5. Nits.
    • N2 cleared: "Why a declared key" on referentialCascadeDelete now says ctx.input and ctx.dispatch match a user's own predicate delete (batched) or by-id delete (fallback).
    • N3 cleared: the changeset carries the ctx.result FROM → TO row with the ctx.previous remedy.
    • N4 cleared: the comment names the WRITE scope and says the READ scope is asked separately (engine-delete-and-aggregate.ts:551).
    • N1 partly: the spec's dispatch.mode TSDoc still lists four of the five by-id cases (it omits the non-member). review#2 carries that as its N1 nit, and I agree it does not hold the round.
  6. New since my FAIL, read.
    • The member filter (74ef4e4b): only ids in cascadeSet.members are batched. A row a hook wrote after the collect goes by id as the root of its own cascade, with its own recycle-bin entry, pinned in recycle-bin/capture.test.ts.
    • The token, the read-door question and the entered set all name the same members list, so the exact-set claim holds, and a landed batch is never deleted again in the by-id loop.
    • 5ed24766 adds the two FROM → TO rows and a both-shapes pin.
  7. Battery. This is a ! narrowing on @objectstack/objectql, a shared package. The merge group runs the Dogfood shards on the queued tree (ci.yml core: 'true' on merge_group), so the 16:10Z rule does not call for a local battery. Dogfood Regression Gate is success on this head.
  8. Check-runs on the head. 54 success and 13 skipped, latest run per check, with none failed or pending. Check Changeset re-ran after the 06:14Z body edit and finished success. mergeable_state is clean. git merge-tree against origin/main 3b1307ede4 is clean.

The patch-id is 0d06a22f6ac0b503eda72b9cfde12c40ea17dfb5. A clean main merge that keeps it keeps this PASS. The seat's landing rulings still apply: lands with or after #33782 (its pins are now on main), and the full BREAKING declaration is present.

@objectstack-fleet

Copy link
Copy Markdown
Contributor Author

domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh

席位核对

Head-sha: 0b9b5c002d90ba121ea8215fffd65a091750f706 · 读于 2026-11-16T06:20Z

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation protocol:data size/xl tests tooling Fix lands in tooling, not a product package — enters pm:queue only with Unblocks: or a named surface

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant