Skip to content

Commit a825152

Browse files
fix(objectql)!: a roll-up summary field is read-only on update whether or not it declares readonly: true (#34752)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBFyg5B2muWbKZjA9phXVWse)_ Part of #34672 (the update side; the create side stays open on the card, scope note 6949162788) Clause-②: no (narrowing) Metadata-protocol: none Skills-docs: none — skills/** teaches `readonly: true` and summary fields but says nothing on what an update does with a value sent for a summary field; `content/docs/data-modeling/fields.mdx` now states it ## 维护者速读 - 改了什么:汇总字段(`Field.summary`)在更新时一律只读,不管作者有没有写 `readonly: true`。人用 PATCH 改、导入用 `writeMode: 'update'` 改、批量条件更新改、更新预览,送来的汇总值都被丢掉,其余字段照写,`droppedFields` 里报 `readonly`;开了 `strictReadonlyWrites` 则整笔拒收。 - 为什么改:卡上实测 18.5.0 里销售能把「累计已转吨数」「实际成交额」「客户订单合计」直接改成任意数,存下来被下游读,直到下次子记录变动才被重算覆盖。汇总值是引擎算的,不该能手填。 - 风险与回滚:收窄(BREAKING):今天能写进汇总字段的非系统更新会被丢或被拒。系统上下文(`isSystem`)照写,汇总重算本身就是这条路,不受影响。新建记录时带的初值照旧保留(种子数据、历史导入的预算合计,按 #6014 的既有设计)。 - 仍未覆盖:普通用户新建记录时,仍可给没写 `readonly: true` 的汇总字段带一个初值,直到下一次子记录变动重算为止;这一半留在 #34672 继续处理(席位 6949162788),所以本 PR 写 `Part of #34672`,卡不随合并关闭。回滚即撤回本 PR,无数据迁移。 - 先看:`packages/objectql/src/engine-top-level.ts`(`updateStaticReadonlySubject` 与新的 `summaryFieldsLockedOnUpdate`)、`packages/objectql/src/engine-summary-update-lock.test.ts`、`packages/rest/src/import-summary-update-lock-34672.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-summary-update-lock.test.ts`,预期 11 条全过;把 `engine-top-level.ts` 里 `summaryFieldsLockedOnUpdate(schema)` 换成 `[]` 后其中 5 条变红。 - 需要你做的:无。`check-governed-merges` 判定非受管,L1 与契约复审通过后由区自行落地。 ## What changes A roll-up `summary` field is read-only on update whether or not the author declared `readonly: true`. - `packages/objectql/src/engine-top-level.ts` - `updateStaticReadonlySubject(schema, wallJudgesOrganization)` is the one schema view every update-side static `readonly` pass judges: the pre-hook hide pass (`engine-update.ts`, what `beforeUpdate` is shown), the by-id strip and the predicate (`multi`) strip (what is stored), `staticReadonlyStoredView` (read by the `readonlyWhen` strips and the master-detail settlement), and the `update`-mode preview in `engine-validate.ts`. It now also reads every `summary` field as `readonly: true`. So all five take the same key, report it through `onFieldsDropped` / `droppedFields` with reason `readonly`, and refuse it under `strictReadonlyWrites` (`ERR_READONLY_FIELD_REJECTED`). - New export `summaryFieldsLockedOnUpdate(schema)`: the `summary` fields not already declared `readonly: true`, keyed on `type === 'summary'` literally. - The `stripComputedWriteFields` doc points at the new lock: that door runs in every context, so it would also take the recompute's own write; this one exempts `isSystem`. - `content/docs/data-modeling/fields.mdx`: one paragraph under the summary field section. - `.changeset/34672-summary-readonly-on-update.md`: `patch` on `@objectstack/objectql`, BREAKING, the one-line fix, ADR-0087 `not-required (no-migration-prescription)`. No new drop reason, no spec key: reason `readonly`, as `autonumber` already rides it without the flag (#5503). ## Why The card measured on 18.5.0: a sales rep's `PATCH` of `crm_quote_line_item.cb_converted_quantity` stored `90` with no order behind it; a manager's `PATCH` or an import update moved `crm_opportunity.cb_actual_won_amount` from `619469.03` to `2`; `crm_account.cb_order_amount` took `55`. Each value stayed until a child write recomputed the roll-up, and downstream defaults read it. The spec already says `summary` is "never client-written" (`COMPUTED_VALUE_TYPES`); the update path did not enforce it. Why the `readonly` strip and not the `computed` door: `stripComputedWriteFields` runs in every context, `isSystem` included, so it would also take the roll-up recompute's write (`recomputeSummaries` writes the parent through `update()` with `isSystem: true` and `SUMMARY_RECOMPUTE_WRITE`), and the spec describes `computed` as a formula with no column. The static `readonly` strip already skips `isSystem` writes (`staticReadonlyStripRuns = !isSystem`), so the recompute, the backfill and the enable refresh keep writing without reading the marker. Insert is NOT narrowed. A create keeps a caller's value as the field's starting value. The `summary` note on `RUNTIME_OWNED_FIELD_TYPES` (`packages/objectql/src/validation/rule-validator.ts`, the #6014 note) keeps the type out of the insert-side strip on purpose: seed data and a historical import may carry a pre-computed total, and `initializeSummaryFields` seeds only the roll-ups the caller left out. This PR does not overturn it; the insert half is reported to the seat as a finding. ## Tests - `packages/objectql/src/engine-summary-update-lock.test.ts` (new, 11 cases), one account whose `order_total` is a `sum` roll-up with no `readonly`, beside the same roll-up declared `readonly: true`, written as a signed-in person: - by-id update (the PATCH door): the roll-up is dropped and reported as `readonly`, the rest of the payload is written; - predicate update (`multi: true`): dropped from every matched row, reported once; - `strictReadonlyWrites`: by-id and predicate both refused (`code` `ERR_READONLY_FIELD_REJECTED`, `fields`, `drops`, `operation`), nothing written; - the `update`-mode preview reports the same drop; - the next child write recomputes the roll-up after a dropped write; - an `isSystem` write of the column is kept; - CONTROL: the declared `readonly: true` roll-up answers the same, and a payload naming both reports both in one event; - insert keeps a caller's initial value; - two unit pins on `summaryFieldsLockedOnUpdate`. - `packages/rest/src/import-summary-update-lock-34672.test.ts` (new, 3 cases), real ObjectQL + protocol + SQLite `:memory:` through the HTTP routes as a signed-in person: `PATCH /api/v1/data/:object/:id`; `POST /api/v1/data/:object/import` with `writeMode: 'update'`, dry run and commit (each row's `droppedFields` and the stored value); the declared `readonly: true` control on both doors. - Changed tests (forced by the narrowing), the two #20308 blank-typed-value pins. Each sends a blank for every typed column, `f_summary` included, and asserted each lands `null`. On update the `summary` blank is now dropped, so: - `packages/objectql/src/engine-blank-typed-value-door.test.ts`, case "update by id and update by predicate": every other typed column reaches the driver as `null`, and no `f_summary` is sent; - `packages/rest/src/rest-data-blank-typed-value.test.ts` (SQLite), the PATCH, batch update and updateMany doors: every other typed column stores `null`, and `f_summary` keeps its seeded `7`. - The insert / create cases of both files are unchanged. Ablation (`node scripts/ablation-replace.mjs`, on 7aebcc3): `const rollUps = summaryFieldsLockedOnUpdate(schema);` replaced by `const rollUps: string[] = [];` (anchor x1 → x0, blob `c112f3aea19e` → `b4d66f559710`). The suites import the engine from source. Result: `Tests 6 failed | 14 passed (20)`. - Red, as predicted: by-id, predicate, strict, preview, CONTROL (the undeclared roll-up is stored), and the forced blank-door case. - Green, as predicted: the baseline, the recompute, `isSystem`, insert and the two unit pins. - Restore: blob `c112f3aea19e` == HEAD, `git diff HEAD` empty. ## Acceptance notes - Started from `main` while PR #34709 (#34465, same area, edits `engine-update.ts`) is still open, on the seat's go-ahead; this PR edits no line of `engine-update.ts`. `git merge-tree --write-tree` of 7aebcc3 against #34709's head `13741cb9` and against #34565's head `779d1aa3`: both exit 0. #34565 then landed and `main` (6091b64) is merged here (65f7837). Against #34709's current head `18f3774a`, `git merge-tree --write-tree` of the final head 76acd4f exits 0. Whichever of #34709 and this PR lands second merges `main` and re-runs the affected pins. - The file surface grew twice in the area's records on the card: one new test file under `packages/rest/src` (the import door end to end), and the forced change to `packages/rest/src/rest-data-blank-typed-value.test.ts`. - The insert half (a person's `POST` with a summary value is kept until the next child write) is NOT outside the card: its Expected covers creates too (seat contract review delta 6949128257, scope note corrected on #34672 as 6949162788). It is deferred, so this PR is `Part of #34672` and the card stays open for the create side. - Update-side answers, written in the changeset and in `content/docs/data-modeling/fields.mdx` by `91202760` (prose only, over the reviewed head `76acd4f2`): an import with `writeMode: 'upsert'` drops a summary value on the rows it updates and keeps it on the rows it creates; a historical import (`treatAsHistorical: true`, writing with `preserveAudit`) keeps the value on update, as it keeps any other read-only value it sends; undoing an ordinary import restores rows through an ordinary update, so a summary value an import committed before this rule is not put back by the undo and stays until the next child write recomputes it. - The strict refusal's per-reason phrase for `readonly` reads "read-only (`readonly: true`)". It already covers `autonumber` without the flag; it now covers `summary` too. Unchanged here: it shows only on a refusal that mixes reasons. ## Verification Final head `8d567553`: a merge of `main` (`46991d0e`, 63 first-parent commits) over `91202760`, with no conflict (`git show --remerge-diff` empty). The PR's delta against `main` is byte-for-byte the delta `91202760` carried (same 7 files, +536 / -8). Records at `91202760`: L1 delta ACCEPT 6948959772, contract review delta PASS 6949128257. The battery, the objectql suite and the PR's pins below ran on `8d567553`. <details><summary>Full dogfood battery</summary> - On `8d567553`, under one `os-verify-lock.sh` hold (`VERDICT command-exit 0`): `pnpm --workspace-concurrency=2 --filter '@objectstack/dogfood^...' build` exit 0, then `pnpm --filter @objectstack/dogfood test` (no shard, no path): `Test Files 479 passed | 3 skipped (482)`, `Tests 4072 passed | 68 skipped (4140)`, exit 0. No failure. - Earlier heads: `65f7837f` gave `Test Files 478 passed | 3 skipped (481)`, `Tests 4055 passed | 68 skipped (4123)`; `a4f80eb9` the same, all green. </details> <details><summary>Local runs</summary> - `pnpm --filter @objectstack/objectql test` on `8d567553` (same lock hold): exit 0, `Test Files 607 passed (607)`, `Tests 13667 passed (13667)`. Earlier, typecheck + suite on `65f7837f`: exit 0, `Tests 13617 passed (13617)`. - `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` on `8d567553`: exit 0, `Test Files 2 passed (2)`, `Tests 10 passed (10)`. - `pnpm check:facade-delegation-only` on `8d567553`: exit 0 (`protocol.ts` 11694 lines, ceiling 11705). `node scripts/pm/overlap-check.mjs` on `8d567553`: `VERDICT clean exit 0` against `main` `46991d0e`, #34817 and #34709. - `pnpm --filter @objectstack/rest exec vitest run --maxWorkers=2 src/rest-data-blank-typed-value.test.ts src/import-summary-update-lock-34672.test.ts src/import-row-dropped-fields-20701.test.ts` on `76acd4f2`: `Test Files 3 passed (3)`, `Tests 20 passed (20)`. - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on `76acd4f2`: 100 derived gate commands, each `:: exit 0`; `--ran` reconciliation: 100 derived famil(ies) accounted for — 100 run, 0 NOT-MEASURED. `check:type-check-debt` first exited 3 (lock queue timeout behind the dogfood run) and re-measured OK after it. The per-command log is kept with the seat. - The full `@objectstack/rest` suite and the other packages: CI Test Core. - CI on `91202760`: every check-run success or skipped (59 runs). - CI on `8d567553` (55 runs): 38 success, 15 skipped, `Test Core (7/10)` failure and the `Test Core` aggregate cancelled. The one failing test is `packages/qa/scenarios/test/skill-evals/skill-evals.test.ts` ("--regrade … a reworded case keeps its record bytes"), `Test timed out in 5000ms` (it took 6810ms). That file landed on `main` today and this PR does not touch `packages/qa/scenarios`; `Test Core (7/10)` is green on `main` `46991d0e`. Lint & Repo Gates, TypeScript Type Check, Build Core, Check Changeset, Dogfood Regression Gate and Governed Surface Queue Guard: success. </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. Taken over by repo:objectstack#3 area o3-J (claim 6948796553 on #34672, seat 2 hand-off 6948320778). --- 🤖 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 90f2b1c commit a825152

7 files changed

Lines changed: 536 additions & 8 deletions

File tree

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql)!: a roll-up `summary` field is read-only on update whether or not it declares `readonly: true`
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 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. -->
11+
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.
13+
14+
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.
15+
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.

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

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,23 @@ 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.
415+
399416
Because the roll-up is engine-derived state rather than a user write, the
400417
recompute runs under a system context: a user who may create a child does not
401418
also need edit access on the parent, and the aggregate is computed over the

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,14 +178,22 @@ describe('engine write doors: a blank on a non-string-typed column reaches the d
178178
});
179179

