Skip to content

Commit cc5472e

Browse files
fix(objectql)!: a roll-up summary field is read-only on create too, and a create seeds it as for an empty child list (#35089)
<!-- 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 #34672 Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — skills/** teaches no starting value for a summary field (its only summary-write text, `skills/objectstack-data/rules/relationships.md`, is about the backfill); `content/docs/data-modeling/fields.mdx` now states the create side ## 维护者速读 - 改了什么:汇总字段(`Field.summary`)在新建时也一律只读,不管作者有没有写 `readonly: true`。普通用户的 `POST`、批量/复合新建、导入(`insert`,以及 `upsert` 新建的那些行)、MCP `create_record`、非系统身份的流程新建,送来的汇总初值都被丢掉,在 `droppedFields` 里报 `readonly`,该列按「没有子记录」起步(`count`/`sum` 为 0,`min`/`max`/`avg` 为空);开了 `strictReadonlyWrites` 则整笔拒收。顺带修好:写了 `readonly: true` 的汇总字段,新建时若带了值,过去会落成 `null`,现在落 0。 - 为什么改:#34752 只锁了更新;新建时普通用户仍可手填一个汇总初值,存下来被下游读,直到下一次子记录变动才被重算覆盖。spec 早已写明 `summary` 属于「never client-written」的计算类型(`COMPUTED_VALUE_TYPES`)。席位按路线 A 裁定(认领修正 6963962011)。 - 风险与回滚:收窄(BREAKING):今天给汇总字段带初值的非系统新建会被丢值或被拒。系统身份(`isSystem`)照写:种子数据、包安装、历史导入(`treatAsHistorical` 只许系统身份)都不受影响。Console 新建表单本来就不发汇总字段(见 Acceptance notes)。回滚即撤回本 PR,无数据迁移。 - 先看:`packages/objectql/src/engine-top-level.ts`(`insertStaticReadonlySubject` 与新的 `withSummaryRollUpsReadonly`)、`packages/objectql/src/engine-insert.ts`(`staticReadonlyCreateStrip` 里的重新播种那 4 行)、`packages/objectql/src/engine-summary-update-lock.test.ts`(新建一侧的 describe)。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-summary-update-lock.test.ts`,预期全过;新建一侧那组里「a person's create (REST POST)」断言两列都是 0、`droppedFields` 点名两个字段。 - 需要你做的:无。`check-governed-merges` 判定非受管;L1 与席位的收窄契约复审通过后由区落地。 ## What changes A roll-up `summary` field is read-only on create too, whether or not the author declared `readonly: true`, and a create that had its value taken starts the column at the empty-child-list seed. - `packages/objectql/src/engine-top-level.ts` - `insertStaticReadonlySubject(schema, wallJudgesOrganization)` is the one schema view the three create-side static `readonly` passes read: the pre-hook withhold (what `beforeInsert` is shown), the post-hook strip in `engine-insert.ts` (what is stored) and the `insert`-mode preview in `engine-validate.ts`. It now reads every roll-up as `readonly: true` before `staticReadonlyInsertSubject` judges the schema, so that function's exclusions (a `sys_` object, a platform-internal `managedBy` bucket) hold for roll-ups too. `isSystem` runs none of these passes and keeps its value. - New private helper `withSummaryRollUpsReadonly(schema)`: the one spelling of the roll-up lock, read by both the insert view and `updateStaticReadonlySubject` (the update half, #34752, now reads it instead of its own loop; no update answer changes). - `summaryFieldsLockedOnUpdate` is renamed `summaryFieldsLockedOnWrite` (it now answers both verbs). It is a module export of `engine-top-level.ts`, not a package export: `packages/objectql/dist/index.d.ts` names neither spelling. - `packages/objectql/src/engine-insert.ts`: `staticReadonlyCreateStrip` re-runs `initializeSummaryFields` over the stripped row after its re-default and copies the seed back for the TAKEN keys only. Without it the strip re-ran `applyFieldDefaults` alone, so a taken roll-up landed `null` while the write succeeded: the state the summary seed exists to rule out. That already happened before this PR for a roll-up declared `readonly: true` (route condition 1); it is fixed here for both. - `packages/objectql/src/validation/rule-validator.ts`: the `summary` note on `RUNTIME_OWNED_FIELD_TYPES` (the #6014 note) is rewritten. It keeps "do not add `summary` to this set" and says why the type rides the static `readonly` strip instead (the `isSystem`-only exemption, and the re-seed); it retires "supplying an initial value is a SUPPORTED authoring path" for an ordinary caller, per the route ruling. - `content/docs/data-modeling/fields.mdx`: the summary paragraph now covers create and update. - `.changeset/34672-summary-readonly-on-create.md`: `patch` on `@objectstack/objectql`, BREAKING, the migration line for REST, import and MCP clients, ADR-0087 `not-required (no-migration-prescription)`. - `.changeset/34672-summary-readonly-on-update.md`: DELIBERATE CORRECTION, see Acceptance notes. No new drop reason, no spec key: reason `readonly`, as on update. ## Tests - `packages/objectql/src/engine-summary-update-lock.test.ts`, new describe "a roll-up summary is read-only on create" (14 cases), real `ObjectQL` and a recording driver, `order_total` a `sum` roll-up without `readonly` beside `order_total_ro` declared `readonly: true`, written as a signed-in person unless stated: - baseline: a create naming neither stores `0` and `0`, reports nothing; - the REST POST shape: both values dropped and reported in one event, both columns `0`, the rest stored, the returned row `0`; - condition 1: the declared `readonly: true` roll-up alone lands `0`, not `null` (the driver's create payload is asserted); - a `null` starting value is taken the same way and lands `0`; - a batch (array) create and `insertMany` (the import commit; the row that sent a value carries `droppedFields`, the other none); - `strictReadonlyWrites`: refused (`code` `ERR_READONLY_FIELD_REJECTED`, `fields`, `drops`, `operation: 'insert'`), nothing written; - the `insert`-mode preview reports the same drop; - a `beforeInsert` hook is shown the seed, not the caller's value; - children already stored before the parent: the create lands `0`, not the typed value; the next child write recomputes to the true sum; - `isSystem` keeps `90` and `90` (seed loads, package installs, historical imports); - `preserveAudit` without `isSystem` is no exemption; - a `max` roll-up (no empty-set value) is dropped and stays empty; - a `sys_` object stays outside the create lock. - `packages/rest/src/import-summary-update-lock-34672.test.ts`, new describe (3 cases), real ObjectQL + protocol + SQLite `:memory:` over the HTTP routes as a signed-in person, reading the physical row: `POST /api/v1/data/:object` (201, `droppedFields` names both, both columns `0`); import `writeMode: 'insert'` dry run and commit (row 1 carries `droppedFields`, stored `0`); import `writeMode: 'upsert'` (drops on the updated row and on the created row; a created row whose children were already stored lands `0`, and the next child `POST` recomputes to `51`). - Changed pins, each forced by the narrowing and each now stating the new expectation (route condition 4; no pin deleted): 1. `engine-summary-update-lock.test.ts` "INSERT is not narrowed: a caller's initial value is kept" → "INSERT is narrowed too: a person's starting value is dropped, reported, and the column seeded 0". 2. `summary-rollup.test.ts` "never overwrites a value the author supplied on insert" → "never overwrites a value a system writer supplied on insert (seed data, a historical import)": the same assertion, now written with `isSystem: true`, the only writer that may still supply one; beside it a new case, "an ordinary caller's value on insert is dropped, and the seed fills the column" (`0` and `0`). 3. `summary-rollup.test.ts` "seeds every row of a batch insert, and only the unsupplied ones" → the same assertions with a system writer. 4.–7. `engine-blank-typed-value-door.test.ts`, the four insert cases (`""` one row, `" "` one row, array + `insertMany`, "a valid value on every typed column … (the roll-up's is dropped)"): every other typed column still reaches the driver as `null` / unchanged, and no `f_summary` is sent on create, as it already was not on update (the shared `expectTypedNull` now says so for both verbs). 8. `packages/rest/src/rest-data-blank-typed-value.test.ts`: the fixture `seed` helper writes as the system principal (that is the writer that may still set `f_summary: 7`); "a valid value on every typed column" now expects `droppedFields` naming `f_summary` and the column `null` (this fixture's roll-up declares no `summaryOperations`, so there is no seed). Ablation (`node scripts/ablation-replace.mjs`, each leg restored to the HEAD blob with `git diff HEAD` empty; the objectql suites import the engine from source, so no build sits between the edit and the run): - The lock, `engine-top-level.ts` `staticReadonlyInsertSubject(withSummaryRollUpsReadonly(schema) as any)` → `staticReadonlyInsertSubject(schema as any)` (anchor x1 → x0, blob `853f70980a4d` → `4c1dc5b1d8f4`): `Tests 16 failed | 91 passed (107)`. Red: the flipped insert pin, 10 of the 14 create cases, the ordinary-caller `summary-rollup` case and the 4 blank-door insert cases. Green, as predicted: the baseline, the declared `readonly: true` case (the declared flag is taken without the lock), `isSystem`, `sys_`, every update case and the system-writer `summary-rollup` cases. - The re-seed, `engine-insert.ts` `if (stripped[k] == null && reseeded[k] !== undefined) stripped[k] = reseeded[k];` → `void reseeded[k];` (blob `0b8e11afbbae` → `3c2e0b671768`): `Tests 10 failed | 97 passed (107)`. Red includes condition 1's pin ("the declared readonly: true roll-up alone lands 0, not null"); green: the baseline, `isSystem`, the `max` case, `sys_`, strict, preview and every update case. ## Acceptance notes - Console create form (route condition 2), measured on this head: the Console does NOT send a summary field on create. `ObjectForm` builds its create payload with `formWritePayload` (`ui/packages/plugin-form/src/writePayload.ts`), whose first step is `sanitizeFormData`; `ModalForm` and `DrawerForm` call `sanitizeFormData` directly; the master-detail batch sanitizes child rows the same way. `sanitizeFormData` drops every field whose type is in `COMPUTED_FIELD_TYPES` (`ui/packages/plugin-form/src/sanitize.ts`, `summary` a member) whenever the object schema is supplied, and `ObjectForm` renders a summary control disabled. Existing pins: `ui/packages/plugin-form/src/sanitize.test.ts` "drops computed / read-only field types when a schema is provided" (`task_count: { type: 'summary' }` dropped) and `ui/packages/plugin-form/src/masterDetailTx.test.ts` "buildMasterDetailBatch strips computed/server-managed child fields" (a child `summary` dropped from the create op); both run on this head, `Test Files 2 passed (2)`, `Tests 21 passed (21)`. The import mapping also offers no summary target (`ui/packages/app-shell/src/views/importTargetFields.ts`, `COMPUTED_TYPES`). One edge, harmless after this PR: a form built only from inline `customFields` sanitizes with no schema, so a summary there would not be filtered client-side; the engine now drops and reports it. No `ui/` change. - DELIBERATE CORRECTION of an unreleased changeset, `.changeset/34672-summary-readonly-on-update.md` (#34752's, not yet consumed by a release), two sentences, because they state the create-side answer this PR reverses: - was "An import with `writeMode: 'upsert'` drops the value on the rows it updates and keeps it on the rows it creates." now "An import with `writeMode: 'upsert'` drops the value on the rows it updates; the rows it creates are covered by the create-side entry (`34672-summary-readonly-on-create`)." - was "Not changed: a create keeps a value sent for a summary field as its starting value, …" now "Not changed by this entry: the create side, which the create-side entry (`34672-summary-readonly-on-create`) narrows in the same release; seed data and a historical import, which write as the system principal, still carry a pre-computed total on create." The dispatch order for this round names both changesets in the file surface. - `node scripts/pm/overlap-check.mjs` reports one overlap, with #33849 (`chore: version packages`) on that same changeset: the Version Packages PR deletes the file it consumes and this PR edits it. It is regenerated from `main`, so it is no queue; every other candidate (#34978, #34817, #34709) and `origin/main` merge cleanly. - The rename `summaryFieldsLockedOnUpdate` → `summaryFieldsLockedOnWrite` has no caller outside `packages/objectql/src` (`git grep`), and `node scripts/check-platform-checklist.mjs --changed-from origin/main` reports `0 lost`. - Started from the lost round's pushed head `4f08aded` (Resume-from); the work was reviewed against route A and its five conditions and found complete; this round added a merge of `main` and the verification below. The `(wip)` subject on `5430eb9a` is left in history, not rewritten. ## Verification Final head `b2f55b4eb7e8e029c1df489121a97f18c7814370`: a merge of `main` (`eb7b09d4d2`, 9 first-parent commits, none in `packages/objectql`) over the lost round's head `4f08aded`, no conflict. Every reading below ran on this head. <details><summary>Full dogfood battery</summary> - On `b2f55b4eb7e8e029c1df489121a97f18c7814370`, under one `os-verify-lock.sh` hold (`VERDICT command-exit 0`, held 45m22s): `pnpm --workspace-concurrency=2 --filter '@objectstack/dogfood^...' build && pnpm --filter @objectstack/dogfood test` (no shard, no path): `Test Files 479 passed | 3 skipped (482)`, `Tests 4072 passed | 68 skipped (4140)`. No failure. </details> <details><summary>Local runs</summary> - Under one lock hold: `pnpm --filter @objectstack/objectql typecheck` exit 0, `pnpm --filter @objectstack/rest typecheck` exit 0 (both `tsc --noEmit && pnpm check:test-typecheck`), `pnpm --filter @objectstack/objectql test` exit 0 (`Test Files 610 passed (610)`, `Tests 13739 passed (13739)`), `pnpm --filter @objectstack/rest test` exit 0 (`Test Files 418 passed (418)`, `Tests 8610 passed | 350 skipped (8960)`). Built first: `pnpm --workspace-concurrency=2 --filter '@objectstack/rest...' build`, `VERDICT command-exit 0`. - The card's pins: `pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-summary-update-lock.test.ts src/summary-rollup.test.ts src/engine-blank-typed-value-door.test.ts` (`Tests 107 passed (107)`) and `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/import-summary-update-lock-34672.test.ts src/rest-data-blank-typed-value.test.ts` (`Tests 13 passed (13)`), `VERDICT command-exit 0`. - Console pins, from `ui/`: `pnpm exec vitest run --maxWorkers=2 packages/plugin-form/src/sanitize.test.ts packages/plugin-form/src/masterDetailTx.test.ts`, `Test Files 2 passed (2)`, `Tests 21 passed (21)`. - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 101 derived commands, each recorded as `CMD :: exit N`; `--ran` reconciliation: "101 derived, 100 run, 1 NOT-MEASURED, 0 UNRUN". 99 exit 0. `node scripts/check-empty-changeset.mjs --base origin/main` exit 1, the DELIBERATE CORRECTION above (red by design until the seat's record). `pnpm check:type-check-debt` exit 3 twice, NOT MEASURED, reason: its closure build queues for the verify lock, held first by this PR's battery and then by a sibling's dogfood run (queue timeout 540s); its coverage half printed `OK — 128/131 workspace packages type-checked`; CI's run is the reading. - `node scripts/check-platform-checklist.mjs --changed-from origin/main`: exit 0, `0 lost`. - `node scripts/pm/overlap-check.mjs --branch=HEAD`: `VERDICT overlap exit 1`, only #33849 (Version Packages) on the corrected changeset, see Acceptance notes; `origin/main` `eb7b09d4d2`, #34978, #34817 and #34709 merge cleanly. - The full repo farm (`pnpm lint`, `test:repo`, the other packages): CI. </details> --- 🤖 Generated with [Claude Code](https://claude.com/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 ab1c734 commit cc5472e

11 files changed

Lines changed: 450 additions & 103 deletions
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql)!: a roll-up `summary` field is read-only on create too, and a create seeds it as for an empty child list
6+
7+
Clause-②: no (narrowing)
8+
Metadata-protocol: none
9+
10+
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: the moved answer is whether a non-system create may store a caller's starting value in a roll-up summary column. The one-line fix is in the body: leave the summary field out of the create payload, or write it from server code with isSystem: true. -->
11+
12+
**BREAKING** for a caller that sets a starting value on a `summary` field. A REST `POST /api/v1/data/:object` (and the batch, `createMany` and composite create doors), an import with `writeMode: 'insert'`, the rows an import with `writeMode: 'upsert'` creates, an MCP `create_record`, a flow `create_record` that does not run as system, and the `insert`-mode preview (`validate`) now drop a value sent for a roll-up summary field, as the update side already does. The rest of the row is stored, and `droppedFields` / `onFieldsDropped` (an import row's `droppedFields`) name the field with reason `readonly`. The column starts as if no value had been sent: `0` for `count` and `sum`, empty for `min`, `max` and `avg`; the next child write replaces it with the computed value. Under `strictReadonlyWrites` the whole create is refused with `ERR_READONLY_FIELD_REJECTED` and nothing is written. Before this change the typed value was stored and read downstream (defaults, rules, reports) until the next child write recomputed the roll-up.
13+
14+
Migration for REST, import and MCP clients that set a starting roll-up value: that value is now dropped and reported in `droppedFields`; leave the summary field out of the create payload and let the child rows compute it. Server code that must load a pre-computed total (seed data, a package install, a historical import with `treatAsHistorical: true`, a repair job) writes as the system principal, `{ context: { isSystem: true } }`, which keeps the value, as it keeps every read-only value it sends.
15+
16+
Also fixed: a create that sent a value for a roll-up declared `readonly: true` stored `null` in the column, not the empty-child-list `0`, while the write still succeeded. The value is still dropped and reported, and the column now starts at `0` (`count` / `sum`).
17+
18+
Not changed: seed loads, package installs, historical imports, the roll-up recompute, the backfill and the enable refresh write as before. An in-process create that passes `preserveAudit` without `isSystem` gets no exemption, as for every other read-only column on create. Objects in the `sys_` namespace and the platform-internal `managedBy` buckets stay outside the create-side strip.

‎.changeset/34672-summary-readonly-on-update.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ Metadata-protocol: none
99

1010
<!-- adr-0087: not-required (no-migration-prescription) No schema key, accepted value or metadata type is added, removed or renamed, and nothing stored is rewritten: the moved answer is whether a non-system update may store a caller's value in a roll-up summary column. The one-line fix for a refused write is in the body: leave the summary field out of the update payload, or write it from server code with isSystem: true. -->
1111

12-
**BREAKING** for a caller that updates a `summary` field. A `PATCH /api/v1/data/:object/:id`, an import with `writeMode: 'update'`, a predicate (`multi: true`) update and the `update`-mode preview (`validate`) now drop a value sent for a roll-up summary field, as they already did for one declared `readonly: true`. The rest of the write is stored, and `droppedFields` / `onFieldsDropped` name the field with reason `readonly`. Under `strictReadonlyWrites` the whole update is refused with `ERR_READONLY_FIELD_REJECTED` and nothing is written. Before this change the typed value was stored and read downstream (defaults, rules, reports) until the next child write recomputed the roll-up. An import with `writeMode: 'upsert'` drops the value on the rows it updates and keeps it on the rows it creates. Undoing a non-historical import that was committed before this release restores the rows' `before` snapshot through an ordinary update, so a summary value that import overwrote is not put back; it stays until the next child write recomputes it.
12+
**BREAKING** for a caller that updates a `summary` field. A `PATCH /api/v1/data/:object/:id`, an import with `writeMode: 'update'`, a predicate (`multi: true`) update and the `update`-mode preview (`validate`) now drop a value sent for a roll-up summary field, as they already did for one declared `readonly: true`. The rest of the write is stored, and `droppedFields` / `onFieldsDropped` name the field with reason `readonly`. Under `strictReadonlyWrites` the whole update is refused with `ERR_READONLY_FIELD_REJECTED` and nothing is written. Before this change the typed value was stored and read downstream (defaults, rules, reports) until the next child write recomputed the roll-up. An import with `writeMode: 'upsert'` drops the value on the rows it updates; the rows it creates are covered by the create-side entry (`34672-summary-readonly-on-create`). Undoing a non-historical import that was committed before this release restores the rows' `before` snapshot through an ordinary update, so a summary value that import overwrote is not put back; it stays until the next child write recomputes it.
1313

1414
To fix a refused or dropped write: leave the summary field out of the update payload. Server code that must set the column (a migration, a repair job) passes `{ context: { isSystem: true } }`, which the roll-up recompute itself uses and which this lock exempts, as it exempts every read-only column.
1515

16-
Not changed: a create keeps a value sent for a summary field as its starting value, so seed data and a historical import may still carry a pre-computed total; the next child write replaces it with the computed one. A historical import (`treatAsHistorical: true`, which writes with `preserveAudit`) keeps a summary value it sends on update too, as it keeps any other read-only value it sends, and so does the undo of such an import. The roll-up recompute, the backfill and the enable refresh write as before. A summary field that already declares `readonly: true` answers exactly as before.
16+
Not changed by this entry: the create side, which the create-side entry (`34672-summary-readonly-on-create`) narrows in the same release; seed data and a historical import, which write as the system principal, still carry a pre-computed total on create. A historical import (`treatAsHistorical: true`, which writes with `preserveAudit`) keeps a summary value it sends on update too, as it keeps any other read-only value it sends, and so does the undo of such an import. The roll-up recompute, the backfill and the enable refresh write as before. A summary field that already declares `readonly: true` answers exactly as before.

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

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -396,22 +396,20 @@ are inserted, updated, or deleted. `relationshipField` is optional when the chil
396396
has only one `lookup`/`master_detail` field pointing back to the parent; set it
397397
when multiple relationships target the same parent object.
398398
399-
On update a summary field is read-only whether or not it declares `readonly: true`.
400-
A value that a `PATCH`, an import with `writeMode: 'update'` or a bulk update
401-
sends for it is dropped, the rest of the write is stored, and the response's
402-
`droppedFields` names the field with reason `readonly`. Under
403-
`strictReadonlyWrites` the whole update is refused. Server code that runs with
404-
`isSystem: true` can still write the column, as it can any read-only column.
405-
On create, a value you send is kept as the field's starting value (seed data or
406-
a historical import may carry a pre-computed total); the next child write
407-
replaces it with the computed one.
408-
An import with `writeMode: 'upsert'` therefore drops the value on the rows it
409-
updates and keeps it on the rows it creates. A historical import
410-
(`treatAsHistorical: true`, which writes with `preserveAudit`) keeps a summary
411-
value on update as well, as it keeps any other read-only value it sends. Undoing
412-
an ordinary import restores the rows through an ordinary update, so a summary
413-
value that an import committed before this rule overwrote is not put back by
414-
the undo; it stays until the next child write recomputes it.
399+
A summary field is read-only on create and on update whether or not it declares
400+
`readonly: true`. A value that a `POST`, an import (any `writeMode`), an MCP
401+
create, a `PATCH` or a bulk update sends for it is dropped, the rest of the write
402+
is stored, and the response's `droppedFields` names the field with reason
403+
`readonly`. A record created that way starts as if no value had been sent: `0`
404+
for `count` and `sum`, empty for `min`, `max` and `avg`, and the next child write
405+
replaces it with the computed value. Under `strictReadonlyWrites` the whole write
406+
is refused. Server code that runs with `isSystem: true` can still write the
407+
column, as it can any read-only column: seed data, package installs and a
408+
historical import (`treatAsHistorical: true`, which only the system principal may
409+
send) keep a pre-computed total, on create and on update. Undoing an ordinary
410+
import restores the rows through an ordinary update, so a summary value that an
411+
import committed before this rule overwrote is not put back by the undo; it stays
412+
until the next child write recomputes it.
415413
416414
Because the roll-up is engine-derived state rather than a user write, the
417415
recompute runs under a system context: a user who may create a child does not

