Skip to content

Commit a2bb7d5

Browse files
feat(objectql): a bulk update recomputes its parents' roll-up summaries once, at the end of the batch (#34439)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1X4qWPMG9dcYCnVwZPchsM59)_ Fixes #33795 Clause-②: yes (widening) Metadata-protocol: semantic Skills-docs: follow-up owed — `skills/objectstack-data/rules/relationships.md` (Roll-up Summaries: "the engine recomputes it server-side whenever a child is inserted/updated/deleted") does not say that a bulk update recomputes once at the end of the batch, that a summary a rule reads still recomputes after each row, or that a hook reads the pre-batch value meanwhile (ruling 6928862195); it moves as a governed skills-only change. `content/docs/data-modeling/fields.mdx` is updated here. ## 维护者速读 - **改了什么**:引擎接口加一个可选成员 `deferSummaryRecompute`(回调形,同 `transaction`);批量更新的两个入口(`updateManyData` 和通用批量接口的 update)在它里面逐行写,父记录汇总在整批结束时统一重算一次。被规则读到的汇总例外,仍每行算一次(裁决 6928862195 B):另一对象的校验规则隔一跳读、明细的 `parent.` 字段条件读、父对象自己的规则读,也包括经公式或存储计算字段间接读、经汇总链读,以及汇总或父对象存储计算字段上声明的 min/max/unique 等约束,和任何对象上隔一跳读汇总的存储计算字段。批量改 50 行、10 个父记录、2 个汇总字段:400 → 182 条语句(无汇总时 150,不变)。SQLite 和 PostgreSQL 16 实测。 - **为什么改**:裁决 6922040858(A 「A 整批结束后统一重算」),由裁决 6928862195(B 「B 被规则读到的合计不延后」)修正一处。第一半(分组重算)#34421 已合并(6aeb665f),本 PR 已合入 main,diff 只剩「批量更新先推迟、再统一算」这一半。 - **风险与回滚**:接口纯加宽,没有这个成员的引擎照旧逐行重算、值相同;钩子何时跑、读到什么变了,changeset 声明 `Metadata-protocol: semantic`,objectql 升 minor。客户能看到的两处:批量更新进行中,钩子和流程步骤读到的父记录汇总是批前的值(与批量新建一致);被延后的汇总,父记录的钩子/校验/审计/实时事件每批每个父记录只跑一次。校验规则的结果与今天的 main 相同。回滚 = revert 本 PR。 - **先看**:`packages/objectql/src/engine-summaries-and-expansion.ts`(`deferSummaryRecompute`,`recomputeSummaries` 开头的记录分支,`writeTransactionOf`、`rollUpReadByARule`);`packages/objectql/src/summary-rule-reads.ts`(「被规则读到」的判定);`packages/metadata-protocol/src/protocol-batch-data.ts`(`inSummaryBatch`);`packages/spec/src/contracts/objectql-engine.ts`(契约加宽处)。 - **两分钟验证**:`pnpm --filter @objectstack/objectql exec vitest run src/summary-rollup.test.ts`,预期 61 个用例全绿,其中 `deferSummaryRecompute: one roll-up batch` 一组 32 个(含裁决 B 的 20 个:规则读到的汇总每行即算,包括父对象自己的规则、经公式或计算字段、经汇总链、声明的约束、隔一跳读汇总的存储计算字段;`parent.status` 这类读非汇总字段的条件保留延后)。 - **需要你做的**:无待决问题。落地等两位复审对本轮增量的结论和 CI 绿,由席位推进。 ## Ruling 6928862195 (B 「B 被规则读到的合计不延后」), amending ruling 6922040858 The first ruling's premise, that a rule reading the parent's summary sees the pre-batch value during a bulk update "as it already does for `createMany`", does not hold for validation rules: since #25579 (ruling 6377847361, 「批量等于逐条,并发不保证」) a multi-row insert overlays the batch's earlier rows on such a rule, and today's per-row `updateMany` re-reads the recomputed parent before each row. The maintainer ruled B: the deferral stands, and a roll-up summary field that a rule reads is not deferred. Built here as the ruling's parameters set it: - **Where the test sits.** In the engine, at the point where an open scope chooses between recording a recompute and running it (`rollUpReadByARule` in the record branch of `recomputeSummaries`), not in the doors. - **What "read by a rule" is.** `summaryFieldsReadByRules` builds a set of `<object>.<field>` keys from the registry: (i) a validation rule of any object reading a field one hop through a reference (`collectPredicateRelationships`, the hops #25579's accumulation covers), resolved to the reference's target object; (ii) a detail object's field-level `requiredWhen` / `readonlyWhen` reading a field on `parent` (`analyzeRelationshipTraversals(source, 'parent')`, by field name), resolved to the master object. A recompute runs at once when any summary field among the written child object's roll-ups is in the set. The set is kept per summary index (a `WeakMap` keyed by the index), so a metadata change that rebuilds the index rebuilds it too. Class (ii) could name the field, so both classes are built and no limit card is owed. Round 3 adds (iii), a rule of the summary's own object, and closes the set over computed fields and summary chains (below). - **No coarse fallback.** A `parent.` predicate reading a field that is not a summary keeps the deferral. Probed on the real showcase metadata (all 22 objects): the read set is `showcase_account.status`, `showcase_invoice.status`, no summary, so the invoice line's `parent.status == 'paid'` keeps its deferral; with the line's `product.readonlyWhen` changed to `parent.total > 100` the set gains `showcase_invoice.total` (one-off probe, not committed; the engine pin mirrors it). - **Hooks and flow steps** are outside the test and read the pre-batch value, as during a multi-row insert. The round-1 pin "a hook reading the parent summary during the batch reads the pre-batch value" is the hook pin of parameter 6. - **Wording.** "as it already does for `createMany` and a predicate update" is gone from the spec docblock, the facet docblock, the door docblocks and the changeset; they say rule behaviour does not change against today's `main`, and that hooks and flow steps read the pre-batch value during a bulk update as during a bulk create. `content/docs/data-modeling/fields.mdx` gains the bulk-update half (「批量等于逐条」 for a rule reading a parent summary; hooks and flows read the pre-batch value inside one batch, on create and update alike). - **For the contract reviewer (parameter 8).** A recompute that runs at once inside the scope is today's per-row recompute and fails as it does: non-atomic, logged, the row stays written; atomic, the batch rolls back. No new failure path. ## Seat route (not a maintainer ruling) An atomic bulk update whose end-of-batch recompute fails answers today's `200` rolled-back envelope: the last row that landed carries the refusal's own row error (`ERR_SUMMARY_RECOMPUTE`, the withheld sentence), the rows before it `ROLLED_BACK`, the rest `NOT_ATTEMPTED`, and nothing is committed. That is the envelope a per-row recompute failure answered, so the response contract does not move. Pinned in `protocol.many-data-atomic.test.ts`. ## Stacking Built on #34421 (the grouped recompute, `Part of #33795`), which merged as `6aeb665f`. `origin/main` at `6aeb665f` is merged in (`54bc155b`), so this PR's diff against `main` is the deferral half only (17 files at `7c80b9db`, after a second merge of `main` at `1e91fa3e`). The merge took this branch's side for the three files #34421 added that this PR extends (`engine-summaries-and-expansion.ts`, `summary-rollup.test.ts`, the dogfood pin); main's copies of them were byte-identical to #34421's head `1789606e`. The branch name is the one the platform pins this thread to (`claude/project-thread-vah7al`); the hand-over head was `claude/issue-33795-batch-deferral@7480459`. ## What changes - **Contract (spec).** `IObjectQLEngine.deferSummaryRecompute?(callback)`, generic over the callback's result type and answering that result, optional by ruling 6922040858 (the header's list of members optional by ruling now names four). Callback form, entered and left by the engine as `transaction` is; a nested call joins the open scope. - **Contract (metadata-protocol).** The same optional member on `MetadataHostEngine`, typed off the spec member. - **Engine (objectql).** `ObjectQL#deferSummaryRecompute` delegates to `SummariesAndExpansionFacet.deferSummaryRecompute`. The scope is ambient (`AsyncLocalStorage`), because a row's write reaches `recomputeSummaries` through hooks, `ctx.api` writes and nested engine calls. Inside it `recomputeSummaries` records the foreign keys of the rows (copied, per child object, tenant and user) and returns no failure. When the outermost callback settles the scope closes and each recorded entry runs ONE grouped recompute (#34421's path), outside the scope, so a parent write recomputes its own parents at once, in dependency order. Every way out recomputes: resolved, the result, or `SummaryRecomputeError` with `written` = the result; rejected, the recompute runs for the rows that landed and the callback's error is rethrown (a recompute failure there is logged). A write recorded after the scope closed (work the callback started and did not await) recomputes at once. The scope is ambient, not tied to the object the door updates: a write a hook issues on another object during the batch (its own insert, update or delete) is deferred too. When the call that opens the scope runs inside a transaction, the recompute runs before the commit. Only writes under the transaction the scope was opened in (or under none) are recorded: a write under another transaction opened within the scope (a hook's own `ctx.api.transaction`, or an atomic batch reached from inside a non-atomic one) recomputes at once inside that transaction, as before (`writeTransactionOf`, which reads the write's transaction the way `buildDriverOptions` does). A roll-up a rule reads is never recorded (ruling 6928862195, below): `rollUpReadByARule` asks whether any summary field among the written child object's roll-ups is read by a rule (`summary-rule-reads.ts`), and if so the recompute runs at once. The engine.ts facade only delegates; the docblock lives with the body (the facade's line ceiling). - **Doors (metadata-protocol).** `inSummaryBatch` probes `typeof engine.deferSummaryRecompute === 'function'` and runs the loop inside it; without it the loop runs as before. `runUpdateManyLoop` (both arms of `updateManyData`) and the `update` operation of `runBatchDataLoop` use it; `create`, `upsert` and `delete` keep their per-row recompute (the ruling moved the update arm only). The atomic loop is `runAtomicBatch`'s `runLoop`, so the scope is inside the transaction. Non-atomic stale refusal: rows answered as written, the stale column logged once at `error` (`staleSummaryAnswerLines`, as `landedDespiteStaleSummary` logs a row's). Atomic: see the seat route above. - **Dogfood.** `@objectstack/metadata-protocol` added to devDependencies and aliased to source in `vitest.config.ts` (the door wiring is the pin's subject). What a caller can see (also in the changeset): during a bulk update a hook or flow step reading a parent's summary reads its pre-batch value until the batch ends, as during a bulk create; a rule's answer does not change against today's `main` (a summary a rule reads is not deferred); the parent's own write path (hooks, validation, audit, realtime) runs once per recompute, so once per parent per batch for a deferred roll-up, not once per child row. Each child row's own hooks, validation, audit and realtime run where they ran. ## Statements (measured, SQLite and PostgreSQL 16.15, identical) A 50-row `updateManyData` over 10 parents, system context: | summary fields on the parent | 0 | 1 | 2 | |:--|--:|--:|--:| | with the scope (non-atomic) | 150 | 181 | 182 | | with the scope (atomic) | 152 | 183 | 184 | | engine without the member (today's per-row recompute) | 150 | 350 | 400 | With the scope a bulk update pays what a `createMany` pays: one grouped aggregate per summary field plus one write per parent (3 statements: the update and its two reads of the parent). The ruling's "about 608 to about 390" was an estimate on the card's admin bench; these are the measured engine-and-door counts under system context. ## Tests - `packages/objectql/src/summary-rollup.test.ts`, new top-level describe `[#33795] deferSummaryRecompute: one roll-up batch` (32; the round-2 to round-4 pins are listed under those rounds): a loop of single-row updates recomputes once (3 parent writes, 2 aggregates) and CONTROL outside a scope (6 writes); a hook reading the parent summary during the batch reads the pre-batch value (`[5, 5]`; ruling 6928862195 parameter 6 makes this the hook pin); a nested call joins; a summary over a summary recomputes up the chain when the scope ends; a throwing callback still recomputes the rows that landed and rethrows; a failed recompute answers `ERR_SUMMARY_RECOMPUTE` with `written` = the callback's result and the other parent still recomputed; inside a transaction the parent write precedes the commit; an un-awaited write after the scope closed recomputes at once; a scope with no roll-up write runs nothing; a child-row hook that inserts into a second child object of the same parent is deferred too (no parent write during the batch, 6 parent writes at the end for 3 parents x 2 child objects where the per-row loop pays 12, one grouped read of the second child). - `packages/metadata-protocol/src/protocol.many-data-atomic.test.ts`, new describe `[#33795] the bulk update doors run as one roll-up batch` (7), over the file's store engine with a fake scope: every `engine.update` runs between entering the scope and its one recompute; a non-atomic batch stopped by a failed row still ends the scope; a non-atomic failed recompute keeps the rows and logs one `error` line; atomic recompute runs before the commit; atomic failed recompute rolls back with the envelope above; an engine without the member is unchanged; `batchData` update enters the scope and `delete` does not. - `packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts`, new describe `roll-up batch deferral through the bulk update door (#33795)` (2 per cell, the rule describe of round 2, 8 per cell, and the round-3/4 parity describe, 12 per cell), real engine over a real `SqlDriver`, statements counted by knex's `query` event: the table above; value parity for every summary kind (count, sum, min, max, avg, filtered count and sum) after a non-atomic `updateManyData`, an atomic one, `batchData` update, a bulk update stopped by a failed row, and the same door on the engine with the member hidden, each checked against the one-parent aggregate and a hand count, with rows moving between parents and in and out of the filters. <details><summary>Ablations (one-off, not committed)</summary> - **Deferral, engine (unit, source-resolved).** `node scripts/ablation-replace.mjs --file packages/objectql/src/engine-summaries-and-expansion.ts --anchor "if (scope && !scope.closed) {" --replacement "if (scope && !scope.closed && false) {"`: mutation landed (blob 191a8f4 → dfb0159d); `summary-rollup.test.ts` **6 failed | 33 passed** (the six scope pins that read a count or a pre-batch value; CONTROL, throw, late-write and no-op stay green as they should); restored, blob == HEAD, `git diff HEAD` empty. - **Deferral, engine (dogfood, dist-resolved).** Same anchor, replacement carrying the marker `ABLATED33795`; `pnpm --filter @objectstack/objectql build`; `ablation-dist-preflight.mjs @objectstack/objectql ABLATED33795` found it in 4 built files; dogfood file **2 failed | 6 passed**: both door statement pins red on SQLite and PostgreSQL (`updateMany` back to 150/350/400), every value-parity pin green. Restored; rebuilt; `--absent` preflight clean in all 14 built files and the tree. - **Door probe (unit).** `--anchor "if (typeof engine?.deferSummaryRecompute !== 'function') return await runLoop();" --replacement "if (engine || true) return await runLoop(); // ABLATED-33795"`: `protocol.many-data-atomic.test.ts` **6 failed | 15 passed** (every door pin but the no-member CONTROL); restored, blob == HEAD. (A first attempt whose replacement contained the anchor text was refused by the tool before any run, and rerun with a distinct marker.) - **Grouping.** Ablated separately on #34421 (its report, comment 6922044015 on #33795): grouping ablated, createMany 1/41/51 and 2 failed; collapse ablated, update loop 150/350/550 and 2 failed. </details> <details><summary>Package suites and typecheck</summary> - `pnpm --filter @objectstack/objectql test` at a4adf63: **603 files, 13485/13485 passed**. `pnpm --filter @objectstack/metadata-protocol test` at c37b71e: **346 files passed, 9 skipped; 22975 passed, 45 skipped**. The commits after them move the engine docblock from the facade into the facet, drop a test cast and an unused parameter, add a module-top import to one test file and the dogfood alias; the three pin files were re-run at the final head e68802f: objectql `summary-rollup.test.ts` 39/39, metadata-protocol `protocol.many-data-atomic.test.ts` 21/21, dogfood `rollup-grouped-recompute-33795.test.ts` 8/8 (both cells, with `OS_TEST_POSTGRES_URL` on PostgreSQL 16.15). - Typecheck (`tsc --noEmit` plus `check:test-typecheck`): `@objectstack/objectql`, `@objectstack/metadata-protocol`, `@objectstack/spec` exit 0. `@objectstack/dogfood`: NOT MEASURED locally (see Acceptance notes). - `pnpm --filter @objectstack/spec check:generated` after a spec build: all 14 generated artifacts up to date. - Derived gates (`dispatch-gates.mjs --commands`, 109 families) at e68802f: 108 exit 0; `node scripts/check-plugin-teardown-shape.mjs --self-test` exit 3, PREREQUISITE NOT MET (its fixture commit is outside this shallow clone; the diff does not touch it) — NOT MEASURED, CI runs it. `--ran` reconciliation: 109 accounted, 108 run, 1 NOT-MEASURED. - The first gate pass (at c37b71e) found four real reds, fixed in this PR: `check:facade-delegation-only` (engine.ts over its line ceiling by 2; the docblock moved to the facet, the facade keeps a one-line delegation), `check:query-options-erasure` (a new `as any` on test query options; typed instead), and `check:test-source-alias` twice (the dogfood file's new `@objectstack/metadata-protocol` import, now aliased to source; the atomic test file's reach to the dynamic `@objectstack/lint` load, now paid at module top). </details> ## Review round 1 (L1 6924908574, contract review 6925110082) Head `54bc155b`: three commits after `e68802ff`, then the merge of `main`. - **L1 B1 (`check:closing-target-claim` red).** The governing `Claim:` on #33795 named #34421's branch. Comment 6924974543 restates this card thread's claim as a `Claim:` line with `Branch: claude/project-thread-vah7al`. The guard run locally against this PR reads it as UNDETERMINED (its branch reader parses only `claude/issue-N-…`), warned and exit 0, the outcome the guard's own card-thread fixture pins. - **L1 S1 (the scope is ambient).** The spec docblock and the changeset say a write a hook issues on another object during the batch is deferred too. New engine pin: a child-row hook inserts into a second child object of the same parent; no parent write during the batch, 6 at the end (3 parents x 2 child objects), one grouped read of the second child. Green first, so ablated: the deferral off (`if (scope && !scope.closed && false)`) turns it red with 12 parent writes during the batch; restored, blob == HEAD. - **L1 N2.** The `summaryBatchKey` docblock says two writes under one user and tenant but different transaction handles share an entry, and the first row's context wins. - **Contract review S1 (semver).** The changeset now declares `Metadata-protocol: semantic`, `@objectstack/objectql` `minor`, with a `Skills-docs:` line (follow-up owed on the data skill's roll-up section, after the maintainer's answer). Precedent: `33760-async-hook-on-commit`. This PR body carries the same lines. - **Contract review S3 (joined scope inside its own transaction).** The spec docblock, the facet docblock and the changeset state it: a call that joins an open scope from inside a transaction opened within it commits first and recomputes when the outer scope ends, so a failure no longer rolls that batch back. No caller does this today. No code change. - **Contract review N1.** The spec docblock no longer states the statement cost as contract; the facet states it per child object, caller and id chunk, and names the roll-up cycle's per-parent order. - **Contract review S2 (pin the validation-RULE arm through `updateManyData`) and option B are held** for the maintainer's answer on the open question above, as the seat asked; they land in the next delta, in the direction he rules. N2 (an atomic batch stopped by a failed row recomputes before rolling back) is unchanged: fewer statements than before, noted. Verification on the merged head (tree `a59b04d2`, identical to the tree all of the runs below measured): - Closure rebuilt (`pnpm --workspace-concurrency=2 --filter '@objectstack/dogfood^...' run build`, exit 0). Typecheck `@objectstack/spec`, `@objectstack/objectql`, `@objectstack/metadata-protocol` exit 0, and `@objectstack/dogfood` exit 0 (measured now that the closure is built). - `pnpm --filter @objectstack/objectql test`: 603 files, **13487/13487**. `pnpm --filter @objectstack/metadata-protocol test`: 346 files passed, 9 skipped; **22975 passed, 45 skipped**. - Pin files: `summary-rollup.test.ts` 40/40, `protocol.many-data-atomic.test.ts` 21/21, dogfood `rollup-grouped-recompute-33795.test.ts` 8/8 with `OS_TEST_POSTGRES_URL` on PostgreSQL 16.15 (no skip). - `pnpm --filter @objectstack/spec check:generated`: all 14 current. - Derived gates (109 families): 108 exit 0; `check-plugin-teardown-shape.mjs --self-test` exit 3, PREREQUISITE NOT MET (shallow clone) — NOT MEASURED. `dispatch-gates --ran`: 109 accounted, 108 run, 1 NOT-MEASURED. ## Review round 2 (L1 6927725912 M1, ruling 6928862195) Head `0868390f`: three commits after `54bc155b` (M1 fix, ruling B, a census row), no merge. Round 1's contract review delta (6927718273) PASSed with S2 held for the ruling; S2 is now pinned (below). - **L1 M1 (a write under a transaction a hook opened and committed).** A sandboxed hook's `ctx.api.transaction` (the begin/commit trio) commits inside a non-atomic bulk update. Its writes were recorded, and the end-of-batch recompute ran on the committed handle (the trio is not tracked in `openedUnits`, so `buildDriverOptions` kept it) and failed with `ERR_SUMMARY_RECOMPUTE`. Now a scope records a write only when the write's transaction is the one the scope was opened under: `writeTransactionOf(host, execCtx)` reads it as `buildDriverOptions` does (the explicit handle unless closed, else the ambient one), and the scope keeps its opening transaction. Any other write recomputes at once inside its own transaction, as before the scope existed. This also replaces round 1's S3 wording: a call that joins an open scope from inside its own transaction now recomputes inside it, so its failure rolls that transaction back again. - Pin `a write under a transaction a hook opened and committed inside the batch recomputes in that transaction, not on its dead handle at the end`: the fake driver marks a handle done on commit and refuses any op on it. Red before the fix (`1 failed`: `SummaryRecomputeError … for 3 parent record(s)`), green after. - Ablation: anchor `if (scope && !scope.closed && writeTransactionOf(this, execCtx) === scope.transaction) {` back to `if (scope && !scope.closed) {`: mutation landed (blob 56462ff → 6bcc3f60), `summary-rollup.test.ts` `1 failed | 40 passed`; restored, blob == HEAD. - **Ruling B (contract review S2).** Built as described in the ruling section above. - Engine pins, nested describe `[ruling 6928862195 B] a roll-up a rule reads is not deferred` (5), each a batch of six single-row updates under a scope, counting parent writes during the batch and after it: (i) a child validation rule reading the parent summary one hop → 6 during, 0 after; (i) a rule on ANOTHER object (`inv_memo`) reading the same summary → 6, 0; (ii) a `readonlyWhen: 'parent.line_total > 100000'` → 6, 0; a `parent.` predicate reading a field that is no summary (the showcase shape) → 0, 3; a rule reading another field of the related row → 0, 3. - Door pins, dogfood `a roll-up a rule reads is not deferred (#33795 B)` per cell (8 per cell, 16 with PostgreSQL): a supplier with four summaries (filtered count `primary_count`, `score_avg`, `score_min`, `score_max`) over four child objects, each with a rule reading its summary through the reference. For each function, `continueOnError` and atomic `updateManyData` of two rows answer what two single updates answer on a twin data set, field for field (`success`, `code`, message), and leave the same state (two primary contacts: the first admitted, the second refused with the rule's text; atomic: refused, nothing written). Red first on `54bc155b` plus the pins: `16 failed`; green with the test: 24/24 on SQLite and PostgreSQL 16.15. The round-1 statement and value pins stay green, so an object with no such rule keeps its deferred counts. - Ablations: the test removed (anchor ` && !rollUpReadByARule(this, descriptors)) {`): engine `3 failed | 43 passed` (the three rule-class pins; the two keep-the-deferral pins stay green, as they should). Dist leg, replacement carrying a code marker `ABLATED33795B`: objectql rebuilt, `ablation-dist-preflight` found it in 4 built files, dogfood file `16 failed | 8 passed` (every rule pin, both cells; statement and value pins green). Restored, blob == HEAD, whole-tree `git status --porcelain` empty, rebuilt, `--absent` preflight clean. Verification on `0868390f`: - `pnpm --filter @objectstack/spec build && pnpm --filter @objectstack/objectql build` exit 0. Typecheck `@objectstack/spec`, `@objectstack/objectql`, `@objectstack/metadata-protocol`, `@objectstack/dogfood` exit 0. - Pin files: `summary-rollup.test.ts` **46/46**, `protocol.many-data-atomic.test.ts` 21/21, dogfood `rollup-grouped-recompute-33795.test.ts` **24/24** with `OS_TEST_POSTGRES_URL` on PostgreSQL 16.15 (no skip). - `pnpm --filter @objectstack/objectql test` at `a35af28b`: 603 files, 13492 passed, **1 failed**: `federated-injected-column-readers.test.ts` asks every seam use in the engine source for a READERS row, and the new `summaryFieldsReadByRules` calls `referenceTargetOf`. `0868390f` adds its row (`caller-predicate`: it names the object a rule's one hop reaches, from the declaration, and reads no row); that file 5/5. No other file changed after the suite run. `pnpm --filter @objectstack/metadata-protocol test`: 346 files passed, 9 skipped; **22975 passed, 45 skipped**. - `pnpm --filter @objectstack/spec check:generated`: all 14 current. - Derived gates (`dispatch-gates --commands`, 132 families now that a doc page is in the diff) at `0868390f`: 131 exit 0; `check-plugin-teardown-shape.mjs --self-test` exit 3, PREREQUISITE NOT MET (shallow clone) — NOT MEASURED, CI runs it. `--ran`: 132 accounted, 131 run, 1 NOT-MEASURED. - CI on `54bc155b`: the four reds (`Build UI Deps` transient anchor fetch, `Check Changeset` push-run read of the old body, `Test Core (7/8)` history fetch timeout, and its aggregate) were infrastructure, noted in 6927631653; this head supersedes that run. Out of this card, filed by the seat, neither built here: #34465 (a predicate update, `multi: true`) and #34466 (a multi-row insert and a field-level `parent.` predicate). ## Review round 3 (L1 6930506752 M1, contract review 6930582939 M1 and N3) Head `7c80b9db`: four commits after `0868390f` (the fix, two census rows, the merge of `main`). The seat routed both must-fixes as inside ruling 6928862195, with no new question. - **L1 M1: a rule of the parent reading its own summary (class iii).** The recompute's own write is an update of the parent, judged by the parent's rules, so one by one they judge every intermediate value. Now in the read set: a rule of the summary's own object reading it on `record` or `previous` (a validation rule's CEL condition at any depth of a `conditional`, the field a `state_machine` / `format` / `json_schema` rule names, and field-level `requiredWhen` / `readonlyWhen`). - **Contract review M1: a rule reading a summary through a computed field.** The read set is now closed, to a fixed point, over what a read computed field (a `formula`, or a stored field with an `expression`) is calculated from, on its row and one hop through a reference, so it covers classes (i), (ii) and (iii) alike. This is finer than the "every summary of that object" over-read the review allowed: it follows the expression. The same closure follows summary chains: a summary a rule reads that aggregates a child field makes that field read, and a filtered one makes every summary of its child object read. Without that, a rule on the top of a chain would judge only the end of the batch. - **N3.** `fields.mdx`, the spec docblock and the changeset now say that every roll-up of that child object recomputes after each row, and name the computed-field and chain cases. - **Door pins** (dogfood, new describe `a roll-up a rule reads through its own row or a formula is not deferred (#33795 B)`). These are four cases, each run `atomic` and `continueOnError`, on SQLite and PostgreSQL 16.15. The oracle is the same door on the same engine with the member hidden, which is today's per-row recompute. The answer and the stored rows must match, and each atomic case asserts first that it is live (one by one, the batch is refused or a note is locked). - (iii) the parent caps its own count: invoice B holds two lines, the batch moves A's line onto B and one of B's back. - (iii) the same cap read through a stored computed field `room = 2 - line_count`. - (i) a contact rule reading the supplier formula `slots = 1 - primary_count` one hop. - (ii) a line `readonlyWhen` reading the header's stored computed `room = 1 - flagged_count` on `parent`. - Red first on the pre-change dist: **10 failed** (every atomic case, plus the (i) `continueOnError` cases), then **40/40** green. - A `formula` (not stored) read on the parent's own row or on `parent` is not computed where the rule or predicate is judged today. Measured: with `record.room` / `parent.room` as formulas, today's per-row path admits the batch, so no door case can diverge there. Those reads stay in the closure, which costs only statements, and are pinned at the engine level. - **Engine pins** (`summary-rollup.test.ts`, 10 new, 56 in all), in the ruling-B describe, each counting parent writes during and after a six-row batch: - (iii) a validation rule, `previous` inside a `conditional`, and a `requiredWhen` → 6, 0; - (iii) a parent rule on its own non-summary field → 0, 3; - (i), (ii) and (iii) through a formula, and through a stored computed field → 6, 0; - a formula that reads no summary → 0, 3; - a chain (a region rule reading a summary over the invoice summary) → 6, 0. - **Ablations**: each with a code marker, the unit leg, then the dist leg (marker present in 4 built files) and the dogfood file. Each was restored with blob == HEAD and `git diff HEAD` empty, then rebuilt, and `--absent` is clean for all three markers. - Class (iii) off: engine **5 failed** (the four (iii) pins and the chain, whose rule is the region's own); door **4 failed** (both cap cases, atomic, both cells). - Computed closure off: engine **4 failed** (the computed pins); door **10 failed** (every computed case that is live). - Chain closure off: engine **1 failed** (the chain pin); door green, since there is no door chain case. - **CI on `0868390f`**: `Test Core (5/8)` was red. The core census `second-object-read-exposure.pin.test.ts` asks every caller of the reference-target arbiter to be classified; `24ad0728` classifies `summary-rule-reads.ts` as `not-a-served-read` (it reads declarations, no record). The objectql census `federated-injected-column-readers.test.ts` likewise owed a row for the new `keysReadFrom` hop (`7c80b9db`). `Build Docs` was the transient anchor fetch (6930468696). - **Base**: `origin/main` merged cleanly (`1e91fa3e`; K was 15). Verification on `7c80b9db`: - The dogfood closure was rebuilt on the merged tree (`pnpm --workspace-concurrency=2 --filter '@objectstack/dogfood^...' run build`, exit 0). Typecheck `@objectstack/spec`, `@objectstack/objectql`, `@objectstack/metadata-protocol` and `@objectstack/dogfood`: exit 0. `check:generated`: all 14 current. - Pin files: `summary-rollup.test.ts` **56/56**, `protocol.many-data-atomic.test.ts` 21/21, dogfood `rollup-grouped-recompute-33795.test.ts` **40/40** with `OS_TEST_POSTGRES_URL` on PostgreSQL 16.15 (no skip). The core `second-object-read-exposure.pin.test.ts` passed 4/4. - `pnpm --filter @objectstack/objectql test` at `1e91fa3e`: 604 files, 13530 passed, **1 failed**. That was the federated-column census asking a row for `keysReadFrom`; `7c80b9db` adds it, and that file passes 5/5. `summary-rollup.test.ts` was re-run after: 56/56. `pnpm --filter @objectstack/metadata-protocol test`: 346 files passed, 9 skipped; **22975 passed, 45 skipped**. - Derived gates (133 families): 132 exit 0. `check-plugin-teardown-shape.mjs --self-test` exited 3, PREREQUISITE NOT MET (shallow clone), so it is NOT MEASURED. `--ran`: 133 accounted, 132 run, 1 NOT-MEASURED. ## Review round 4 (contract review 6932181981 M2, S4, N4, N5; L1 ACCEPT 6932033886 at `7c80b9db`) Head `8191a5d5`: one commit after `7c80b9db`, no merge (K = 14 against `main` at push). - **M2: a declared bound on a value the recompute's write stores.** The write judges a bound on the summary itself, or on a stored computed field of its object (`min`, `max`, `minLength`, `maxLength`, `pattern`, `unique`, `required`), so that bound now counts as reading the field. The closure then follows the stored computed field to the summary it is calculated from. Door case: the cap spelled as `min: 0` on the parent's stored `room = 2 - line_count`, with no rule. - **S4: a stored computed field reading another row one hop.** A stored computed field (an `expression` on a field that is not a `formula`) stores what it read at its own write, so its one-hop reads seed the set. A `formula` does not, since it is computed when read. Door case: a line's stored `rank = owner.flagged_count`; one by one the two lines store 0 and 1, and deferred both would store 0. - **N4.** The spec docblock now lists the classes and the closure for all three classes, and says a stored value matches one-by-one too. - **N5.** Each parity case now asserts that it is live under `continueOnError` where it is (the formula hop, the header lock and the stored rank). The three cap cases are parity pins only under `continueOnError`: the per-row path logs the refused recompute and ends in the same rows. That is stated in the test. - **Red-first counts, reconciled (review ③).** In round 3 the first red run had the `(ii)` case as a `requiredWhen`, which was not live: its liveness assertion failed, which is the wrong reason. After the switch to `readonlyWhen` only SQLite was re-run red. The round-3 "10 red first" therefore mixed two runs. The counts that do reconcile are from this round's whole-test ablation, with the rule test forced off (`String('ABL33795AL').length > 0 || …`) and measured in the dist leg on both cells: - engine: **14 failed** (every pin that runs at once); - door: **34 failed of 48**. The failures are the 16 round-2 rule pins, the atomic run of all 6 parity cases (12) and the 3 live `continueOnError` cases (6). The 14 still green are the 8 statement and value pins and the 3 cap cases under `continueOnError` (6), which are parity only (N5). - Round 4's own cases: **6 red first** on the round-3 dist (the bound case atomic on both cells, and the rank case atomic and `continueOnError` on both cells), then green. - **Ablations** of the two new seeds, each with a dist leg on both cells: - bound seed off: engine 2 failed, door 2 failed; - stored-hop seed off: engine 1 failed, door 4 failed. Every leg was restored with blob == HEAD, the package rebuilt, and `--absent` is clean for all three markers. Verification on `8191a5d5`: - Typecheck `@objectstack/spec`, `@objectstack/objectql`, `@objectstack/metadata-protocol` and `@objectstack/dogfood`: exit 0. `check:generated`: current. - `pnpm --filter @objectstack/objectql test`: **604 files, 13536/13536**. Pin files: `summary-rollup.test.ts` **61/61**, `protocol.many-data-atomic.test.ts` 21/21, dogfood `rollup-grouped-recompute-33795.test.ts` **48/48** with `OS_TEST_POSTGRES_URL` on PostgreSQL 16.15. The core `second-object-read-exposure.pin.test.ts` passed 4/4. The metadata-protocol suite is unchanged since round 3 (no file of it moved): 22975 passed, 45 skipped. - Derived gates (133 families): 132 exit 0. `check-plugin-teardown-shape.mjs --self-test` exited 3, PREREQUISITE NOT MET (shallow clone), so it is NOT MEASURED. `--ran`: 133 accounted, 132 run, 1 NOT-MEASURED. - CI on `7c80b9db` finished green (every third-party suite completed with no failure). ## Review round 5 (contract review PASS 6933280758 with S5; L1 ACCEPT 6933240039 at `8191a5d5`) Head `584fd7df`: main merged (`fff7423e`, K had reached 15), then two commits. - **S5, the reviewer's second option.** The recompute's own write judges every value it stores against its declaration, so **every stored computed field** of the summary's object now counts as read, bound or not (a bound, `precision`, an option list, a value domain, a number that is not finite). The summary itself counts when it declares a bound (the list now includes `precision`) or when a declared index with `unique` names it. - Cost: an object with a stored computed field over its own summary no longer defers that child's roll-ups. The showcase invoice is one (`amount` is stored from `total`). - Engine pins: summary `precision`; a unique index naming the summary; an unbounded stored computed field → at once; controls: a non-unique index, and a stored computed field reading no summary, keep the deferral. **3 red first**, then 65/65. - Door pin: the cap spelled as a stored select whose option list lacks the value past the cap, no declaration at all. **2 red first** (atomic, both cells), then 52/52 on SQLite and PostgreSQL 16.15. - Ablations (dist leg on both cells): stored-field seed off: engine 2 failed, door 4 failed; summary bound/index seed off: engine 3 failed, door 0 (no door case for it). Restored, rebuilt, `--absent` clean for both markers. - **Not measured on `584fd7df` at hand-off:** the full objectql and metadata-protocol suites, the derived gates. CI runs on the push. ## Acceptance notes - No CI job sets `OS_TEST_POSTGRES_URL` for `@objectstack/dogfood`, so the PostgreSQL cell of both dogfood describes is a named skip in CI (noted on #34421 too). Measured here on a local PostgreSQL 16.15. - `@objectstack/dogfood` typecheck was NOT MEASURED in round 0 (unbuilt closure); in round 1, with the closure built, it exits 0. - A non-atomic bulk update whose end-of-batch recompute fails now logs its stale column once per batch, where the per-row path met (and logged) the refusal at each row; the once-per-field-per-process memory of `staleSummaryAnswerLines` is unchanged. ## Verification - Red first: the six engine scope pins and the six door pins fail with the deferral or the door probe ablated (above); round 2: the M1 pin red before the fix (1 failed) and the 16 rule door pins red before the test (16 failed), then green; round 3 and 4: see the reconciled counts under Review round 4. - Statement, value and rule pins green on SQLite and PostgreSQL 16.15 at the final head. --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr)_ <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5oe2Rer5VB78pdZqkr --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 21d84a8 commit a2bb7d5

17 files changed

Lines changed: 1933 additions & 61 deletions
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
---
2+
'@objectstack/spec': patch
3+
'@objectstack/objectql': minor
4+
'@objectstack/metadata-protocol': patch
5+
---
6+
7+
feat(objectql): a bulk update recomputes its parents' roll-up summaries once, at the end of the batch
8+
9+
Clause-②: yes (widening)
10+
Metadata-protocol: semantic
11+
Skills-docs: follow-up owed — `skills/objectstack-data/rules/relationships.md` (Roll-up Summaries: "the engine recomputes it server-side whenever a child is inserted/updated/deleted") does not say that a bulk update recomputes once at the end of the batch, that a summary a rule reads still recomputes after each row, or that a hook reads the pre-batch value meanwhile (ruling 6928862195); it moves as a governed skills-only change. `content/docs/data-modeling/fields.mdx` is updated here.
12+
13+
**Added:** an optional member on the engine slot contract, `IObjectQLEngine.deferSummaryRecompute(callback)` in `@objectstack/spec` (and the same optional member on `MetadataHostEngine` in `@objectstack/metadata-protocol`). It is a callback, entered and left by the engine as `transaction` is; a nested call joins the open scope. Inside it, the roll-up `summary` recompute every write would run after itself is recorded, and runs once when the callback settles: per child object and caller, one grouped aggregate per summary field and one write per parent for the whole batch. `ObjectQL` implements it. A caller probes for it; an engine without it keeps the per-row recompute, with the same values. Every way out of the callback recomputes: resolved, the callback's result (or `ERR_SUMMARY_RECOMPUTE` with `written` set to that result when a parent cannot be recomputed); rejected, the recompute still runs for the writes that landed and the callback's error is rethrown. Opened inside a transaction, the scope's recompute runs before the commit. Only writes under the transaction the scope was opened in (or under none) are deferred: a write under another transaction opened within the scope, such as a hook's own `ctx.api.transaction` or an atomic batch reached from inside a non-atomic one, recomputes at once inside that transaction, as before, because that transaction may commit before the scope ends.
14+
15+
**Changed:** the bulk update doors run their per-row loop inside that scope: `updateManyData` (`PATCH /api/v1/data/:object/updateMany`, both arms) and the `update` operation of `batchData`. A 50-row bulk update over 10 parents with two summary fields went from 400 to 182 statements (one summary field: 350 to 181; no summary field: 150, unchanged), measured on SQLite and PostgreSQL 16. The stored values are unchanged for every summary kind.
16+
17+
Two things a caller can see, which is why this declares `Metadata-protocol: semantic` (when an authored hook runs and what it reads move, as in `33760-async-hook-on-commit`):
18+
19+
- A hook or a flow step that reads a parent's summary during a bulk update reads the value from before the batch until the batch ends, as it does during a bulk create; before this change each row's hook saw the recompute of the rows before it. Rules do not change against today: a summary field a rule reads is not deferred (ruling 6928862195). A validation rule of any object that reads it one hop through a reference, a detail object's `requiredWhen` / `readonlyWhen` that reads it on `parent`, or a rule of the summary's own object that reads it on its own row, whether the rule names the summary or a formula or stored computed field calculated from it (and any summary a chain of summaries rolls up into one of those), a declared bound (`min`, `max`, `precision`, `unique`, …) or a declared unique index on the summary, and any stored computed field of its object calculated from it (the recompute's write judges that value whatever it declares: a bound, an option list, a number that is not finite), makes every roll-up of that child object recompute after each row inside the batch, so a bulk update answers such a rule as one-by-one updates do, for every summary function (two contacts set primary in one grid edit: the first is admitted, the second refused with the rule's text; an atomic edit that moves a line onto a capped invoice and back rolls back at the first move). A `parent.` predicate that reads a field that is not a summary (`parent.status == 'paid'`) does not turn the deferral off. A stored computed field of any object that reads the summary one hop (`record.invoice.line_count`) does turn it off, since it stores what it read at its own write; a `formula` does not, since it is computed when read.
20+
- The parent's own write path (hooks, validation, audit entry, realtime event) runs once per recompute: once per parent for the whole batch, instead of once per child row, for a roll-up that is deferred. A roll-up a rule of the parent reads is not deferred, so those rules still judge every recompute.
21+
22+
The scope is ambient, not tied to the object being updated: a write a hook issues while the batch runs under the batch's own transaction (or under none, for a non-atomic batch), on any object (a hook's own insert, update or delete, for instance a child-row hook that inserts a row into a second child object of the same parent), has its roll-up recompute deferred to the end of the batch as well, so a summary over that second object also reads its pre-batch value until the batch ends.
23+
24+
Each row's own hooks, validation, audit and realtime run where they ran. An atomic bulk update whose end-of-batch recompute fails rolls back and answers the same rolled-back envelope a failed row answers (the last row that landed carries `ERR_SUMMARY_RECOMPUTE`, the rows before it `ROLLED_BACK`). A non-atomic one keeps its rows written, logs the stale summary once at `error`, and answers the rows as written, as a per-row recompute failure did.

