Skip to content

Commit 94a2d8b

Browse files
fix(objectql)!: a predicate update judges each matched row against the parent roll-ups the rows before it move (#34709)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBFyg5B2muWbKZjA9phXVWse)_ Fixes #34465 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — skills/** teaches the per-row hook semantics of a predicate (`multi: true`) write (skills/objectstack-data/references/data-hooks.md, lines 181 and 195) but says nothing on how a rule reads a parent summary during one ## 维护者速读 - 改了什么:按条件批量更新(`update(..., { where, multi: true })`,flow 的 update_record 节点 `multi: true`)时,读父记录汇总的校验规则和明细字段的 `parent.` 条件,现在每一行读到的是「前面已判过的匹配行改完之后」的汇总,和逐条 by-id 更新的结果一致。count/sum/min/max/avg 都精确,换父也算;规则读的是父记录上建在汇总上的公式或存储计算字段(如 `remaining = budget - spent`)时,也按叠加后的汇总重算;被重算的公式若还读一个与汇总无关的公式(如 `room = ceiling - total`,`ceiling = budget + extra`),后者取父记录读出的存值,和逐条一致;存储计算字段像逐条写入那样算两遍,所以先声明的字段读到后声明字段的新值;每个父记录带一份「上一行重算写下的行」往下传,所以读自身存值的字段(如历史最高值)和逆声明顺序的三级链从第三行起也和逐条一致;汇总的 `filter` 以嵌套写法 `{ account: { status: 'x' } }` 读关联记录时,与点路径写法一样不叠加、读存值。 - 为什么改:裁决 6377847361(C,插入)和 6928862195(B,updateMany)已定「批量等于逐条」,谓词更新是剩下唯一不守它的批量门;席位在卡上按路线 A 裁定(6938087434)。 - 风险与回滚:收窄(BREAKING):今天能整批写进去的某些谓词更新会被整批拒收(只影响有规则读父汇总的子对象,hotcrm 与示例应用里没找到)。也有反方向:前面的行把汇总往放行方向推时,main 会拒的更新现在会放行,和逐条一致。没有这类规则、或只匹配一行时,零额外开销。三种情形读存值(下面单列一节)。回滚即撤回本 PR,无数据迁移。 - 先看:`packages/objectql/src/summary-batch-accumulation.ts`(末尾新增 `loadPredicateUpdateSummaryBases` 与 `createPredicateUpdateSummaryFold`)、`packages/objectql/src/engine-update.ts`(谓词分支校验循环)、`packages/objectql/src/summary-rollup.test.ts`(末尾 #34465 一组)。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/summary-rollup.test.ts src/summary-batch-accumulation.test.ts`,预期全过;`summary-rollup.test.ts` 末尾两组 #34465 共 30 条、`summary-batch-accumulation.test.ts` 三组 #34465 共 9 条,两文件合计 125 条全过;各轮修复各做一次消融:去掉「未重算公式取存值」1 条变红,嵌套写法退回只认点路径 2 条变红,存储计算只算一遍 1 条变红,不再逐行传父记录映像 3 条变红。 - 需要你做的:无,席位落地(`check-governed-merges` 判定非受管;区在 L1 ACCEPT 与席位契约复审 PASS 之后落地)。 ## What changes A predicate update judges every matched row before its one `updateMany`, against related rows (`resolvePredicateRelated`) and master-detail headers (`resolveMasterDetailParents`) read once for the batch, and recomputes the roll-ups once after it. So every row read a parent summary as it stood before the update. Measured on `main` before this change: with "one primary line per invoice" (`record.is_primary == true && record.inv.primaries > 0`), two by-id updates admit the first line and refuse the second, but one predicate update admits both and leaves `primaries` at 2. - `packages/objectql/src/summary-batch-accumulation.ts` - `loadPredicateUpdateSummaryBases(engine, descriptors, matched, ctx)` reads, per summary a rule reads and per chunk of parents, one grouped aggregate (`groupBy` the FK, `ROLLUP_AGGREGATE_OPTION` on the FK, a system context like the recompute). The parents are those the matched rows name, as stored or as the update leaves them. - `count` / `sum` / `avg`: every child as stored, the matched rows included. `avg` reads its sum and non-null count. - `min` / `max`: the children outside the matched set (`id $nin`), since an extreme cannot be taken back out. - `createPredicateUpdateSummaryFold(bases, matched, childFields)` folds the matched rows in memory. Before row k, rows 0..k-1 have left their stored contribution and taken the one the update gives them. It exposes `overlay(binding)` and `overlayRow(object, header)`, the same two shapes as the insert arm, plus `advance(i)`. The summary `filter` is evaluated on each row state by the in-memory aggregation's own walker. - The fold also patches the parent's fields that are calculated from a folded roll-up: a `formula`, or a stored computed field (an `expression` on a field that is not a formula), directly or through another such field. A rule can read one of these instead of the roll-up (`record.project.remaining`, where `remaining = budget - spent`). `setDependents` hands the fold what computes them, and `foldedSummaries()` says which roll-ups and parents it moves. - `packages/objectql/src/engine-update.ts` — in the predicate branch's per-row validation loop, when a rule reads a summary of this object and more than one row matched, it builds the fold. It then judges row i against the overlaid related binding and header (and the previous header), and advances. `loadSummaryFoldDependents` handles the calculated fields the way a by-id update's rule reads the parent, that is, as SYSTEM (`resolvePredicateRelated` reads related values under system authority). It reads the folded parents' stored rows once, at most 500 ids per read. It resolves the plan's permission map once over those rows, with the SYSTEM context's own permission resolution, and likewise its one-hop related rows and its option labels; none of these moves while the update is judged. The plan is the parent's stored computed fields and formulas that read a folded roll-up, closed transitively (`storedExpressionsReading`). Each overlay then computes them in two passes, as one by one computes them: 1. The stored computed fields, as the recompute's write computes them: over the write's image, the stored row with the folded roll-ups and no formula fields. A stored field that reads a formula therefore computes `null` here, as it does on every write. This pass uses the DECLARED option labels, and it is evaluated TWICE, because a by-id write computes the stored fields before its `beforeUpdate` hooks, moves the changed values onto the patch, and computes them again before the statement. So a stored field declared BEFORE the stored field it reads (`head_gap = record.headroom`, `headroom` over the roll-up) is written over the moved value, and the fold reads it the same way. The pass also carries ONE IMAGE PER PARENT through the update: after each matched row is judged, the fold's `advance` tells the dependents every parent that row names (as stored and as left), which writes that parent's image again from the previous image, as the recompute writes each such parent after every child update. The next row reads that image. So a stored field that reads its own stored value (a high-water mark) or a chain of stored fields declared against their reading order holds at every row what one by one holds, not only at the second row. Row 0 still reads the write's image over the stored row (N3, follow-up #34821). 2. The formulas, as the next read computes them: over that row, with the stored row's values of the formulas the plan does not hold put back on it, and with the option labels the SYSTEM read uses. A formula outside the plan reads no folded roll-up, so it does not move while the update is judged, and the SYSTEM read of the stored parent already computed it. A planned formula reading one (`room = ceiling - total`, `ceiling = budget + extra`) therefore reads it as the by-id rule's read does. Both passes use the read path's own `applyFormulaPlan`. An object whose calculated fields read no folded roll-up reads nothing more. Validation still runs on every row before the one write: all-or-nothing is unchanged. - `packages/objectql/src/engine-summaries-and-expansion.ts` and `engine.ts` — `summaryDescriptorsReadByRules(childObject)`: the child's roll-up descriptors that some rule reads, from the cached #34439 analysis (`summaryFieldsReadByRules`, classes (i) and (ii)). It is wired through the facet host like `summaryForeignKeyColumns`. Added to the claim's file surface by the area (comment 6938143680 on #34465). - `content/docs/data-modeling/fields.mdx` — one paragraph after the bulk-update one: a predicate update equals one-by-one updates, with its limits. - `.changeset/34465-predicate-update-parent-summary-rule.md` — `patch` on `@objectstack/objectql`, BREAKING, FROM → TO and the one-line fix, ADR-0087 `not-required (no-migration-prescription)`. ## Why Ruling 6377847361 (C, 「批量等于逐条,并发不保证」, inserts) and ruling record 6928862195 (B, 「被规则读到的合计不延后」, updateMany). The record's out-of-card finding named this door: "No ruling covers it". The seat ruled it the third door of the same family, route A, on the card (6938087434). The SQL stays in the database (one grouped aggregate per summary read), the hook and event shapes do not move (route B would have split the write into N by-id updates), and no function is left with a partial answer (route C). What narrows, named in the changeset: a predicate update that one-by-one updates would refuse a row of is now refused, with `VALIDATION_FAILED` / 400, and writes nothing. Not moved: a rule that reads no summary, a predicate update matching one row, a by-id update, hooks and flow steps (they read the value from before the update, as ruling record 6928862195 states), and a rule of the parent itself (class (iii): it judges the summary once, after the write; outside this card, as the card's options analysis says). ## Tests - `packages/objectql/src/summary-rollup.test.ts` — a new top-level `describe` (#34465) on the file's memory driver, where the roll-up recompute runs for real. A child carries five roll-ups that rules read (a filtered `count`, a `count`, `sum`, `min`, `avg`). Its class (i) rules read them one hop, and its class (ii) `requiredWhen: 'parent.line_count >= 3'` reads one on the header. - The one-by-one reference answer. - A predicate update refused as one by one refuses its second row (`VALIDATION_FAILED` / 400, nothing written) for the filtered `count`, `sum`, `avg` (a row outside the match included) and `min` (a matched row holding the extreme takes it with it). - A reparent: three lines moving under a header of one land under 1, 2, then 3, and the third needs `note`. A reparent under the line: all admitted. - A predicate update matching one row reads the stored value. - A rule reading a FORMULA (`remaining`) and one reading a STORED computed field (`headroom`) calculated from the `total` roll-up: the one-by-one reference, the predicate update refusing the second row, and under the line admitted. - The other direction: a row main refused (it read the stored total, 120) is admitted, because the row before it lowers the total to 70, as one by one admits it. - S2, each with its one-by-one reference: a formula reading a lookup hop and the roll-up (`cap_left = record.cap_ref.amount - record.total`), updated by a caller who cannot read the lookup's object (a read-scoping middleware): one by one refuses the second update, and a predicate update by the same caller is refused the same way, because the calculated field is computed under SYSTEM. A stored computed field reading a formula (`slack = record.remaining`): measured one by one it stays `null` on every write, because a write's image carries no formula, so the rule admits both rows, and the predicate update admits both. - L1 M1, with its one-by-one reference: a formula over the roll-up that also reads a formula reading no roll-up (`room = record.ceiling - record.total`, `ceiling = record.budget + record.extra`). One by one refuses the second update. The predicate update is refused the same way, and under the line it admits both. - L2 delta S3, with its one-by-one reference: a stored computed field declared before the stored computed field it reads (`head_gap = record.headroom`). One by one it tracks `headroom` on every write (20, then -10) and the second update is refused; the predicate update is refused the same way. - L2 delta S4, over three rows, each with its one-by-one reference: a high-water mark (`peak` is the larger of `record.peak` and `record.total`; totals 100 → 160 → 120, so the third line reads 160 and is refused, where a restart from the stored row reads 120 and admits) and three stored fields chained against declaration order (`chain_x` reads `chain_y`, `chain_y` reads `chain_z`, `chain_z` reads `record.total`; the third line reads 150 and is refused, where a restart reads 120). The predicate update is refused the same way in both. - L2 delta M2, in its own top-level `describe` (the fake driver declares `readableIdsLeaf` and resolves the composed semi-join leaf): a `min` roll-up filtered in the nested form (`{ acct: { status: 'active' } }`) and a patch that moves no roll-up (`tag`). One by one reads the stored minimum (5) and refuses the first line; the predicate update reads it too and is refused, where the fold over the children outside the match (80) would have admitted both. - CONTROL: an object whose rule reads no roll-up makes no aggregate read before its write, and admits as before. - The subject reads one grouped aggregate per roll-up a rule reads, before the write. - The file's fake driver learned `$null`: the engine widens a `$nin` to `$or [x $null, x $nin]`, and the fake answered `true` for any unknown operator. - `packages/objectql/src/summary-batch-accumulation.test.ts` covers the fold and the loader on their own (including the nested form left out before any statement in three shapes, with an operator-only field condition as the control, and the fold telling the dependents, after each judged row, every parent that row names with the roll-ups it leaves): count/sum/avg over a base holding the matched rows, min/max over a base leaving them out, reparent and header, the three left-out cases, and the statements the loader sends. It also checks that the fold hands the folded values to the dependents hook and patches only the calculated fields the row carries. Ablation (`node scripts/ablation-replace.mjs`, one mutation, taken on the fix commit before the branch was restarted on `main`, so the blobs below are that commit's `engine-update.ts`): the `summaryFold?.advance(i);` line in the `engine-update.ts` validation loop was deleted (anchor x1 → x0, blob `72635fb6ff22` → `79e693a8edb8`). Every row then reads the base as stored. The suites import the engine from source, so no rebuild was needed. Result: `Tests 5 failed | 97 passed (102)`. - Red, as predicted: the filtered `count`, `sum`, `avg`, `min` and the reparent refusal. - Green, as predicted: one-by-one, single match, under the line, CONTROL, bases-read, and every unit pin. - Restore: blob `72635fb6ff22` == HEAD, `git diff HEAD` empty. Second ablation, for the calculated fields (at `06427b07`): `const computed = dependents?.(object, parentId, moved);` was replaced with `const computed = undefined as …;` (anchor x1 → x0, blob `2e7d129120ed` → `7e274c71df8f`). Result: `Tests 3 failed | 105 passed (108)`. - Red, as predicted: the dependents unit pin, and the FORMULA and STORED computed refusals. - Green, as predicted: the one-by-one formula reference, under the line, the other direction, and every earlier pin. - Restore: blob `2e7d129120ed` == HEAD, `git diff HEAD` empty. Third and fourth ablations, for S2 (at `a7affccc`), one mutation each, `Tests 1 failed | 111 passed (112)` each, restored blob == HEAD: - `resolveFormulaRelated(…, systemCtx)` → `(…, context)`: red is the caller/lookup refusal only. - The line removing the formula fields from the write's image deleted: red is the stored-reads-formula pin only. Fifth ablation, for L1 M1 (at `9e5bae05`): the line putting the unplanned formulas back before the formula pass was deleted (anchor x1 → x0, blob `726b7cceae20` → `93453eaaab6f`). Run with `-t 34465` on `summary-rollup.test.ts`: `Tests 1 failed | 21 passed | 72 skipped (94)`. - Red, as predicted: the M1 predicate-update refusal only (the update admits both rows). - Green, as predicted: the M1 one-by-one reference, its under-the-line control, and every earlier pin. - Restore: blob `726b7cceae20` == HEAD, `git diff HEAD` empty. Sixth and seventh ablations, for L2 delta M2 and S3 (at `c14d8dd9`), one mutation each, run over both files (`Tests … (120)`), restored blob == HEAD and `git diff HEAD` empty each: - M2: `if (filterReadsThroughReference(desc.filter)) continue;` → `if (filterNamesDottedPath(desc.filter)) continue;` in the loader (blob `260317ab8f34` → `eac8b30b74dd`): `Tests 2 failed | 118 passed`. Red, as predicted: the loader's nested-form pin and the M2 predicate-update refusal (the update admits). Green: the M2 one-by-one reference and every earlier pin. - S3: the overlay's pass bound 2 → 1 (one stored pass) (blob `90d4a727eaf5` → `d741636a9bb9`): `Tests 1 failed | 119 passed`. Red, as predicted: the S3 predicate-update refusal only. Green: the S3 one-by-one reference, `slack`, `headroom` and every earlier pin. Eighth ablation, for L2 delta S4 (at `d19c04bb`): the fold's `advance` stopped telling the dependents (`if (!dependents?.advance || !states) return;` → `return;`, blob `5078351317da` → `2f02052470ed`): `Tests 3 failed | 122 passed (125)`, restored blob `5078351317da` == HEAD and `git diff HEAD` empty. - Red, as predicted: the fold unit pin for the parents advanced, and the S4 high-water-mark and chain predicate-update refusals (each an "expected the write to be refused": the update admits). - Green, as predicted: both S4 one-by-one references, S3's `head_gap`, `slack`, `headroom`, M1, M2 and every earlier pin. On the order of the two passes: L2's S2 asked for a stored field to compute after the formula it reads. That would compute a value one by one never stores: the reference pin measures a stored computed field reading a formula as `null` after every by-id write. So the stored pass runs first, over the image without formulas, as the write does, and the formulas after, as the read does; the fourth ablation reds that pin. ## Where "exact" is not reached (the three stored-value exceptions) Route A (seat ruling on the card, 6938087434) asks each matched row to read the roll-up exactly as consecutive by-id updates would. In three cases the fold cannot say that value exactly. The roll-up then keeps reading the stored value, the value every row read before this change, rather than a guessed one. This applies to that roll-up for EVERY parent the update reads it for, not only the parent whose row or base caused it, because the case is decided once per roll-up per update. Every other roll-up a rule reads, and every parent field calculated from one, is still folded. A rule reading a dropped roll-up answers as it did before this PR, so nothing here can admit a row that main refuses. 1. **A summary `filter` that reads through a reference, as a dotted path** (`{ 'account.kind': 'x' }`) **or in the nested form** (`{ account: { status: 'x' } }`, the form the summary-filter lint accepts for a relation head), **or one the in-memory filter walker refuses**. The loader leaves such a roll-up out before any statement runs (`filterReadsThroughReference`). Whether a matched row counts depends on a field of ANOTHER record, reached through a reference. The matched row in memory carries the foreign key but not that record, so the in-memory walker cannot tell whether the row's old or new state passes the filter. The same limit applies on the insert arm (#25579). A filter the walker refuses (an operator it does not evaluate) cannot be judged in memory either, so it falls back the same way. Exact would need one extra read per hop, per row. 2. **A value that is not a finite number, in any matched row or any parent's base.** This covers a `sum` / `min` / `max` / `avg` over a date, a text, or a decimal that the driver returns as a string, either in a matched row or in the base the database answers. Folding needs arithmetic and ordering on the values. Comparing a JS string with a database decimal or date would invent an order that the database does not use. The same limit applies on the insert arm. 3. **A `min` / `max` when any one parent holds more than 5,000 matched rows** (`MIN_MAX_EXCLUDED_ID_BUDGET`). An extreme cannot be taken back out of an aggregate. So the base for `min` / `max` leaves the matched rows out with `id $nin (…)`. Parents are packed so that one statement names at most 500 parent ids and 5,000 excluded ids, far below SQLite's 32,766 and PostgreSQL's 65,535 bound parameters. One parent whose own matched set is larger than that cannot be excluded in one statement. `count` / `sum` / `avg` have no such limit: their base holds the matched rows as stored, and the fold subtracts each row's old part in memory, so no id list is sent. Pinned: cases 1 (both spellings; the nested form also end to end against its one-by-one reference in `summary-rollup.test.ts`) and 3, and case 2 for a base that is not a number, in `summary-batch-accumulation.test.ts` (`loadPredicateUpdateSummaryBases`: a roll-up is left out). Case 2 for a matched value that is not a number is pinned in the same file (`createPredicateUpdateSummaryFold`: no fold). The user-facing docs state all three (`content/docs/data-modeling/fields.mdx`), and so does the changeset. ## Acceptance notes - Restarted from `main` after #34612 merged (b91cefa). `origin/main` was merged again before the first runs (13741cb), and again for the L2 delta (f63c9e3). Both merges were clean. - L2 delta (review 6943284591): S1, a rule reading a parent field calculated from a roll-up, is now folded (see What changes and the second ablation). N1, the direction a predicate update can move each way, and N2, which roll-ups and parents fall back to the stored value, are written into the changeset, the docs and the exceptions section. - PR #34565 (#33876, same area) also edited `engine.ts`. It merged at 10:36Z as `6091b645`, after this head's last `main` merge. `git merge-tree --write-tree` of this head against `origin/main` with it (`48a6c3e4`) is clean. - Cost: an object with no rule reading a roll-up of it, or an update matching one row, reads nothing more (pinned by CONTROL). Otherwise: one grouped aggregate per roll-up read, per 500 parents (for `min` / `max`, also per 5,000 excluded ids), before the write. - Class (iii) (a rule of the parent itself judging the recompute's write) and the `readonlyWhen` bulk strip are outside this card, as the card's options analysis says. - Seat 3 fix round (L1 delta REWORK 6949424147, M1): the formula pass now reads the formulas outside the plan at their stored values instead of missing. This regressed in `a7affccc`; at `18f3774a` they were kept. Measured before the fix on the merged head: the new predicate-update pin was red (the update admitted both rows) while its one-by-one reference refused. Pinned with the one-by-one reference, the predicate update and an under-the-line control; ablated once (fifth ablation above). `origin/main` was merged first (`05241f49`, clean). The full dogfood battery was run on the final head (Verification). - Seat 3 fix round 2 (L2 delta FAIL 6957356275 at `9e5bae05`): M2, a `min` / `max` roll-up whose filter reads a related record in the nested form slipped past the dotted-path check and the in-memory walker answered "no match" without refusing, so it was folded over the children outside the match. The loader now leaves it out before any statement (`filterReadsThroughReference`), so it reads the stored value as the dotted form does, and the base aggregate that #33876 refuses on a driver without `readableIdsLeaf` is never sent for it. S3, fixed rather than stated: the fold evaluates the stored plan twice, as the by-id write does. The changeset and `fields.mdx` name the nested form; the S3 fix keeps their existing claim true. Both pinned with a one-by-one reference and ablated once each (sixth and seventh ablations). N6 (nit) is left to the follow-up card with N3 and N4. The insert arm's own dotted-path check (`createBatchSummaryAccumulator`) is unchanged: there a nested-form filter contributes nothing for every new row, which leaves the stored value, the same answer as leaving it out. - Seat 3 fix round 3 (L1-e delta ACCEPT 6961160128 at `c14d8dd9`, contract review delta 6961415010 with S4): S4 was fixed by carrying one image per parent through the fold (the review's first remedy), not by stating it: the change is small (an optional `advance` on `SummaryDependents`, called by the fold's `advance`, and an image map in `loadSummaryFoldDependents`), the same shape as the S3 fix. N7 (nit, trivial) is folded in: `filterReadsThroughReference` asks `isNoOperatorObject` too, so an empty object beneath a field (`{ acct: {} }`) is left out like the nested form. The insert arm is untouched (its limit went to #34821, comment 6961449942). N3, N4 and N6 stay on #34821. - Follow-up #34821 (Blocked-by #34465): L2 nits N3 (row 0 reads the base even when the patch moves no roll-up) and N4 (no trace of the three fallbacks), and the same shape as S1 on the multi-row insert side (#34612's accumulator overlays the summary field only, so a rule reading a formula built on it still reads the stored value). ## Verification All readings are on the final head `d19c04bb` (`d19c04bb49e278843e9aceaacea198b9961440ae`: S4 and N7 over `c14d8dd9`). `origin/main` was not merged again: `overlap-check` against `origin/main` `db1a05cd` and the PRs sharing files (#34978, #34817, #34799) reads `VERDICT clean exit 0`. <details><summary>Full dogfood battery</summary> - `bash scripts/pm/os-verify-lock.sh -c "pnpm --filter '@objectstack/dogfood^...' build && pnpm --filter @objectstack/dogfood test"` on `d19c04bb` (no shard, no path): `Test Files 479 passed | 3 skipped (482)`, `Tests 4072 passed | 68 skipped (4140)`, `VERDICT command-exit 0`. No failure. - The earlier batteries on `9e5bae05` and `c14d8dd9` (same counts, `VERDICT 0`) no longer count for this head. </details> <details><summary>Local runs</summary> - `pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2` on `d19c04bb`: `Test Files 607 passed (607)`, `Tests 13700 passed (13700)`. - `src/summary-rollup.test.ts` + `src/summary-batch-accumulation.test.ts` on `d19c04bb`: `Tests 125 passed (125)`. - `pnpm --filter @objectstack/objectql typecheck`: exit 0 (`check:test-typecheck` OK), on `52e46807`, the same commit before a one-string amend of a test rule's CEL condition (a null guard) that made it `d19c04bb`. - `node scripts/check-nul-bytes.mjs`: exit 0. `overlap-check`: `VERDICT clean exit 0` (above). - The full derived gate sweep was run on `c14d8dd9` (99 families: 98 run with exit 0, 1 NOT-MEASURED, `check:type-check-debt`, lock queue-timeout). This round's diff moves only objectql source and its two test files, all inside the earlier sweep's paths; the families are CI's on this head. - PR check-runs on `d19c04bb`: 55 completed, 40 success, 15 skipped, none failed. - `pnpm lint` and the rest of the farm: CI. </details> ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (`packages/spec` not touched) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` is CI's run (not run locally). - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: its generated artifacts are regenerated and committed. (not touched) - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzfr1xZSFZzCR8HnqXX --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6f2bd4f commit 94a2d8b

8 files changed

Lines changed: 1314 additions & 11 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql)!: a predicate update judges each matched row against the parent summaries the rows judged before it move, as consecutive by-id updates do
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. What moves is the summary value a rule reads while one predicate update is judged: no stored row, registry key or authored value changes, so there is nothing for a migration to rewrite and no tombstone. -->
11+
12+
**BREAKING** for a predicate update (`update(object, patch, { where, multi: true })`, a flow `update_record` step with `multi: true`) of a child object whose validation rule reads a roll-up `summary` of a parent one hop through a reference (`record.inv.primaries > 0`), or whose field-level `requiredWhen` reads one on `parent` (`parent.line_count >= 3`), or that reads a `formula` or stored computed field of the parent calculated from one (`record.project.remaining`, `remaining = budget - spent`). A bulk create and a bulk update already equal one-by-one writes for a rule reading the summary itself (a bulk create does not yet for a rule reading a parent field calculated from one: its accumulator moves the summary key alone, #34821); this extends that to the update that selects its rows by a filter, calculated parent fields included.
13+
14+
- FROM: the matched rows' related parents and master-detail headers were read once, and every row judged the summary as it stood before the update: "one primary line per invoice" (`record.is_primary == true && record.inv.primaries > 0`) refused the second of two lines made primary one by one, and admitted both made primary by one predicate update.
15+
- TO: each matched row judges the summary as the rows judged before it leave it, for `count`, `sum`, `min`, `max` and `avg`, a row moving to another parent included: the base is read in the database (every child as stored for `count` / `sum` / `avg`, the children outside the matched set for `min` / `max`, one grouped aggregate per summary a rule reads) and the matched rows are folded in memory. A parent field calculated from a folded summary is computed again over the parent with the folded value. The update is refused with `VALIDATION_FAILED` and writes nothing, as it does for any refused row. Only an object with such a rule, on an update matching more than one row, reads the base (and, when a calculated field reads a folded summary, the parents' stored rows once).
16+
- The answer moves both ways. Mostly it narrows: main admitted a row that one-by-one refuses, and it is refused now. It also admits a row main refused when the rows judged before it move the summary toward admitting it, as one by one does. For example, with `parent.line_count >= 3` requiring a field, a row leaving that parent lowers the count the later rows read.
17+
18+
**Not moved.** A rule that reads no summary, a predicate update matching one row, a by-id update, hooks and flow steps (they read the value from before the update), and a rule of the parent itself (it judges the summary once, after the write). Three cases keep reading the stored value, as before, and each one covers that summary for EVERY parent the update reads it for, not only the parent that caused it:
19+
- a summary whose `filter` reads through another reference, as a dotted path (`{ 'account.kind': 'x' }`) or in the nested form (`{ account: { status: 'x' } }`), or that the in-memory filter walker refuses;
20+
- a summary meeting a value that is not a number, in any matched row or in any parent's base;
21+
- a `min` / `max` when any one parent holds more than 5,000 matched rows.
22+
23+
The fix for a caller: update the rows the rule refuses on their own, or narrow the filter so the update matches the rows the rule admits.

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

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,21 @@ recomputes after each row, so each row's rules, and the parent's own rules
492492
judging each recompute, read it as one-by-one updates would, for every summary
493493
function, `avg` included. A `parent.` predicate that reads a field that is not a
494494
summary, and is not calculated from one, does not count.
495+
**A predicate update equals one-by-one updates too:** an update that selects
496+
its rows by a filter (`update(object, patch, { where, multi: true })`, a flow
497+
`update_record` step with `multi: true`) judges every matched row before its
498+
one write. A validation rule reading a parent summary one hop through a
499+
reference, a detail object's `requiredWhen` reading it on `parent`, and a rule
500+
reading a formula or stored computed field of the parent calculated from it,
501+
read it as the matched rows judged before leave it, for every summary function,
502+
`avg` included, and a row that moves to another parent leaves the old one and
503+
joins the new one. If any row is refused, none is written. Three cases keep
504+
reading the stored value for every parent the update reads that summary for: a
505+
summary whose `filter` reads through another reference, as a dotted path or in
506+
the nested form `{ account: { status: 'x' } }` (or one the in-memory filter
507+
cannot evaluate), a summary meeting a value that is not a number, and a `min` / `max`
508+
when one parent holds more than 5,000 matched rows. A rule of the parent
509+
itself judges the summary once, after the write.
495510
**Hooks and flow steps read the value from before the batch:** inside one bulk
496511
create or bulk update, a hook or flow step that reads a parent's summary reads
497512
it as stored before the batch, on create and update alike.

‎packages/objectql/src/engine-summaries-and-expansion.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,19 @@ const ruleReadsByIndex = new WeakMap<object, Set<string>>();
152152
* (`summary-rule-reads.ts`).
153153
*/
154154
function rollUpReadByARule(host: Pick<SummariesAndExpansionHost, '_registry' | 'summaryIndex'>, descriptors: readonly SummaryDescriptor[]): boolean {
155+
const read = summaryFieldsReadByRulesOf(host);
156+
return descriptors.some((d) => read.has(ruleReadKey(d.parentObject, d.summaryField)));
157+
}
158+
159+
/** The `<object>.<field>` keys a rule reads, cached per built summary index ({@link ruleReadsByIndex}). */
160+
function summaryFieldsReadByRulesOf(host: Pick<SummariesAndExpansionHost, '_registry' | 'summaryIndex'>): Set<string> {
155161
const index = host.summaryIndex;
156162
let read = index ? ruleReadsByIndex.get(index) : undefined;
157163
if (!read) {
158164
read = summaryFieldsReadByRules(host._registry.getAllObjects(), index ? [...index.values()].flat() : []);
159165
if (index) ruleReadsByIndex.set(index, read);
160166
}
161-
return descriptors.some((d) => read.has(ruleReadKey(d.parentObject, d.summaryField)));
167+
return read;
162168
}
163169

164170
/**
@@ -456,6 +462,18 @@ export class SummariesAndExpansionFacet {
456462
return [...new Set(this.getSummaryDescriptors(childObject).map((desc) => desc.fkField))];
457463
}
458464

465+
/** [#34465] The roll-ups over `childObject` whose summary field a rule reads
466+
* — the same judgement that keeps a recompute from being deferred
467+
* (`summary-rule-reads.ts`, ruling 6928862195 B). A predicate update folds
468+
* exactly these into the values its rules read, so each matched row is
469+
* judged as one-by-one updates judge it. Empty when no rule reads any. */
470+
static summaryDescriptorsReadByRules(this: Pick<SummariesAndExpansionHost, '_registry' | 'getSummaryDescriptors' | 'summaryIndex'>, childObject: string): SummaryDescriptor[] {
471+
const descriptors = this.getSummaryDescriptors(childObject);
472+
if (descriptors.length === 0) return [];
473+
const read = summaryFieldsReadByRulesOf(this);
474+
return descriptors.filter((d) => read.has(ruleReadKey(d.parentObject, d.summaryField)));
475+
}
476+
459477
/** The body of `ObjectQL#getOwnedSummaryDescriptors`; the method's docblock there is its contract. */
460478
static getOwnedSummaryDescriptors(this: Pick<SummariesAndExpansionHost, 'ensureSummaryIndexes' | 'summaryIndexByParent'>, parentObject: string): SummaryDescriptor[] {
461479
this.ensureSummaryIndexes();

0 commit comments

Comments
 (0)