‎packages/objectql/src/engine-blank-typed-value-door.test.ts‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,16 @@ const VALID: Record<string, unknown> = {
132132
const blankTyped = (v: string) => Object.fromEntries(TYPED.map((t) => [f(t), v]));
133133
const STR_BLANK = { c_text: '', c_lookup: '', c_select: '' };
134134

135+
// [#34672] A `summary` column is read-only on create and on update for an
136+
// ordinary caller: a caller's value for it, a blank included, is dropped
137+
// before the driver, so no write here sends `f_summary` at all (this fixture's
138+
// roll-up declares no `summaryOperations`, so the create seed has nothing to
139+
// fill it with either). Every other typed column still lands null.
140+
const WRITABLE_TYPED = TYPED.filter((t) => t !== 'summary');
141+
135142
function expectTypedNull(data: Record<string, unknown>) {
136-
for (const t of TYPED) expect(data[f(t)], t).toBeNull();
143+
for (const t of WRITABLE_TYPED) expect(data[f(t)], t).toBeNull();
144+
expect(data).not.toHaveProperty(f('summary'));
137145
}
138146

139147
describe('engine write doors: a blank on a non-string-typed column reaches the driver as null (#20308)', () => {
@@ -178,28 +186,24 @@ describe('engine write doors: a blank on a non-string-typed column reaches the d
178186
});
179187

180188
it('update by id and update by predicate', async () => {
181-
// [#34672] A `summary` column is read-only on update: a caller's value
182-
// for it, a blank included, is dropped before the driver, so the update
183-
// sends no `f_summary` at all. Every other typed column still lands null.
184-
const updateTyped = TYPED.filter((t) => t !== 'summary');
185-
const expectUpdateTypedNull = (data: Record<string, unknown>) => {
186-
for (const t of updateTyped) expect(data[f(t)], t).toBeNull();
187-
expect(data).not.toHaveProperty(f('summary'));
188-
};
189189
await engine.insert('blank_door', { id: 'u1', ...VALID });
190190
await engine.update('blank_door', { id: 'u1', ...blankTyped(''), ...STR_BLANK });
191191
const byId = last('update');
192-
expectUpdateTypedNull(byId);
192+
expectTypedNull(byId);
193193
expect([byId.c_text, byId.c_lookup, byId.c_select]).toEqual(['', null, null]);
194194

195195
await engine.update('blank_door', blankTyped(''), { where: { id: { $in: ['u1'] } }, multi: true } as any);
196-
expectUpdateTypedNull(last('updateMany'));
196+
expectTypedNull(last('updateMany'));
197197
});
198198

199-
it('a valid value on every typed column — falsy ones included — is unchanged', async () => {
199+
it('a valid value on every typed column — falsy ones included — is unchanged (the roll-up\'s is dropped)', async () => {
200200
await engine.insert('blank_door', { id: 'v1', ...VALID });
201201
const sent = last('create');
202-
for (const [k, v] of Object.entries(VALID)) expect(sent[k], k).toStrictEqual(v);
202+
for (const [k, v] of Object.entries(VALID)) {
203+
if (k === f('summary')) continue;
204+
expect(sent[k], k).toStrictEqual(v);
205+
}
206+
expect(sent).not.toHaveProperty(f('summary'));
203207
});
204208

205209
it('required refuses a blank exactly as it refuses null — insert and update', async () => {

‎packages/objectql/src/engine-insert.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,13 +179,23 @@ export class InsertFacet {
179179
* need it. Scoped to the TAKEN keys: those are the only defaults this pass
180180
* keeps, so no other field's default can make it ask, or fail.
181181
*
182+
* [#34672] A taken roll-up `summary` is then re-SEEDED, after its default:
183+
* `initializeSummaryFields` over the stripped row, copied back for the
184+
* taken keys only, so the column starts at the empty-child-list value (`0`
185+
* for `count` / `sum`) exactly as a create that never named it does. The
186+
* re-default alone never asked the seed, so a value taken from a
187+
* `readonly: true` roll-up left the column `null` (the #5749 state, which
188+
* the seed exists to rule out) while the write still succeeded. The seed
189+
* yields nothing for `min` / `max` / `avg`, which stay empty as on any
190+
* create.
191+
*
182192
* @returns the row as the strip leaves it (the SAME reference when nothing
183193
* was taken) and the keys taken, in the row's key order. When the
184194
* re-default's permission resolution fails, `error` carries it and `row`
185195
* is the row as it arrived: the caller decides whether that fails the
186196
* write or culls the row, and the taken keys are still reported.
187197
*/
188-
static async staticReadonlyCreateStrip(this: Pick<InsertHost, 'applyFieldDefaults' | 'resolveDefaultPermissions'>, object: string, readonlySubject: NonNullable<ReturnType<typeof staticReadonlyInsertSubject>>, row: Record<string, unknown>, supplied: Readonly<Record<string, unknown>>, context: ExecutionContext | undefined, pass: {
198+
static async staticReadonlyCreateStrip(this: Pick<InsertHost, 'applyFieldDefaults' | 'initializeSummaryFields' | 'resolveDefaultPermissions'>, object: string, readonlySubject: NonNullable<ReturnType<typeof staticReadonlyInsertSubject>>, row: Record<string, unknown>, supplied: Readonly<Record<string, unknown>>, context: ExecutionContext | undefined, pass: {
189199
logger: Parameters<typeof stripReadonlyFields>[3];
190200
strictReadonlyWrites: boolean;
191201
hookWrittenKeys: ReadonlySet<string> | undefined;
@@ -215,6 +225,10 @@ export class InsertFacet {
215225
for (const k of taken) {
216226
if (redefaulted[k] !== undefined) stripped[k] = redefaulted[k];
217227
}
228+
const reseeded = this.initializeSummaryFields(object, stripped) as Record<string, unknown>;
229+
for (const k of taken) {
230+
if (stripped[k] == null && reseeded[k] !== undefined) stripped[k] = reseeded[k];
231+
}
218232
}
219233
return { row: stripped, taken };
220234
}

0 commit comments

Comments
 (0)