‎content/docs/data-modeling/fields.mdx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,29 @@ writes them in (200 rows each) and refuses the rows the import refuses, with
406406
the same message. It writes nothing, so a row in a later batch reads the
407407
summary as stored before the import: two such rows that fall in different
408408
batches of a dry run both preview valid, while the import refuses the second.
409+
**A bulk update equals one-by-one updates (批量等于逐条):** a bulk update
410+
(`updateManyData`, the `update` operation of `batchData`, a grid bulk edit)
411+
recomputes the parents' summaries once, when the batch ends, unless a rule
412+
reads one of the summaries that child object rolls up: a validation rule of any
413+
object reading it one hop through a reference, a detail object's
414+
`requiredWhen` / `readonlyWhen` reading it on `parent`, or a rule of the parent
415+
object itself reading its own summary (a cap such as `record.line_count <= 5`,
416+
or a declared bound such as `min` / `max` / `precision` / `unique` on the
417+
summary, a declared unique index naming it, or any stored computed field of the
418+
parent calculated from it, whose value the recompute's write judges whatever it
419+
declares). A rule that reads a
420+
formula or a stored computed field calculated from the summary reads the
421+
summary too, and so does a rule on a summary that a chain of summaries rolls
422+
the first one up into. A stored computed field of any object that reads the
423+
summary one hop (`record.invoice.line_count`) counts as well, since it stores
424+
what it reads at its own write. Then every roll-up of that child object
425+
recomputes after each row, so each row's rules, and the parent's own rules
426+
judging each recompute, read it as one-by-one updates would, for every summary
427+
function, `avg` included. A `parent.` predicate that reads a field that is not a
428+
summary, and is not calculated from one, does not count.
429+
**Hooks and flow steps read the value from before the batch:** inside one bulk
430+
create or bulk update, a hook or flow step that reads a parent's summary reads
431+
it as stored before the batch, on create and update alike.
409432
**Concurrent writes are not guaranteed (并发不保证):** two writes in flight at
410433
the same time each read the summary they started from, so a guard like the one
411434
above can still admit one row from each.