180180
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+
};
181189
await engine.insert('blank_door', { id: 'u1', ...VALID });
182190
await engine.update('blank_door', { id: 'u1', ...blankTyped(''), ...STR_BLANK });
183191
const byId = last('update');
184-
expectTypedNull(byId);
192+
expectUpdateTypedNull(byId);
185193
expect([byId.c_text, byId.c_lookup, byId.c_select]).toEqual(['', null, null]);
186194

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

191199
it('a valid value on every typed column — falsy ones included — is unchanged', async () => {
Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#34672] A roll-up `summary` field is read-only on UPDATE whether or not the
5+
* author declared `readonly: true`.
6+
*
7+
* The engine computes a roll-up from its child rows and writes it through
8+
* `update()` under an `isSystem` context. Before this card the update's static
9+
* `readonly` strip read only the declared flag, so a person's `PATCH`, an
10+
* import with `writeMode: 'update'` or a predicate update stored the typed
11+
* value, and it was read downstream until the next child write recomputed it.
12+
* Now the update's schema view (`updateStaticReadonlySubject`) reads every
13+
* `summary` field as `readonly: true`. So the write is taken and reported as
14+
* `readonly`, and refused under `strictReadonlyWrites`, exactly as for a
15+
* roll-up the author did declare read-only (the control below).
16+
*
17+
* Kept as before, each pinned here:
18+
* - the roll-up recompute's own write (`isSystem`), and any other `isSystem`
19+
* write of the column;
20+
* - a caller's initial value on INSERT (seed data, a historical import), the
21+
* boundary the `summary` note on `RUNTIME_OWNED_FIELD_TYPES` draws.
22+
*
23+
* The import door, end to end over HTTP and SQLite:
24+
* `packages/rest/src/import-summary-update-lock-34672.test.ts`.
25+
*/
26+
27+
import { describe, it, expect, beforeEach } from 'vitest';
28+
import type { DroppedFieldsEvent } from '@objectstack/spec/data';
29+
import { ObjectQL } from './engine.js';
30+
import { summaryFieldsLockedOnUpdate } from './engine-top-level.js';
31+
import { READONLY_FIELD_REJECTED_CODE } from './readonly-strict-errors.js';
32+
33+
function makeDriver() {
34+
const stores = new Map<string, Map<string, any>>();
35+
const storeFor = (o: string) => {
36+
let s = stores.get(o);
37+
if (!s) { s = new Map(); stores.set(o, s); }
38+
return s;
39+
};
40+
// Flat equality, `$and` and a field's `$in`: the shapes the roll-up
41+
// aggregate and the predicate update below send. Any other operator throws.
42+
const matches = (row: any, where: any): boolean => {
43+
if (!where || typeof where !== 'object') return true;
44+
return Object.entries(where).every(([k, v]) => {
45+
if (k === '$and') return (v as any[]).every((sub) => matches(row, sub));
46+
if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`);
47+
if (v && typeof v === 'object' && !Array.isArray(v)) {
48+
const ops = Object.keys(v);
49+
if (ops.length === 1 && ops[0] === '$in' && Array.isArray((v as any).$in)) return (v as any).$in.includes(row?.[k]);
50+
throw new Error(`fake driver: unsupported condition on ${k}: ${JSON.stringify(v)}`);
51+
}
52+
return row?.[k] === v;
53+
});
54+
};
55+
let n = 0;
56+
const driver: any = {
57+
name: 'memory', version: '0.0.0', supports: {},
58+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
59+
async find(object: string, ast: any) {
60+
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
61+
const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
62+
return page.map((r) => ({ ...r }));
63+
},
64+
async findOne(object: string, ast: any) {
65+
for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r };
66+
return null;
67+
},
68+
async create(object: string, data: Record<string, unknown>) {
69+
n += 1;
70+
const id = (data.id as string) ?? `r_${n}`;
71+
const row = { ...data, id };
72+
storeFor(object).set(id, row);
73+
return { ...row };
74+
},
75+
async update(object: string, id: string, data: Record<string, unknown>) {
76+
const s = storeFor(object);
77+
const row = { ...s.get(id), ...data, id };
78+
s.set(id, row);
79+
return { ...row };
80+
},
81+
async updateMany(object: string, ast: any, data: Record<string, unknown>) {
82+
const s = storeFor(object);
83+
let count = 0;
84+
for (const row of [...s.values()]) {
85+
if (!matches(row, ast?.where)) continue;
86+
s.set(row.id, { ...row, ...data, id: row.id });
87+
count += 1;
88+
}
89+
return count;
90+
},
91+
async delete(object: string, id: string) { return storeFor(object).delete(id); },
92+
async count() { return 0; },
93+
async bulkCreate(object: string, rows: Record<string, unknown>[]) {
94+
return Promise.all(rows.map((r) => this.create(object, r, undefined)));
95+
},
96+
async bulkUpdate() { return []; }, async bulkDelete() {},
97+
async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; },
98+
async commit() {}, async rollback() {},
99+
};
100+
return { driver, storeFor };
101+
}
102+
103+
const silentLogger: any = (() => {
104+
const l: any = { debug() {}, info() {}, error() {}, trace() {}, fatal() {}, warn() {}, child() { return l; } };
105+
return l;
106+
})();
107+
108+
/** A signed-in person: not the system principal. */
109+
const PERSON = { userId: 'u_rep' } as any;
110+
111+
async function rejection(p: Promise<unknown>): Promise<any> {
112+
try {
113+
await p;
114+
} catch (err) {
115+
return err;
116+
}
117+
throw new Error('expected the write to be refused, but it resolved');
118+
}
119+
120+
const ACCOUNT = {
121+
name: 'acct',
122+
fields: {
123+
name: { type: 'text' },
124+
note: { type: 'text' },
125+
// The card's shape: a roll-up with no `readonly`.
126+
order_total: { type: 'summary', summaryOperations: { object: 'ord', field: 'amount', function: 'sum' } },
127+
// The control: the same roll-up, declared read-only by its author.
128+
order_total_ro: { type: 'summary', readonly: true, summaryOperations: { object: 'ord', field: 'amount', function: 'sum' } },
129+
},
130+
};
131+
132+
const ORDER = {
133+
name: 'ord',
134+
fields: {
135+
amount: { type: 'number' },
136+
acct: { type: 'master_detail', reference: 'acct' },
137+
},
138+
};
139+
140+
const ROLL_UP: DroppedFieldsEvent = { object: 'acct', fields: ['order_total'], reason: 'readonly' };
141+
142+
describe('[#34672] a roll-up summary without readonly: true is read-only on update', () => {
143+
let engine: ObjectQL;
144+
let storeFor: ReturnType<typeof makeDriver>['storeFor'];
145+
146+
beforeEach(async () => {
147+
engine = new ObjectQL({ logger: silentLogger });
148+
const d = makeDriver();
149+
storeFor = d.storeFor;
150+
engine.registerDriver(d.driver, true);
151+
await engine.init();
152+
engine.registry.registerObject(ACCOUNT as any);
153+
engine.registry.registerObject(ORDER as any);
154+
const a = await engine.insert('acct', { id: 'a1', name: 'A' }, { context: PERSON } as any);
155+
const b = await engine.insert('acct', { id: 'a2', name: 'B' }, { context: PERSON } as any);
156+
await engine.insert('ord', { acct: a.id, amount: 10 }, { context: PERSON } as any);
157+
await engine.insert('ord', { acct: a.id, amount: 32 }, { context: PERSON } as any);
158+
await engine.insert('ord', { acct: b.id, amount: 5 }, { context: PERSON } as any);
159+
});
160+
161+
const acct = (id: string) => storeFor('acct').get(id);
162+
163+
it('the seeded roll-ups are the engine\'s (the baseline every case reads)', () => {
164+
expect(acct('a1')).toMatchObject({ order_total: 42, order_total_ro: 42 });
165+
expect(acct('a2')).toMatchObject({ order_total: 5, order_total_ro: 5 });
166+
});
167+
168+
it('a by-id update (REST PATCH): the roll-up value is dropped and reported as readonly, the rest is written', async () => {
169+
const events: DroppedFieldsEvent[] = [];
170+
await engine.update(
171+
'acct',
172+
{ id: 'a1', note: 'typed', order_total: 90 },
173+
{ context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any,
174+
);
175+
expect(events).toEqual([ROLL_UP]);
176+
expect(acct('a1')).toMatchObject({ note: 'typed', order_total: 42 });
177+
});
178+
179+
it('a predicate update (multi): the roll-up value is dropped from every matched row and reported once', async () => {
180+
const events: DroppedFieldsEvent[] = [];
181+
await engine.update(
182+
'acct',
183+
{ note: 'bulk', order_total: 2 },
184+
{ where: { id: { $in: ['a1', 'a2'] } }, multi: true, context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any,
185+
);
186+
expect(events).toEqual([ROLL_UP]);
187+
expect(acct('a1')).toMatchObject({ note: 'bulk', order_total: 42 });
188+
expect(acct('a2')).toMatchObject({ note: 'bulk', order_total: 5 });
189+
});
190+
191+
it('under strictReadonlyWrites the update is refused and writes nothing, on both branches', async () => {
192+
const byId = await rejection(engine.update(
193+
'acct', { id: 'a1', note: 'typed', order_total: 90 },
194+
{ context: PERSON, strictReadonlyWrites: true } as any,
195+
));
196+
expect(byId.code).toBe(READONLY_FIELD_REJECTED_CODE);
197+
expect(byId.fields).toEqual(['order_total']);
198+
expect(byId.drops).toEqual([ROLL_UP]);
199+
expect(byId.operation).toBe('update');
200+
201+
const multi = await rejection(engine.update(
202+
'acct', { note: 'bulk', order_total: 2 },
203+
{ where: { id: { $in: ['a1', 'a2'] } }, multi: true, context: PERSON, strictReadonlyWrites: true } as any,
204+
));
205+
expect(multi.code).toBe(READONLY_FIELD_REJECTED_CODE);
206+
expect(multi.fields).toEqual(['order_total']);
207+
208+
expect(acct('a1')).toMatchObject({ order_total: 42 });
209+
expect(acct('a2')).toMatchObject({ order_total: 5 });
210+
expect([acct('a1').note, acct('a2').note]).toEqual([undefined, undefined]);
211+
});
212+
213+
it('the update-mode preview (validate) reports the same drop the write makes', async () => {
214+
const events: DroppedFieldsEvent[] = [];
215+
const preview = await engine.validate(
216+
'acct', { id: 'a1', note: 'typed', order_total: 90 },
217+
{ mode: 'update', context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) },
218+
);
219+
expect(events).toEqual([ROLL_UP]);
220+
expect(preview.results[0]).toMatchObject({ valid: true, droppedFields: [ROLL_UP] });
221+
});
222+
223+
it('the roll-up still recomputes after a refused write: the next child write lands the engine\'s value', async () => {
224+
await engine.update('acct', { id: 'a1', order_total: 90 }, { context: PERSON } as any);
225+
await engine.insert('ord', { acct: 'a1', amount: 8 }, { context: PERSON } as any);
226+
expect(acct('a1')).toMatchObject({ order_total: 50, order_total_ro: 50 });
227+
});
228+
229+
it('an isSystem write of the column is kept, as for a declared readonly column (the recompute\'s exemption)', async () => {
230+
const events: DroppedFieldsEvent[] = [];
231+
await engine.update(
232+
'acct', { id: 'a1', order_total: 7 },
233+
{ context: { isSystem: true }, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any,
234+
);
235+
expect(events).toEqual([]);
236+
expect(acct('a1')).toMatchObject({ order_total: 7 });
237+
});
238+
239+
it('CONTROL: a roll-up declared readonly: true answers the same, and one payload naming both reports both once', async () => {
240+
const events: DroppedFieldsEvent[] = [];
241+
await engine.update(
242+
'acct', { id: 'a1', order_total: 1, order_total_ro: 1 },
243+
{ context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any,
244+
);
245+
expect(events).toEqual([{ object: 'acct', fields: ['order_total', 'order_total_ro'], reason: 'readonly' }]);
246+
expect(acct('a1')).toMatchObject({ order_total: 42, order_total_ro: 42 });
247+
});
248+
249+
it('INSERT is not narrowed: a caller\'s initial value is kept (seed data, a historical import)', async () => {
250+
const events: DroppedFieldsEvent[] = [];
251+
await engine.insert(
252+
'acct', { id: 'a3', name: 'C', order_total: 7 },
253+
{ context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any,
254+
);
255+
expect(events).toEqual([]);
256+
expect(acct('a3')).toMatchObject({ order_total: 7 });
257+
});
258+
});
259+
260+
describe('[#34672] summaryFieldsLockedOnUpdate', () => {
261+
it('names each summary field not declared readonly, and nothing else', () => {
262+
expect(summaryFieldsLockedOnUpdate(ACCOUNT)).toEqual(['order_total']);
263+
expect(summaryFieldsLockedOnUpdate(ORDER)).toEqual([]);
264+
});
265+
266+
it('answers empty for a schema with no field map', () => {
267+
expect(summaryFieldsLockedOnUpdate(undefined)).toEqual([]);
268+
expect(summaryFieldsLockedOnUpdate({ fields: [] })).toEqual([]);
269+
});
270+
});

0 commit comments

Comments
 (0)