diff --git a/.changeset/34672-summary-readonly-on-create.md b/.changeset/34672-summary-readonly-on-create.md new file mode 100644 index 00000000000..22bec7e44f0 --- /dev/null +++ b/.changeset/34672-summary-readonly-on-create.md @@ -0,0 +1,18 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql)!: a roll-up `summary` field is read-only on create too, and a create seeds it as for an empty child list + +Clause-②: no (narrowing) +Metadata-protocol: none + + + +**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. + +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. + +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`). + +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. diff --git a/.changeset/34672-summary-readonly-on-update.md b/.changeset/34672-summary-readonly-on-update.md index c33d0f79e0b..4a8729be2ff 100644 --- a/.changeset/34672-summary-readonly-on-update.md +++ b/.changeset/34672-summary-readonly-on-update.md @@ -9,8 +9,8 @@ Metadata-protocol: none -**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. +**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. 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. -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. +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. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 6a01d5f0505..87c856df478 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -396,22 +396,20 @@ are inserted, updated, or deleted. `relationshipField` is optional when the chil has only one `lookup`/`master_detail` field pointing back to the parent; set it when multiple relationships target the same parent object. -On update a summary field is read-only whether or not it declares `readonly: true`. -A value that a `PATCH`, an import with `writeMode: 'update'` or a bulk update -sends for it is dropped, the rest of the write is stored, and the response's -`droppedFields` names the field with reason `readonly`. Under -`strictReadonlyWrites` the whole update is refused. Server code that runs with -`isSystem: true` can still write the column, as it can any read-only column. -On create, a value you send is kept as the field's starting value (seed data or -a historical import may carry a pre-computed total); the next child write -replaces it with the computed one. -An import with `writeMode: 'upsert'` therefore drops the value on the rows it -updates and keeps it on the rows it creates. A historical import -(`treatAsHistorical: true`, which writes with `preserveAudit`) keeps a summary -value on update as well, as it keeps any other read-only value it sends. Undoing -an ordinary import restores the rows through an ordinary update, so a summary -value that an import committed before this rule overwrote is not put back by -the undo; it stays until the next child write recomputes it. +A summary field is read-only on create and on update whether or not it declares +`readonly: true`. A value that a `POST`, an import (any `writeMode`), an MCP +create, a `PATCH` or a bulk update sends for it is dropped, the rest of the write +is stored, and the response's `droppedFields` names the field with reason +`readonly`. A record created that way starts as if no value had been sent: `0` +for `count` and `sum`, empty for `min`, `max` and `avg`, and the next child write +replaces it with the computed value. Under `strictReadonlyWrites` the whole write +is refused. Server code that runs with `isSystem: true` can still write the +column, as it can any read-only column: seed data, package installs and a +historical import (`treatAsHistorical: true`, which only the system principal may +send) keep a pre-computed total, on create and on update. Undoing an ordinary +import restores the rows through an ordinary update, so a summary value that an +import committed before this rule overwrote is not put back by the undo; it stays +until the next child write recomputes it. Because the roll-up is engine-derived state rather than a user write, the recompute runs under a system context: a user who may create a child does not diff --git a/packages/objectql/src/engine-blank-typed-value-door.test.ts b/packages/objectql/src/engine-blank-typed-value-door.test.ts index c8b4474bba7..a2d34bee414 100644 --- a/packages/objectql/src/engine-blank-typed-value-door.test.ts +++ b/packages/objectql/src/engine-blank-typed-value-door.test.ts @@ -132,8 +132,16 @@ const VALID: Record = { const blankTyped = (v: string) => Object.fromEntries(TYPED.map((t) => [f(t), v])); const STR_BLANK = { c_text: '', c_lookup: '', c_select: '' }; +// [#34672] A `summary` column is read-only on create and on update for an +// ordinary caller: a caller's value for it, a blank included, is dropped +// before the driver, so no write here sends `f_summary` at all (this fixture's +// roll-up declares no `summaryOperations`, so the create seed has nothing to +// fill it with either). Every other typed column still lands null. +const WRITABLE_TYPED = TYPED.filter((t) => t !== 'summary'); + function expectTypedNull(data: Record) { - for (const t of TYPED) expect(data[f(t)], t).toBeNull(); + for (const t of WRITABLE_TYPED) expect(data[f(t)], t).toBeNull(); + expect(data).not.toHaveProperty(f('summary')); } 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 }); it('update by id and update by predicate', async () => { - // [#34672] A `summary` column is read-only on update: a caller's value - // for it, a blank included, is dropped before the driver, so the update - // sends no `f_summary` at all. Every other typed column still lands null. - const updateTyped = TYPED.filter((t) => t !== 'summary'); - const expectUpdateTypedNull = (data: Record) => { - for (const t of updateTyped) expect(data[f(t)], t).toBeNull(); - expect(data).not.toHaveProperty(f('summary')); - }; await engine.insert('blank_door', { id: 'u1', ...VALID }); await engine.update('blank_door', { id: 'u1', ...blankTyped(''), ...STR_BLANK }); const byId = last('update'); - expectUpdateTypedNull(byId); + expectTypedNull(byId); expect([byId.c_text, byId.c_lookup, byId.c_select]).toEqual(['', null, null]); await engine.update('blank_door', blankTyped(''), { where: { id: { $in: ['u1'] } }, multi: true } as any); - expectUpdateTypedNull(last('updateMany')); + expectTypedNull(last('updateMany')); }); - it('a valid value on every typed column — falsy ones included — is unchanged', async () => { + it('a valid value on every typed column — falsy ones included — is unchanged (the roll-up\'s is dropped)', async () => { await engine.insert('blank_door', { id: 'v1', ...VALID }); const sent = last('create'); - for (const [k, v] of Object.entries(VALID)) expect(sent[k], k).toStrictEqual(v); + for (const [k, v] of Object.entries(VALID)) { + if (k === f('summary')) continue; + expect(sent[k], k).toStrictEqual(v); + } + expect(sent).not.toHaveProperty(f('summary')); }); it('required refuses a blank exactly as it refuses null — insert and update', async () => { diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index a682a250645..0b8e11afbba 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -179,13 +179,23 @@ export class InsertFacet { * need it. Scoped to the TAKEN keys: those are the only defaults this pass * keeps, so no other field's default can make it ask, or fail. * + * [#34672] A taken roll-up `summary` is then re-SEEDED, after its default: + * `initializeSummaryFields` over the stripped row, copied back for the + * taken keys only, so the column starts at the empty-child-list value (`0` + * for `count` / `sum`) exactly as a create that never named it does. The + * re-default alone never asked the seed, so a value taken from a + * `readonly: true` roll-up left the column `null` (the #5749 state, which + * the seed exists to rule out) while the write still succeeded. The seed + * yields nothing for `min` / `max` / `avg`, which stay empty as on any + * create. + * * @returns the row as the strip leaves it (the SAME reference when nothing * was taken) and the keys taken, in the row's key order. When the * re-default's permission resolution fails, `error` carries it and `row` * is the row as it arrived: the caller decides whether that fails the * write or culls the row, and the taken keys are still reported. */ - static async staticReadonlyCreateStrip(this: Pick, object: string, readonlySubject: NonNullable>, row: Record, supplied: Readonly>, context: ExecutionContext | undefined, pass: { + static async staticReadonlyCreateStrip(this: Pick, object: string, readonlySubject: NonNullable>, row: Record, supplied: Readonly>, context: ExecutionContext | undefined, pass: { logger: Parameters[3]; strictReadonlyWrites: boolean; hookWrittenKeys: ReadonlySet | undefined; @@ -215,6 +225,10 @@ export class InsertFacet { for (const k of taken) { if (redefaulted[k] !== undefined) stripped[k] = redefaulted[k]; } + const reseeded = this.initializeSummaryFields(object, stripped) as Record; + for (const k of taken) { + if (stripped[k] == null && reseeded[k] !== undefined) stripped[k] = reseeded[k]; + } } return { row: stripped, taken }; } diff --git a/packages/objectql/src/engine-summary-update-lock.test.ts b/packages/objectql/src/engine-summary-update-lock.test.ts index 94a75104c25..2bf4713b5fb 100644 --- a/packages/objectql/src/engine-summary-update-lock.test.ts +++ b/packages/objectql/src/engine-summary-update-lock.test.ts @@ -1,8 +1,8 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * [#34672] A roll-up `summary` field is read-only on UPDATE whether or not the - * author declared `readonly: true`. + * [#34672] A roll-up `summary` field is read-only on UPDATE and on CREATE + * whether or not the author declared `readonly: true`. * * The engine computes a roll-up from its child rows and writes it through * `update()` under an `isSystem` context. Before this card the update's static @@ -14,20 +14,26 @@ * `readonly`, and refused under `strictReadonlyWrites`, exactly as for a * roll-up the author did declare read-only (the control below). * - * Kept as before, each pinned here: - * - the roll-up recompute's own write (`isSystem`), and any other `isSystem` - * write of the column; - * - a caller's initial value on INSERT (seed data, a historical import), the - * boundary the `summary` note on `RUNTIME_OWNED_FIELD_TYPES` draws. + * The create side (second describe) reads the same lock through the insert + * view (`insertStaticReadonlySubject`): a person's or an import's starting + * value is taken, reported as `readonly`, and the column is re-seeded as for an + * empty child list (`staticReadonlyCreateStrip`), so it lands `0` for a `sum`, + * never the typed value and never `null`. The re-seed also fixes the declared + * `readonly: true` roll-up, which used to land `null` on such a create. * - * The import door, end to end over HTTP and SQLite: + * Kept, each pinned here: the roll-up recompute's own write (`isSystem`), and + * any other `isSystem` write of the column, on update and on create (seed + * loads, package installs and historical imports write as the system + * principal). + * + * The REST and import doors, end to end over HTTP and SQLite: * `packages/rest/src/import-summary-update-lock-34672.test.ts`. */ import { describe, it, expect, beforeEach } from 'vitest'; import type { DroppedFieldsEvent } from '@objectstack/spec/data'; import { ObjectQL } from './engine.js'; -import { summaryFieldsLockedOnUpdate } from './engine-top-level.js'; +import { summaryFieldsLockedOnWrite } from './engine-top-level.js'; import { READONLY_FIELD_REJECTED_CODE } from './readonly-strict-errors.js'; function makeDriver() { @@ -246,25 +252,205 @@ describe('[#34672] a roll-up summary without readonly: true is read-only on upda expect(acct('a1')).toMatchObject({ order_total: 42, order_total_ro: 42 }); }); - it('INSERT is not narrowed: a caller\'s initial value is kept (seed data, a historical import)', async () => { + // [#34672, insert half] This case pinned the opposite until the create side + // was narrowed: a person's create kept `order_total: 7`. It now pins the + // narrowed answer; the create side's own cases are in the describe below. + it('INSERT is narrowed too: a person\'s starting value is dropped, reported, and the column seeded 0', async () => { const events: DroppedFieldsEvent[] = []; await engine.insert( 'acct', { id: 'a3', name: 'C', order_total: 7 }, { context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, ); + expect(events).toEqual([ROLL_UP]); + expect(acct('a3')).toMatchObject({ name: 'C', order_total: 0 }); + }); +}); + +describe('[#34672] a roll-up summary is read-only on create: dropped, reported, seeded as for an empty child list', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + let creates: Array>; + + /** A sibling account whose roll-ups have no empty-set value (`max`). */ + const ACCOUNT_MAX = { + name: 'acct_max', + fields: { + name: { type: 'text' }, + biggest: { type: 'summary', summaryOperations: { object: 'ord_max', field: 'amount', function: 'max' } }, + }, + }; + const ORDER_MAX = { + name: 'ord_max', + fields: { amount: { type: 'number' }, acct: { type: 'master_detail', reference: 'acct_max' } }, + }; + const BOTH: DroppedFieldsEvent = { object: 'acct', fields: ['order_total', 'order_total_ro'], reason: 'readonly' }; + + beforeEach(async () => { + engine = new ObjectQL({ logger: silentLogger }); + const d = makeDriver(); + storeFor = d.storeFor; + creates = []; + const create = d.driver.create.bind(d.driver); + d.driver.create = async (object: string, data: Record) => { + if (object === 'acct' || object === 'acct_max') creates.push({ ...data }); + return create(object, data); + }; + engine.registerDriver(d.driver, true); + await engine.init(); + for (const o of [ACCOUNT, ORDER, ACCOUNT_MAX, ORDER_MAX]) engine.registry.registerObject(o as any); + }); + + const acct = (id: string) => storeFor('acct').get(id); + const dropsOf = (events: DroppedFieldsEvent[]) => ({ context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) }) as any; + + it('baseline: a person\'s create that names neither roll-up stores the seed, reports nothing', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.insert('acct', { id: 'a1', name: 'A' }, dropsOf(events)); + expect(events).toEqual([]); + expect(acct('a1')).toMatchObject({ order_total: 0, order_total_ro: 0 }); + }); + + it('a person\'s create (REST POST): both values are dropped and reported, both columns land 0, the rest is stored', async () => { + const events: DroppedFieldsEvent[] = []; + const created = await engine.insert('acct', { id: 'a1', name: 'A', order_total: 90, order_total_ro: 90 }, dropsOf(events)); + expect(events).toEqual([BOTH]); + expect(acct('a1')).toEqual({ id: 'a1', name: 'A', order_total: 0, order_total_ro: 0 }); + expect(created).toMatchObject({ order_total: 0, order_total_ro: 0 }); + }); + + it('the declared readonly: true roll-up alone lands 0, not null (the re-seed after the strip)', async () => { + // Before the re-seed the strip re-ran only `applyFieldDefaults`, so the + // taken value left this column absent (null) while the write succeeded. + const events: DroppedFieldsEvent[] = []; + await engine.insert('acct', { id: 'a1', name: 'A', order_total_ro: 90 }, dropsOf(events)); + expect(events).toEqual([{ object: 'acct', fields: ['order_total_ro'], reason: 'readonly' }]); + expect(creates).toEqual([{ id: 'a1', name: 'A', order_total: 0, order_total_ro: 0 }]); + }); + + it('a blank or null starting value is taken the same way and still lands 0', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.insert('acct', { id: 'a1', name: 'A', order_total: null }, dropsOf(events)); + expect(events).toEqual([ROLL_UP]); + expect(acct('a1')).toMatchObject({ order_total: 0, order_total_ro: 0 }); + }); + + it('a batch create (array): every row\'s value is dropped and seeded, the union reported once', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.insert('acct', [ + { id: 'a1', name: 'A', order_total: 90 }, + { id: 'a2', name: 'B' }, + { id: 'a3', name: 'C', order_total: 2 }, + ], dropsOf(events)); + expect(events).toEqual([ROLL_UP]); + expect(['a1', 'a2', 'a3'].map((id) => acct(id)?.order_total)).toEqual([0, 0, 0]); + }); + + it('insertMany (the import commit): the row that sent a value carries droppedFields, the column lands 0', async () => { + const outcomes = await engine.insertMany('acct', [ + { id: 'a1', name: 'A', order_total: 90 }, + { id: 'a2', name: 'B' }, + ], { context: PERSON } as any); + expect(outcomes.map((o) => o.ok)).toEqual([true, true]); + expect((outcomes[0] as any).droppedFields).toEqual([ROLL_UP]); + expect((outcomes[1] as any).droppedFields ?? []).toEqual([]); + expect([acct('a1')?.order_total, acct('a2')?.order_total]).toEqual([0, 0]); + }); + + it('under strictReadonlyWrites the create is refused and nothing is written', async () => { + const err = await rejection(engine.insert( + 'acct', { id: 'a1', name: 'A', order_total: 90 }, + { context: PERSON, strictReadonlyWrites: true } as any, + )); + expect(err.code).toBe(READONLY_FIELD_REJECTED_CODE); + expect(err.fields).toEqual(['order_total']); + expect(err.drops).toEqual([ROLL_UP]); + expect(err.operation).toBe('insert'); + expect(creates).toEqual([]); + }); + + it('the insert-mode preview (validate) reports the same drop the write makes', async () => { + const events: DroppedFieldsEvent[] = []; + const preview = await engine.validate( + 'acct', { id: 'a1', name: 'A', order_total: 90 }, + { mode: 'insert', context: PERSON, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) }, + ); + expect(events).toEqual([ROLL_UP]); + expect(preview.results[0]).toMatchObject({ valid: true, droppedFields: [ROLL_UP] }); + expect(creates).toEqual([]); + }); + + it('a beforeInsert hook is shown the seed, not the caller\'s value', async () => { + const seen: unknown[] = []; + engine.registerHook('beforeInsert', async (ctx: any) => { + if (ctx.object === 'acct') seen.push(ctx.input.data.order_total); + }); + await engine.insert('acct', { id: 'a1', name: 'A', order_total: 90 }, { context: PERSON } as any); + expect(seen).toEqual([0]); + expect(acct('a1')).toMatchObject({ order_total: 0 }); + }); + + it('children already stored: the create lands the seed (0), not the typed value; the next child write recomputes', async () => { + // Rows naming the parent before it exists (caller-chosen ids, as an + // import keyed on an external id can produce), put straight in the store: + // a child write through the engine would recompute a parent that is not + // there yet. The true sum is 42. + storeFor('ord').set('o1', { id: 'o1', acct: 'a9', amount: 10 }); + storeFor('ord').set('o2', { id: 'o2', acct: 'a9', amount: 32 }); + const events: DroppedFieldsEvent[] = []; + await engine.insert('acct', { id: 'a9', name: 'Z', order_total: 90 }, dropsOf(events)); + expect(events).toEqual([ROLL_UP]); + expect(acct('a9')).toMatchObject({ order_total: 0, order_total_ro: 0 }); + await engine.insert('ord', { acct: 'a9', amount: 8 }, { context: PERSON } as any); + expect(acct('a9')).toMatchObject({ order_total: 50, order_total_ro: 50 }); + }); + + it('an isSystem create keeps its value (seed loads, package installs, historical imports)', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.insert( + 'acct', { id: 'a1', name: 'A', order_total: 90, order_total_ro: 90 }, + { context: { isSystem: true }, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, + ); + expect(events).toEqual([]); + expect(acct('a1')).toMatchObject({ order_total: 90, order_total_ro: 90 }); + }); + + it('preserveAudit on a non-system create is no exemption: dropped and seeded', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.insert( + 'acct', { id: 'a1', name: 'A', order_total: 90 }, + { context: { ...PERSON, preserveAudit: true }, onFieldsDropped: (e: DroppedFieldsEvent) => events.push(e) } as any, + ); + expect(events).toEqual([ROLL_UP]); + expect(acct('a1')).toMatchObject({ order_total: 0 }); + }); + + it('a roll-up with no empty-set value (max) is dropped and stays empty, as on any create', async () => { + const events: DroppedFieldsEvent[] = []; + await engine.insert('acct_max', { id: 'm1', name: 'M', biggest: 77 }, dropsOf(events)); + expect(events).toEqual([{ object: 'acct_max', fields: ['biggest'], reason: 'readonly' }]); + expect(storeFor('acct_max').get('m1')?.biggest ?? null).toBeNull(); + }); + + it('a sys_ object is outside the create lock, as it is outside the insert strip', async () => { + engine.registry.registerObject({ + name: 'sys_tally', + fields: { total: { type: 'summary', summaryOperations: { object: 'ord', field: 'amount', function: 'sum' } } }, + } as any); + const events: DroppedFieldsEvent[] = []; + await engine.insert('sys_tally', { id: 's1', total: 5 }, dropsOf(events)); expect(events).toEqual([]); - expect(acct('a3')).toMatchObject({ order_total: 7 }); + expect(storeFor('sys_tally').get('s1')).toMatchObject({ total: 5 }); }); }); -describe('[#34672] summaryFieldsLockedOnUpdate', () => { +describe('[#34672] summaryFieldsLockedOnWrite', () => { it('names each summary field not declared readonly, and nothing else', () => { - expect(summaryFieldsLockedOnUpdate(ACCOUNT)).toEqual(['order_total']); - expect(summaryFieldsLockedOnUpdate(ORDER)).toEqual([]); + expect(summaryFieldsLockedOnWrite(ACCOUNT)).toEqual(['order_total']); + expect(summaryFieldsLockedOnWrite(ORDER)).toEqual([]); }); it('answers empty for a schema with no field map', () => { - expect(summaryFieldsLockedOnUpdate(undefined)).toEqual([]); - expect(summaryFieldsLockedOnUpdate({ fields: [] })).toEqual([]); + expect(summaryFieldsLockedOnWrite(undefined)).toEqual([]); + expect(summaryFieldsLockedOnWrite({ fields: [] })).toEqual([]); }); }); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 8236d5fdcb1..853f70980a4 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -2241,8 +2241,8 @@ export function undeclaredWriteFieldErrors( * projection and `driver-sql`'s `fieldHasColumn` use. `summary` is NOT here: a * roll-up HAS a column, and a caller-supplied value is persisted (measured on * #20805, SQLite and memory) — a separate question, not this door's. [#34672] - * Its answer is the update's static-`readonly` strip - * ({@link summaryFieldsLockedOnUpdate}), which exempts the `isSystem` write + * Its answer is the static-`readonly` strip on both verbs + * ({@link summaryFieldsLockedOnWrite}), which exempts the `isSystem` write * the roll-up recompute makes; this door, which runs in every context, would * take that write too. * @@ -2432,12 +2432,23 @@ function staticReadonlySparesOrganization(schema: unknown, wallJudgesOrganizatio * ONE function for both passes that read the subject, the pre-hook withhold * and the post-hook strip, so the hook view and the stored row cannot * disagree about the column. [#25062] The write preview's strip reads it too. + * + * [#34672] ...and with every roll-up `summary` field read as `readonly: true` + * ({@link summaryFieldsLockedOnWrite}), as {@link updateStaticReadonlySubject} + * reads it on update: a person's or an import's starting value for a roll-up + * is taken and reported as `readonly`, and the create strip re-seeds the + * column with the empty-child-list value (`staticReadonlyCreateStrip`). The + * flag is added BEFORE {@link staticReadonlyInsertSubject} judges the schema, + * so its exclusions hold for the roll-ups too: a `sys_` object and a + * platform-internal `managedBy` bucket stay outside the subject. `isSystem` + * (seed loads, package installs, historical imports, the recompute) runs none + * of these passes and keeps the value it sends. */ export function insertStaticReadonlySubject( schema: unknown, wallJudgesOrganization: boolean, ): ReturnType { - const subject = staticReadonlyInsertSubject(schema as any); + const subject = staticReadonlyInsertSubject(withSummaryRollUpsReadonly(schema) as any); if (!subject || !staticReadonlySparesOrganization(schema, wallJudgesOrganization)) return subject; const fields = { ...subject.fields }; delete fields[SystemFieldName.ORGANIZATION_ID]; @@ -2461,7 +2472,7 @@ export function insertStaticReadonlySubject( * `update`-mode preview's strip reads it too. * * [#34672] ...and with every roll-up `summary` field read as `readonly: true` - * ({@link summaryFieldsLockedOnUpdate}): the engine owns that value on + * ({@link summaryFieldsLockedOnWrite}): the engine owns that value on * update, so a person's or an import's write to it is taken and reported as * `readonly`, exactly as if the author had declared the flag. The roll-up's * own write is `isSystem` and skips these passes. Because the lock lives in @@ -2469,37 +2480,55 @@ export function insertStaticReadonlySubject( */ export function updateStaticReadonlySubject(schema: unknown, wallJudgesOrganization: boolean): unknown { const sparesOrganization = staticReadonlySparesOrganization(schema, wallJudgesOrganization); - const rollUps = summaryFieldsLockedOnUpdate(schema); - if (!sparesOrganization && rollUps.length === 0) return schema; - const { name, fields } = schema as { name?: string; fields: Record }; + const locked = withSummaryRollUpsReadonly(schema); + if (!sparesOrganization) return locked; + const { name, fields } = locked as { name?: string; fields: Record }; const kept = { ...fields }; - if (sparesOrganization) delete kept[SystemFieldName.ORGANIZATION_ID]; - for (const field of rollUps) kept[field] = { ...(kept[field] as Record), readonly: true }; + delete kept[SystemFieldName.ORGANIZATION_ID]; return { name, fields: kept }; } /** - * [#34672] The roll-up `summary` fields an UPDATE judges read-only although - * the author did not declare `readonly: true`. The engine computes a roll-up - * from its child rows and writes it through `update()` under an `isSystem` - * context (`recomputeSummaries`, the backfill, the enable refresh), which the - * static strip exempts. So the only writes this lock takes are a caller's: - * a REST `PATCH`, an import with `writeMode: 'update'`, a predicate update. - * Before it, such a write was stored and read downstream until the next - * child write recomputed the roll-up. - * - * ⛔ UPDATE only. An insert keeps a caller's initial value: seed data and a - * historical import may carry a pre-computed total, and - * `initializeSummaryFields` seeds only the roll-ups the caller left out. See - * the `summary` note on `RUNTIME_OWNED_FIELD_TYPES` in - * `validation/rule-validator.ts`, which keeps the type out of the - * insert-side runtime-owned strip for that reason. + * [#34672] `schema` with every field {@link summaryFieldsLockedOnWrite} names + * read as `readonly: true`, or `schema` itself when it names none. The one + * spelling of the roll-up lock that both static-`readonly` views read + * ({@link insertStaticReadonlySubject}, {@link updateStaticReadonlySubject}). + * The schema's other members are carried over, so the insert subject's + * `name` and `managedBy` exclusions judge the locked view as they judge the + * registered one. + */ +function withSummaryRollUpsReadonly(schema: unknown): unknown { + const rollUps = summaryFieldsLockedOnWrite(schema); + if (rollUps.length === 0) return schema; + const fields = { ...(schema as { fields: Record }).fields }; + for (const field of rollUps) fields[field] = { ...(fields[field] as Record), readonly: true }; + return { ...(schema as Record), fields }; +} + +/** + * [#34672] The roll-up `summary` fields a person's or an import's write + * judges read-only although the author did not declare `readonly: true`, on + * create and on update alike. The engine computes a roll-up from its child + * rows and writes it through `update()` under an `isSystem` context + * (`recomputeSummaries`, the backfill, the enable refresh), which the static + * strip exempts. So the only writes this lock takes are a caller's: a REST + * `POST` or `PATCH`, an import in any `writeMode`, an MCP create, a + * predicate update. Before it, such a write was stored and read downstream + * until the next child write recomputed the roll-up. + * + * On create the taken value is replaced by the empty-child-list seed + * (`initializeSummaryFields`, re-run by `staticReadonlyCreateStrip`): `0` + * for `count` / `sum`, nothing for `min` / `max` / `avg`. Seed loads, + * package installs and historical imports write as the system principal and + * keep a pre-computed total. The `summary` note on + * `RUNTIME_OWNED_FIELD_TYPES` in `validation/rule-validator.ts` says why the + * type rides this strip and not the runtime-owned one. * * Keyed on `type === 'summary'` literally, like the roll-up readers * (`getSummaryDescriptors`, `summary-enable-refresh.ts`). A field already * declared `readonly: true` is left as it is. */ -export function summaryFieldsLockedOnUpdate(schema: unknown): string[] { +export function summaryFieldsLockedOnWrite(schema: unknown): string[] { const fields = (schema as { fields?: unknown } | null | undefined)?.fields; if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return []; const locked: string[] = []; diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 0a4236c9c05..c32715461d9 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -460,14 +460,25 @@ describe('roll-up summary seeding on the PARENT insert (#5749)', () => { expect(row(p.id).max_estimate ?? null).toBeNull(); }); - it('never overwrites a value the author supplied on insert', async () => { - const p = await engine.insert('project', { name: 'Imported', task_count: 7, total_estimate: 42 }); + // [#34672] These two cases kept an ordinary caller's starting value until the + // create side of the roll-up lock landed. The seed still never overwrites a + // supplied value, but only the system principal (seed loads, package + // installs, historical imports) can still supply one; an ordinary caller's + // is dropped and the seed fills the column. + it('never overwrites a value a system writer supplied on insert (seed data, a historical import)', async () => { + const p = await engine.insert('project', { name: 'Imported', task_count: 7, total_estimate: 42 }, { context: { isSystem: true } } as any); expect(row(p.id).task_count).toBe(7); expect(row(p.id).total_estimate).toBe(42); }); - it('seeds every row of a batch insert, and only the unsupplied ones', async () => { - const written = await engine.insert('project', [{ name: 'P1' }, { name: 'P2', task_count: 3 }]); + it('an ordinary caller\'s value on insert is dropped, and the seed fills the column', async () => { + const p = await engine.insert('project', { name: 'Typed', task_count: 7, total_estimate: 42 }); + expect(row(p.id).task_count).toBe(0); + expect(row(p.id).total_estimate).toBe(0); + }); + + it('seeds every row of a batch insert, and only the unsupplied ones (system writer)', async () => { + const written = await engine.insert('project', [{ name: 'P1' }, { name: 'P2', task_count: 3 }], { context: { isSystem: true } } as any); expect(row(written[0].id).task_count).toBe(0); expect(row(written[0].id).total_estimate).toBe(0); expect(row(written[1].id).task_count).toBe(3); diff --git a/packages/objectql/src/validation/rule-validator.ts b/packages/objectql/src/validation/rule-validator.ts index 15ff561922c..e516aeb18cc 100644 --- a/packages/objectql/src/validation/rule-validator.ts +++ b/packages/objectql/src/validation/rule-validator.ts @@ -1933,26 +1933,36 @@ export function stripReadonlyWhenFieldsMulti( * clauses a naive membership rule would use — persisted AND runtime-issued — * and is STILL excluded. Persistence and runtime ownership do not decide it. * - * What decides it is the third clause: a runtime-owned type must have NO - * legitimate caller-supplied value. `autonumber` qualifies — a client-chosen - * record number bypasses the sequence and forges a business identifier nothing - * later corrects. `summary` does not qualify: the value is a derived cache of - * the child aggregate, self-healing on the next child write, and supplying an - * initial value is a SUPPORTED authoring path — `initializeSummaryFields` - * deliberately keeps a caller-supplied one ("author supplied a value"), so - * historical imports and seed data may carry pre-computed totals. - * - * DO NOT "fix the code to match this comment" by adding `summary` here. The - * insert-side strip ({@link stripRuntimeOwnedFields}) judges against the RAW - * caller payload (its keys AND their values, #6339) and runs in - * `engine.insert` AFTER the seed pass, so a plain - * (non-`isSystem`, non-`preserveAudit`) import of a parent carrying - * `task_count: 42` would lose the 42 to the strip and get no 0 from the seed - * either — the seed already skipped that field precisely BECAUSE the caller - * supplied it. The column lands `null`, the exact state #6013 was written to - * eliminate, and the write still reports success. Only `isSystem: true` (whole - * pass skipped) or `preserveAudit: true` (kept by {@link isPreservableUnderAudit}, - * since a summary field is not `system: true`) would survive it. + * What decides it is HOW a caller's value is taken, not WHETHER it is. + * [#34672] A person's or an import's value for a roll-up IS taken, on create + * and on update: the spec lists `summary` among the computed types that are + * "never client-written" (`COMPUTED_VALUE_TYPES`), and a typed total stood, + * and was read downstream, until the next child write recomputed it. It is + * taken by the static-`readonly` strip, which reads every roll-up as + * `readonly: true` (`summaryFieldsLockedOnWrite` in `engine-top-level.ts`, + * read by both of that strip's schema views), and NOT by this set's strip, + * for two reasons: + * + * - The exemption. {@link stripRuntimeOwnedFields} keeps a value under + * `preserveAudit` as well as `isSystem`. The create-side static strip + * honours `isSystem` alone (the `preserveAudit` ruling below), and that is + * the boundary a roll-up needs: seed loads, package installs and + * historical imports (`treatAsHistorical` is system-only) write as the + * system principal and keep a pre-computed total; an in-process caller + * that merely sets `preserveAudit` does not. + * - The seed. The runtime-owned strip judges the RAW caller payload (#6339) + * and runs AFTER the seed pass, which skipped the field BECAUSE the caller + * supplied it, so taking `task_count: 42` there would land the column + * `null`: the #5749 state #6013 was written to eliminate, behind a write + * that still reports success. The static strip's create pass re-seeds + * every roll-up it takes (`staticReadonlyCreateStrip` in + * `engine-insert.ts`), so the column starts at `0` for `count` / `sum`, + * exactly as a create that never named it. + * + * So DO NOT add `summary` here: that would trade the seed and the boundary + * above for the `null` this note was first written to prevent (#6014). An + * initial value from an ordinary caller is no longer an authoring path; one + * from the system principal still is. * * Keep this set to types whose value is (a) persisted, (b) issued by the * runtime, and (c) never legitimately supplied by a caller. diff --git a/packages/rest/src/import-summary-update-lock-34672.test.ts b/packages/rest/src/import-summary-update-lock-34672.test.ts index 5f247695c07..6545075dddf 100644 --- a/packages/rest/src/import-summary-update-lock-34672.test.ts +++ b/packages/rest/src/import-summary-update-lock-34672.test.ts @@ -14,8 +14,15 @@ * do for the roll-up the author declared read-only (the control), and the * stored value stays the engine's. * + * The create doors (second describe): `POST /api/v1/data/:object`, and the + * import with `writeMode: 'insert'` and with `writeMode: 'upsert'` (the rows it + * creates). Before the create half of this card each stored the typed value + * with no report. Now the value is dropped, reported as `readonly`, and the + * column starts at the empty-child-list seed (`0` for a `sum`), the declared + * `readonly: true` control included, which used to land `null`. + * * The engine's own pins (predicate update, `strictReadonlyWrites`, the - * recompute, `isSystem`, the insert boundary): + * recompute, `isSystem`, the create side): * `packages/objectql/src/engine-summary-update-lock.test.ts`. */ @@ -83,7 +90,8 @@ afterEach(async () => { async function boot() { const engine = new ObjectQL(); liveEngines.push(engine); - engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + engine.registerDriver(driver, true); await engine.init(); engine.registry.registerObject(ACCOUNT as any); engine.registry.registerObject(ORDER as any); @@ -120,7 +128,15 @@ async function boot() { call('POST', '/api/v1/data/:object/import', { format: 'json', rows, dryRun, writeMode: 'update', matchFields: ['id'], }, { object: PARENT }); - return { call, importUpdate, stored }; + const importAs = (writeMode: 'insert' | 'upsert', rows: Array>, dryRun: boolean) => + call('POST', '/api/v1/data/:object/import', { + format: 'json', rows, dryRun, writeMode, ...(writeMode === 'upsert' ? { matchFields: ['id'] } : {}), + }, { object: PARENT }); + const storedRow = async (id: string) => engine.findOne(PARENT, { where: { id } }); + /** The physical row, read past every engine read coercion. */ + const raw = async (id: string) => + (await (driver as any).knex(PARENT).where({ id }).first()) as Record | undefined; + return { call, importUpdate, importAs, stored, storedRow, raw, driver }; } describe('[#34672] a roll-up summary without readonly: true, through the public doors', () => { @@ -155,3 +171,54 @@ describe('[#34672] a roll-up summary without readonly: true, through the public expect(await b.stored()).toMatchObject({ order_total: 42, order_total_ro: 42 }); }); }); + +describe('[#34672] a roll-up summary is read-only on create, through the public doors', () => { + const BOTH = { object: PARENT, fields: ['order_total', 'order_total_ro'], reason: 'readonly' }; + + it('POST create: both roll-up values are dropped and reported; both columns store 0, not the typed value and not null', async () => { + const b = await boot(); + const created = await b.call('POST', '/api/v1/data/:object', { id: 'a2', name: 'B', order_total: 90, order_total_ro: 90 }, { object: PARENT }); + expect(created.status, JSON.stringify(created.body)).toBe(201); + expect(created.body.droppedFields).toEqual([BOTH]); + expect(await b.raw('a2')).toMatchObject({ name: 'B', order_total: 0, order_total_ro: 0 }); + }); + + it('import writeMode insert: the dry run and the commit report the drop on the row, and the commit stores 0', async () => { + const b = await boot(); + const rows = [{ id: 'a2', name: 'B', order_total: 90 }, { id: 'a3', name: 'C' }]; + const dry = await b.importAs('insert', rows, true); + expect(dry.body, JSON.stringify(dry.body)).toMatchObject({ ok: 2, errors: 0 }); + expect(dry.body.results[0]).toMatchObject({ row: 1, ok: true, droppedFields: [ROLL_UP] }); + expect(dry.body.results[1].droppedFields ?? []).toEqual([]); + + const commit = await b.importAs('insert', rows, false); + expect(commit.body, JSON.stringify(commit.body)).toMatchObject({ ok: 2, errors: 0 }); + expect(commit.body.results[0]).toMatchObject({ row: 1, ok: true, droppedFields: [ROLL_UP] }); + expect(await b.raw('a2')).toMatchObject({ name: 'B', order_total: 0, order_total_ro: 0 }); + expect(await b.raw('a3')).toMatchObject({ name: 'C', order_total: 0, order_total_ro: 0 }); + }); + + it('import writeMode upsert: drops the value on the row it updates and on the row it creates; a created row with children already stored lands 0, not the typed value', async () => { + const b = await boot(); + // Two orders already naming `a9`, which does not exist yet (an import keyed + // on an external id can leave them so), put straight in the table: a child + // write through the engine would recompute a parent that is not there. The + // true sum is 50; the create seeds 0, and the next child write recomputes. + await (b.driver as any).knex(CHILD).insert([{ id: 'o8', acct: 'a9', amount: 20 }, { id: 'o9', acct: 'a9', amount: 30 }]); + const commit = await b.importAs('upsert', [ + { id: 'a1', name: 'A4', order_total: 2 }, + { id: 'a9', name: 'Z', order_total: 90 }, + ], false); + expect(commit.body, JSON.stringify(commit.body)).toMatchObject({ ok: 2, errors: 0 }); + expect(commit.body.results).toEqual([ + expect.objectContaining({ row: 1, ok: true, action: 'updated', id: 'a1', droppedFields: [ROLL_UP] }), + expect.objectContaining({ row: 2, ok: true, action: 'created', droppedFields: [ROLL_UP] }), + ]); + expect(await b.raw('a1')).toMatchObject({ name: 'A4', order_total: 42 }); + expect(await b.raw('a9')).toMatchObject({ name: 'Z', order_total: 0, order_total_ro: 0 }); + + const child = await b.call('POST', '/api/v1/data/:object', { id: 'o10', acct: 'a9', amount: 1 }, { object: CHILD }); + expect(child.status, JSON.stringify(child.body)).toBe(201); + expect(await b.raw('a9')).toMatchObject({ order_total: 51, order_total_ro: 51 }); + }); +}); diff --git a/packages/rest/src/rest-data-blank-typed-value.test.ts b/packages/rest/src/rest-data-blank-typed-value.test.ts index 4c38ea2d3e7..5990c26d373 100644 --- a/packages/rest/src/rest-data-blank-typed-value.test.ts +++ b/packages/rest/src/rest-data-blank-typed-value.test.ts @@ -164,7 +164,10 @@ describe('REST write doors on SQLite: a cleared typed column stores null (#20308 let ctx: Awaited>; beforeEach(async () => { ctx = await boot(); }); - const seed = (id: string) => ctx.engine.insert('blank_rest', { id, ...VALID }); + // [#34672] A `summary` column is read-only on create for an ordinary caller, + // so the fixture rows are written as the system principal (a seed load): + // that is the writer that may still set the roll-up's `f_summary: 7`. + const seed = (id: string) => ctx.engine.insert('blank_rest', { id, ...VALID }, { context: { isSystem: true } } as any); it('POST create: the typed blanks store null; a text blank stores "", a lookup / select blank null (#29277)', async () => { const res = await ctx.call('POST', '/api/v1/data/:object', { object: 'blank_rest' }, { id: 'c1', ...blankTyped(), ...STR_BLANK }); @@ -209,11 +212,18 @@ describe('REST write doors on SQLite: a cleared typed column stores null (#20308 expectUpdatedTypedNull(await ctx.stored('blank_rest', 'm2'), 'updateMany'); }); - it('a valid value on every typed column is stored and read back unchanged', async () => { + it('a valid value on every typed column is stored and read back unchanged; the roll-up\'s is dropped (#34672)', async () => { const res = await ctx.call('POST', '/api/v1/data/:object', { object: 'blank_rest' }, { id: 'v1', ...VALID }); expect(res.status).toBe(201); + // [#34672] A person's create no longer sets a `summary` column: the value + // is dropped and reported, and this fixture's roll-up (no + // `summaryOperations`, so no seed) stays null. + expect(res.body.droppedFields).toEqual([{ object: 'blank_rest', fields: ['f_summary'], reason: 'readonly' }]); const read = await ctx.engine.findOne('blank_rest', { where: { id: 'v1' } }) as Record; - for (const [k, v] of Object.entries(VALID)) expect(read[k], k).toStrictEqual(v); + for (const [k, v] of Object.entries(VALID)) { + if (k === 'f_summary') expect(read[k] ?? null, k).toBeNull(); + else expect(read[k], k).toStrictEqual(v); + } }); it('a required field refuses a blank: 400 VALIDATION_FAILED / required, nothing stored', async () => {