‎packages/core/src/security/second-object-read-exposure.pin.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,14 @@ const CALLERS: Record<string, Classification> = {
253253
kind: 'not-a-served-read',
254254
reason: "resolves a seed's references at install, under the system identity; serves nothing to a caller",
255255
},
256+
// [#33795] The batch scope's rule-read test (ruling 6928862195 B).
257+
'packages/objectql/src/summary-rule-reads.ts': {
258+
kind: 'not-a-served-read',
259+
reason:
260+
"names the object a validation rule's or a computed field's one hop reaches, from the declarations in the " +
261+
'registry, only to decide whether a roll-up recompute inside a bulk update runs at once or at the end of the ' +
262+
'batch; it reads no record and serves nothing of the target to any caller',
263+
},
256264
// ADR-0100: the credential-column guard's filter / sort half.
257265
'packages/objectql/src/credential-evaluation-guard.ts': {
258266
kind: 'not-a-served-read',

‎packages/metadata-protocol/src/host-engine.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,15 @@ export interface MetadataHostEngine extends IDataEngine {
6464
* see `protocol-stored-expression-fill.ts`.
6565
*/
6666
captureStoredExpressions?(object: string): StoredExpressionFillCapture;
67+
/**
68+
* [#33795] The engine's roll-up batch scope, typed off the `objectql` slot
69+
* contract for the reason `transaction` is, and optional there as here by
70+
* ruling 6922040858. The bulk update doors (`runUpdateManyLoop`, and the
71+
* update arm of `runBatchDataLoop`) run their per-row loop inside it, so a
72+
* batch recomputes its parents' summaries once. Degrading means today's
73+
* per-row recompute: the same values, more statements.
74+
*/
75+
deferSummaryRecompute?: IObjectQLEngine['deferSummaryRecompute'];
6776
// Protocol accesses additional engine members structurally; keep it permissive
6877
// for this relocation (behavior unchanged — the concrete engine is injected).
6978
[key: string]: any;

0 commit comments

Comments
 (0)