Repository navigation
perf(objectql)!: a cascade delete removes a relation's children as one predicate delete per chunk - #33887
Conversation
…per chunk Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ
…allback and guard verdict Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ
… the batched cascade Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ
…hangeset carries the claim's declaration line verbatim Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jRmmALkM1ftZxdVatQ
📓 Docs Drift CheckThis PR changes 2 package(s): 38 hand-written doc(s) name something this change touched — list omitted above 15 rows. Re-derive on the tree named below: ⛔ 7 release-owned page(s) also affected — read-only, see AGENTS.md Documentation Guardrails. What this run could not see
Coarse fallback — 175 page(s) merely mention a changed package (the pre-#9192 predicate, kept for the deliberately-wide backstop): Which tree this was computed onThis run read A worktree cut from an older # 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
|
|
domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh Request: review · PR #33887 · area S2 (A4) · Fixes #33699 · head
Test Core (3/8) red at this head, judged not this PR's: the only failure is |
|
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. |
|
domain:server#5 · zhuangjianguo · session_01QsR2jTyY9BGjj9WBi7QgH6 Contract reviewServed-tier: Inputs read: card #33699 body and all 10 comments (rulings 6893104201 and 6893661036, reports 6892420600, 6893257535, 6895711951), the PR body, the net diff ① Derived judgments
② Semver level
③ Boundary flags
④ Design judgmentThe narrowing itself holds against ruling 6893661036 (F1). Consumers that relied on per-row cascade hooks, read against the new shape:
Findings
N1 to N4 ride the re-push M1 forces; none of them alone would hold the round. Implemented-by: VERDICT: FAIL |
|
domain:server#5 · zhuangjianguo · session_01QsR2jTyY9BGjj9WBi7QgH6 Review — FAILHead-sha:
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
…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
|
domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh Blocked-by: #33928 (PR #34033, area S1). Test Core (8/8) is red at
|
|
review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW Contract-review-claim: session_01L9qibxTeW8xHnxoHxWNHWW · head — · 2026-11-15T19:01Z |
|
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. |
|
review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW Contract reviewServed-tier: 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 Prior findings (record 6896079092), judged on this tree:
① Derived judgments
② Semver level
③ Boundary flags
④ Design judgmentThe batch itself, against ruling 6893661036 (F1), read in the cited code.
Findings
Tests otherwise pin each behaviour with a control: order and shape (control: the by-id shape on the no- Implemented-by: VERDICT: FAIL |
…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>
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh
…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
|
review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW Contract-review-claim: session_01L9qibxTeW8xHnxoHxWNHWW · head 5ed2476 · 2026-11-16T06:00Z |
|
review#2 · os-tesla · session_01L9qibxTeW8xHnxoHxWNHWW Contract reviewServed-tier: 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 What moved between the two heads, the PR's own work kept apart from main's.
Prior findings (record 6899834361), judged on this tree.
① Derived judgments
② Semver level
③ Boundary flags
④ Design judgmentThe delta, against ruling 6893661036 (F1) and ruling 6893104201, read in the cited code.
Findings
No must-fix. Implemented-by: VERDICT: PASS |
|
domain:server#5 · zhuangjianguo · session_01QsR2jTyY9BGjj9WBi7QgH6 Review — PASSHead-sha: About the contract record. The face is
The patch-id is |
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh
|
domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh 席位核对Head-sha:
|
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 queueMetadata-protocol: none
Skills-docs: none — no
skills/**file teaches a cascaded child'sdispatch.mode,referentialCascadeDeleteor a sibling-count hook (git grepofdispatch.mode,referentialCascadeDeleteandper-rowoverskills/: the only hits teach predicate writes in general and stay true); the spec's own hook docs are updated hereNo longer waiting on #33928 (as of
5ed247661): it landed on main as #34033 and is in this tree by the merge at321a8668f. Ruling 6893661036 precondition (1), the #33782 parity pins merged as #33927, is met: all 8 cases green at5ed247661, inTest Core (8/8)and locally. CONTRACT_REVIEW_TIER record 6908865874 on5ed247661: 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.
维护者速读
DELETE … WHERE id IN (…)删掉;每个子记录的删除前后钩子、实时事件、回收站、权限拒绝回滚都保留。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.
engine-cascade-planning.ts): for acascaderelation the walk now collects the relation's dependents across the whole root set and hands them todeleteCascadedChildren, which issues ONE predicate delete per chunk of 500 (REFERENCE_PROBE_BATCH, underMAX_BULK_PER_ROW_HOOK_ROWS= 10,000) through the publicdelete():where: { id: { $in: chunk } },multi: true. The chunk therefore runs every child'sbeforeDelete(per-row, ADR-0058 Addendum II), onedeleteMany, then every child'safterDelete. A child's own children are walked by the predicate arm's existingcascadeDeleteRelations(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.engine-top-level.ts,engine-middleware-and-context.ts, surface amendment 6893212568): the cascade-issued token gains an optional id set, andclaimReferentialCascadeDeletematches a predicate delete whosewhereis exactly{ id: { $in } }naming that set. Every per-row context, both phases, carriesreferentialCascadeDelete: true.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-internalCascadeBatchNarrowedbefore 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 nodeleteMany(or a floored external driver) keeps the by-id path. One cascade can show both shapes.data.record.deletedper child from its pre-image, never the bulkdata.records.deleted.HookContext.dispatch.modeandreferentialCascadeDeleteTSDoc now say a cascaded child is'per-row'withmulti, and that the token can name an id set. No.describe()and no schema shape changed (check:docsgreen, nothing regenerated).DEBUG=knex:query, warm delete): inside the transaction, one doomed readselect * from bench_line_item where id in (?, x10), then onedelete 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 forsys_share_link); the audit pair stays per child.engine-cascade-planning.ts, record 6899834361 S2): onlycascadeSet.membersare 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)
ctx.dispatch.mode: 'record'andctx.input.options{ where: { id } }TOctx.dispatch.mode: 'per-row', withctx.dispatch.indexits position in the chunk andctx.input.optionscarryingwhere: { id: { $in: [...] } }andmulti: true.ctx.input.idandctx.previousstill name the child's own row, andctx.referentialCascadeDeleteis stilltrueon every per-row context, in both phases, grandchildren included.ctx.resultin a cascaded child'safterDeletebeing the driver's by-id answer TOctx.resultabsent, as on every per-row delete context. Readctx.previousfor the deleted row.ctx.dispatch.scopeone 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).beforeDeleteandafterDeleteTO a fresh context per row per phase, so a value abeforeDeletehandler leaves onctxno longer reaches that child'safterDelete. Keep cross-phase state inctx.dispatch.scope, keyed byctx.input.id.beforeDelete, then the one set delete, then every child'safterDelete. Before, each child ran before → delete → after in turn. So abeforeDeletehook 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: onctx.input.options.multi === trueread the target set fromctx.input.options.where(the shipped last-administrator guard does exactly this, and reaches the same verdict as before), or usectx.referentialCascadeDelete === trueto tell the cascade from a hand delete.'record'with nomulti, so one cascade can show both shapes. A driver with nodeleteMany, 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, onedeleteMany, after x N with the write count observed from inside each hook;dispatch.mode: 'per-row',index0..N-1,options.multi,previous= own row, the marker on every per-row context;dispatch.scopeis one object across the chunk's six dispatches, a value left onctxinbeforeDeletedoes not reachafterDelete, and the same value kept indispatch.scopekeyed byinput.iddoes, 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; nodeleteManykeeps 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-leveldescribe: acascadedependent 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-leveldescribe[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
dispatch.modeTSDoc 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 nopackages/spectext; the changeset names it.packages/plugins/plugin-auth/src/last-admin-guard.test.tsandpackages/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.tsis inside it.Verification
Head
5ed247661:origin/mainat31eb2aedamerged (321a8668f, 128 commits, no textual conflict;hook.zod.tsauto-merged), then74ef4e4bc(S2) and5ed247661(S1). The net diff againstorigin/mainis 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 amulti: truewrite 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 byCascadeBatchNarrowedand 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
beforeDeleterecorder was added to the parity file throughscripts/ablation-replace.mjsand removed (restored blob equals HEAD,git diff HEADempty); 8 of 8 green with it. The four cases that land run batched:f_all(12 lines, 2 notes),m1,m2,h1, every childper-row multi=true marker=true. The four refused cases fall back:r1,f_u(unreadable child, the read door misses it) andr2,f_e(edit-shared child, readable, so the batch's write-scope read misses it andCascadeBatchNarrowedcrosses the real security and sharing chain back to the walk); each shows_aasrecord, 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
VERDICT command-exit 0): objectql build exit 0;pnpm --filter @objectstack/objectql testTest Files 600 passed (600), Tests 13369 passed (13369); objectqltypecheckexit 0 (test layer 39 files / 233 errors / 64 signatures held, unchanged);pnpm --filter @objectstack/plugin-security testTest Files 272 passed (272), Tests 6724 passed, 45 skipped (6769);pnpm --filter @objectstack/plugin-sharing testTest Files 75 passed (75), Tests 1581 passed (1581);last-admin-guard.test.ts114 passed.node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstackat5ed247661derived 99 commands (11 paths vs merge base31eb2aeda; it flaggedorigin/mainone commit ahead,8898b4e39, which changedscripts/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/specfamilies exit 0.spec check:generated: 13 of 14 current;check:test-typecheck(spec) died intscwith 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 nopackages/specfile.check:type-check-debtandcheck: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.--no-inline-configover the three files this round touched: exit 0. Control-byte self-scan of the four files: no hit.pnpm --filter @objectstack/dogfood testunder the verify lock, no shard, no path, afterpnpm --filter '@objectstack/dogfood^...' buildexit 0 at5ed247661):VERDICT command-exit 0, Test Files 471 passed, 3 skipped (474); Tests 3988 passed, 42 skipped (4030); no failure. CI on5ed247661: 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 Guardsuccess (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/objectqlto source.expected [ 'account/acc1' ] to deeply equal [ 'account/acc1', 'note/n9' ](the late row deleted with no entry). Green after74ef4e4bc.const members = chunk;, blobdaa43fc8ato28aa50b34): 1 failed / 42 passed over the two objectql files, the same message. Restored.if (false && batchable …): thedispatch.scopecase 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 sessionsession_01QsR2jUg7BKfRBcTPyMxbLh; S1 and S2 folded into this main-merge round after #34033, as the seat ruled.Commits this round:
321a8668f: merge oforigin/mainat31eb2aeda(128 commits, no textual conflict;git show --remerge-diffof the merge is empty). The PR's own changed lines against main are identical before and after the merge.74ef4e4bc: the member filter.deleteCascadedChildrenbatches onlycascadeSet.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 inrecycle-bin/capture.test.ts.5ed247661: the two FROM to TO changeset rows (dispatch.scopeshared 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-shapesdispatch.scopepin inengine-cascade-delete-batch.test.ts.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.dispatch.scopeand the fresh ctx per phase.changeset/33699-cascade-delete-batch.mdlines 21 and 22) with the remedy: keep cross-phase state inctx.dispatch.scope, keyed byctx.input.id. Pin (a):engine-cascade-delete-batch.test.tsline 199, both shapes.deleteCascadedChildrenbatches onlycascadeSet.members(engine-cascade-planning.tsline 1461); a non-member goes by id as the root of its own cascade. Pin:recycle-bin/capture.test.tsline 544, red before the fix, red under the ablation.CascadeBatchNarrowedacross the real chain pinned only by the #33927 casesr2/f_eare 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:dispatch.modeTSDoc inhook.zod.tslists 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.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 ofpackages/qa/dogfood/bench/sql-perf/bench.mjs --scale 100000 --only cascade_delete_opportunityon this box (shared, 5 deletes each, one opportunity with 10 line items, admin): statement counts exact, milliseconds indicative. "Before" = objectql source at base1e65a389ebuilt into the same tree; "after" = this branch.7d2730a95)7d2730a95)Local suites and gates
pnpm --filter @objectstack/objectql exec vitest runat89dff98f6: Test Files 598 passed (598), Tests 13168 passed (13168); VERDICT command-exit 0. objectqltypecheckat89dff98f6exit 0.pnpm --filter @objectstack/plugin-auth exec vitest runata1e04815b: Test Files 277 passed (277), Tests 5472 passed, 10 skipped; VERDICT command-exit 0. At89dff98f6: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; speccheck:test-typecheckexit 0.node scripts/pm/dispatch-gates.mjs --commands: 96 families, all run atcb2cafef6; 94 exit 0.check:query-options-erasureexit 1 (test surface 236 to 237, anas anyon an option bag in the new test) fixed ind31c13d0a, re-run exit 0.check:dual-build-cjs-loadsexit 3 (prerequisite: not every package built here), NOT MEASURED, CI's.--ranreconciliation: 96 derived, 96 run, 0 unrun.d31c13d0awith this body as the event:check-adr-0087-registration0,check-changeset-no-major0,check-closing-keyword-parity0,check-empty-changeset0,check-partof-closing-keyword0; pluscheck:nul-bytes,check:cross-package-test-inputs,check:test-source-alias,check:doc-authoring,check:issue-citationsall 0; eslint over the eight touched files exit 0.pnpm --filter @objectstack/spec check:generatedafter a spec build: every artifact current (check:docsgreen; 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).CascadeBatchNarrowedthrow: 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).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.['data.records.deleted']instead of threedata.record.deleted).multi(the "record shape, batched befores" the ruling rejects), objectql rebuilt so plugin-auth's dist import carries it:[batch] … BOTH administrative memberships is refusedred ("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 --absentok, 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 of4029ca241),eab93bab0and7d2730a95(merges of main; the second brought in the #33927 parity pins),616735ceb(changeset count).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.sys_organizationnewly refused 409childName !== ORGANIZATION_OBJECTinbatchable; pinned in objectql. No other refusal of the same one-term shape found (list in Acceptance notes of this update).dispatch.modefallbacksdeleteMany, floored external driver, the organization object) and says the before-hooks run before the set delete per chunk of 500 within one relation.referentialCascadeDelete"Why a declared key" now saysctx.user/ctx.sessionare identical andctx.input/ctx.dispatchtell nothing apart either.ctx.resultctx.resultin a cascaded child'safterDelete, the driver's by-id answer, is now absent; readctx.previous. Thedispatch.modevalue is stated as the code sets it,'per-row'.engine-delete-and-aggregate.tssays the doomed read is the caller's WRITE scope and that the read scope is proven by the walk.Part of #33699; c1 stays open on the card.inferTargetId(sharing-plugin.tsline 1776) returnsoptions.where.ideven when it is the operator object{ $in: [...] }, so the batch'sdelete(child, { where: { id: { $in } }, multi: true })on aprivate+owner_idchild is judged as a by-id write of the id[object Object]and refused 403FORBIDDEN. The same 4 cases are red with the read-door proof ablated, so they are not the M1 fix. 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 (area S1); this PR is not reshaped to dodge it. After 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 merges, this branch merges main.Tests and ablations at this head
packages/plugins/plugin-security/src/cascade-batch-read-scope.test.ts(new, realObjectQL+SqlDriver+SecurityPlugin, both legs: the batch, and the by-id path withdeleteManyhidden): a child hidden by a select-class policy and admitted by a delete-classusingpolicy (public_read_write, noowner_id) makes the parent's delete answer 403PERMISSION_DENIEDwith nothing deleted, on both legs; control: readable deletable children are deleted (per-rowon the batch,recordby 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.if (batchable) {), viascripts/ablation-replace.mjs(anchor 1 to 0, blobe80908231to0c3d9ff28): plugin-security pin 1 failed / 3 passed ([batch]case:{ kind: 'landed' }), objectql 2 failed / 12 passed. Restored, blob equals HEAD,git diff HEADempty.true;): objectql 1 failed / 13 passed, the refusalOrganizations are deleted one at a time, by idfromorganizationPredicateDeleteRefusal. Restored, blob equals HEAD,git diff HEADempty.@objectstack/objectqlto its source.7d2730a95under 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.pnpm --filter @objectstack/dogfood testunder the verify lock, no shard, no path; the tree of616735ceb, 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 20Schema sync FAILEDlines forshowcase_invoice(sqlite-wasm refusesadd columnwith a non-constant default); that is log output, not a failed test, and this diff does not touch schema sync.dispatch-gates --commandsderived 98 commands at7d2730a95; all 98 ran with exit 0 (96 in the sweep,check:type-check-debtandcheck:dual-build-cjs-loadsunder the lock);dispatch-gates --ranreconciles 98 derived, 98 run, 0 NOT MEASURED, 0 UNRUN.dispatch-gates --tierexit 0.check-durability-degradation-log-levelexit 0 and objectql typecheck exit 0, the two CI reds of4029ca241.pnpm lintexit 0 ateab93bab0. 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 namesidonly); the credential-column guard (idis not one). None is of the one-term shape. One refusal found outside objectql, of a different shape: plugin-sharing'sinferTargetId, above, carried by #33928.🤖 Generated with Claude Code
https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh