Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .changeset/34672-summary-readonly-on-create.md
Original file line number Diff line number Diff line change
@@ -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

<!-- 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. -->

**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.
4 changes: 2 additions & 2 deletions .changeset/34672-summary-readonly-on-update.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
---
'@objectstack/objectql': patch
---
Expand All @@ -9,8 +9,8 @@

<!-- 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. -->

**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.
30 changes: 14 additions & 16 deletions content/docs/data-modeling/fields.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 17 additions & 13 deletions packages/objectql/src/engine-blank-typed-value-door.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,16 @@ const VALID: Record<string, unknown> = {
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<string, unknown>) {
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)', () => {
Expand Down Expand Up @@ -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<string, unknown>) => {
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 () => {
Expand Down
16 changes: 15 additions & 1 deletion packages/objectql/src/engine-insert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<InsertHost, 'applyFieldDefaults' | 'resolveDefaultPermissions'>, object: string, readonlySubject: NonNullable<ReturnType<typeof staticReadonlyInsertSubject>>, row: Record<string, unknown>, supplied: Readonly<Record<string, unknown>>, context: ExecutionContext | undefined, pass: {
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: {
logger: Parameters<typeof stripReadonlyFields>[3];
strictReadonlyWrites: boolean;
hookWrittenKeys: ReadonlySet<string> | undefined;
Expand Down Expand Up @@ -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<string, unknown>;
for (const k of taken) {
if (stripped[k] == null && reseeded[k] !== undefined) stripped[k] = reseeded[k];
}
}
return { row: stripped, taken };
}
Expand Down
Loading
Loading