Skip to content

Commit 3b3cd84

Browse files
committed
fix(objectql): count a filter's { $field } referents as fields a patch can move, and keep the preview's batch overlay on the header columns the caller was served
summaryPatchCanMove now reads a { $field } comparand and an addDays offset as fields of the filter, so a predicate update writing only a comparand still folds the roll-up. The multi-row insert preview moves and computes the batch's roll-ups onto the master-detail header columns the read door served the caller only. fields.mdx and the 34821 note follow both doors. Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6169c1e commit 3b3cd84

8 files changed

Lines changed: 228 additions & 27 deletions

File tree

‎.changeset/34821-rollup-fold-followups.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,12 @@ Metadata-protocol: none
1212
**BREAKING** for a multi-row insert (`insert(object, rows)`, an import batch, `insertMany`) of a child object whose validation rule, or field-level `requiredWhen` on `parent`, reads a `formula` or stored computed field of the parent calculated from a roll-up `summary` (`record.bud.remaining`, `remaining = budget - total`).
1313

1414
- FROM: the batch moved the parent roll-up itself by the rows admitted before each row, but a parent field calculated from it kept its stored value: "a line may not exceed the remaining budget" (`record.amount > record.bud.remaining`) refused the third line of 40 against a budget of 100 written one by one, and admitted all three written in one call.
15-
- TO: the field is computed again over the moved roll-ups, as a predicate update already computes it, carrying the parent's stored image from row to row as each one-by-one recompute stores it. The batch is refused with `VALIDATION_FAILED` and writes nothing, as for any refused row; the insert preview (`validate` with `mode: 'insert'`) answers the same row invalid. Only a batch with a rule reading that parent pays one read of its parent rows.
15+
- TO: the field is computed again over the moved roll-ups, as a predicate update already computes it, carrying the parent's stored image from row to row as each one-by-one recompute stores it. The batch is refused with `VALIDATION_FAILED` and writes nothing, as for any refused row; the insert preview (`validate` with `mode: 'insert'`) answers the same row invalid, and judges a master-detail header column the caller is not served as empty at every row. Only a batch with a rule reading that parent pays one read of its parent rows.
16+
- The answer moves both ways. Mostly it narrows: a row main admitted against the stored calculated value is refused when the rows before it move that value over the rule's line. It also admits a row main refused when the rows before it move the value back under the line, as one by one does.
17+
- A calculated field that also reads a roll-up the insert does not move (an `avg`, a filter through a reference, or one left stored from the row where it meets a value that is not a number) is computed over the moved and the stored values as they stand.
1618

1719
The insert accumulation also leaves out a roll-up whose `filter` reads a related record in the nested form (`{ account: { status: 'x' } }`), as it already left out the dotted form and as the predicate update leaves out both.
1820

19-
A predicate update (`multi: true`) whose patch writes no foreign key, source field or filter field of a roll-up its rules read no longer aggregates a base for it: its rules read the stored value, as the by-id update does, with no aggregate read. Each roll-up a predicate update leaves unfolded now logs one debug line naming the object, parent, field and reason (`filter`, `not_a_number`, `exclusion_budget`).
21+
A predicate update (`multi: true`) whose patch writes no foreign key, source field or field the filter reads (as a key, or as a `{ $field }` comparand or `addDays` offset) of a roll-up its rules read no longer aggregates a base for it: its rules read the stored value, as the by-id update does, with no aggregate read. So the 34465 note's "one grouped aggregate per summary a rule reads" and its three stored-value cases hold for the roll-ups the patch can move; one it cannot move is neither aggregated nor folded. Each roll-up a predicate update leaves unfolded now logs one debug line naming the object, parent, field and reason (`filter`, `not_a_number`, `exclusion_budget`).
2022

2123
The fix for a caller: insert the rows the rule refuses on their own, or split the batch so each part fits the rule.

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

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -463,10 +463,19 @@ refuse is not counted. A detail object's `requiredWhen` that reads the summary
463463
on `parent` (the master-detail header, for example
464464
`requiredWhen: 'parent.line_count >= 2'`) reads it the same way, so the third
465465
of three bare lines in one batch is refused as the third single insert is.
466+
A rule that reads a formula or a stored computed field of the parent calculated
467+
from the summary (`record.budget.remaining`, `parent.headroom < 50`) reads it
468+
calculated over the summary as the earlier rows moved it, so a row is refused,
469+
or admitted, as the same row inserted on its own after them would be.
466470
This holds for `count`, and for `sum`, `min` and `max`
467471
over number values. An `avg` summary, a `sum`/`min`/`max` meeting a value that
468-
is not a number, and a summary whose `filter` reads a dotted path through
469-
another reference keep reading the stored value, as they did before.
472+
is not a number, and a summary whose `filter` reads through another reference,
473+
as a dotted path or in the nested form `{ account: { status: 'x' } }`, keep
474+
reading the stored value, as they did before; a field calculated from one of
475+
them and from a summary that moves reads the first as stored. A preview of the
476+
batch (`validate` in insert mode) judges each row the same way, except that a
477+
column of the master-detail header the caller is not served reads as empty at
478+
every row.
470479
An import's **dry run** previews its create rows in the batches the import
471480
writes them in (200 rows each) and refuses the rows the import refuses, with
472481
the same message. It writes nothing, so a row in a later batch reads the
@@ -500,8 +509,11 @@ reference, a detail object's `requiredWhen` reading it on `parent`, and a rule
500509
reading a formula or stored computed field of the parent calculated from it,
501510
read it as the matched rows judged before leave it, for every summary function,
502511
`avg` included, and a row that moves to another parent leaves the old one and
503-
joins the new one. If any row is refused, none is written. Three cases keep
504-
reading the stored value for every parent the update reads that summary for: a
512+
joins the new one. If any row is refused, none is written. Four cases keep
513+
reading the stored value for every parent the update reads that summary for,
514+
as a by-id update reads it: a summary the patch cannot move (it writes neither
515+
the reference to the parent, nor the summed field, nor a field the summary's
516+
`filter` reads, as a key or as a `{ $field }` comparand), a
505517
summary whose `filter` reads through another reference, as a dotted path or in
506518
the nested form `{ account: { status: 'x' } }` (or one the in-memory filter
507519
cannot evaluate), a summary meeting a value that is not a number, and a `min` / `max`

‎packages/objectql/src/engine-master-detail-related.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,9 @@ export async function settleMasterDetailLanding<H>(
289289
* is judged as empty: the header is materialised over the master's declared
290290
* fields after the columns are kept, so such a column reads `null`. So the
291291
* verdict never depends on a header value the caller could not have read in
292-
* full.
292+
* full. [#34821] `servedColumns[i]` names the columns kept for `parents[i]`:
293+
* a multi-row preview moves and computes the batch's roll-ups onto those
294+
* only, so a withheld column reads `null` at every row.
293295
*/
294296
export async function resolvePreviewParents(
295297
this: Pick<MasterDetailRelatedHost, 'find' | 'logger' | 'resolveMasterDetailParents' | 'materializeParentHeader'>,
@@ -300,6 +302,7 @@ export async function resolvePreviewParents(
300302
): Promise<{
301303
parents: Array<Record<string, unknown> | null>;
302304
previousParents: Array<Record<string, unknown> | null | undefined>;
305+
servedColumns: Array<ReadonlySet<string> | null>;
303306
}> {
304307
const rel = resolveMasterDetailRelation(schema as any);
305308
const landingIds = views.map((view) => (rel ? masterIdOf(rel.fk, null, view) : undefined));
@@ -318,6 +321,8 @@ export async function resolvePreviewParents(
318321
priorIds.forEach((id, i) => { if (repoints[i]) ids.add(String(id)); });
319322

320323
const headers = new Map<string, Record<string, unknown>>();
324+
/** [#34821] Header id → the columns kept: what a batch overlay may move or compute onto. */
325+
const keptColumns = new Map<string, ReadonlySet<string>>();
321326
// [#24358] ⛔ A stored-metadata-body header is never read here either, as
322327
// the write's own header read never reads one: every header binds unbound.
323328
if (rel && ids.size > 0 && !isStoredMetadataBodyObject(rel.master)) {
@@ -351,13 +356,15 @@ export async function resolvePreviewParents(
351356
}
352357
}
353358
headers.set(id, this.materializeParentHeader(rel.master, kept));
359+
keptColumns.set(id, new Set(Object.keys(kept)));
354360
}
355361
}
356362
}
357363
const headerOf = (id: string | number | undefined) => (id == null ? null : (headers.get(String(id)) ?? null));
358364
return {
359365
parents: landingIds.map(headerOf),
360366
previousParents: priorIds.map((id, i) => (priorUnknown[i] ? null : repoints[i] ? headerOf(id) : undefined)),
367+
servedColumns: landingIds.map((id) => (id == null ? null : (keptColumns.get(String(id)) ?? null))),
361368
};
362369
}
363370

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,8 @@ export async function validate(
651651
// [#22474] The header the write binds: the insert's
652652
// `insertParentForRow`, the update's landing header and, for a
653653
// repoint, `roWhenPreviousParent`.
654-
parent: previewParentMaster ? batchSummaries!.overlayRow(previewParentMaster, previewParents?.parents[i]) : previewParents?.parents[i],
654+
// [#34821] Onto the columns the caller was served only (`servedColumns`).
655+
parent: previewParentMaster ? batchSummaries!.overlayRow(previewParentMaster, previewParents?.parents[i], previewParents?.servedColumns[i] ?? new Set()) : previewParents?.parents[i],
655656
previousParent: previewParents?.previousParents[i],
656657
related: batchSummaries ? batchSummaries.overlay(previewRelatedForRow(judgedViews[i])) : previewRelatedForRow(judgedViews[i]),
657658
permissions: previewPermissionsFor(row),

‎packages/objectql/src/engine.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2799,7 +2799,7 @@ export class ObjectQL implements IObjectQLEngine {
27992799
context: ExecutionContext | undefined,
28002800
): Promise<{
28012801
parents: Array<Record<string, unknown> | null>;
2802-
previousParents: Array<Record<string, unknown> | null | undefined>;
2802+
previousParents: Array<Record<string, unknown> | null | undefined>; servedColumns: Array<ReadonlySet<string> | null>;
28032803
}> {
28042804
// [#25522 cut 14] The body moved to `engine-master-detail-related.ts`, its docblock with it (see `MasterDetailRelatedHost`).
28052805
const readLogger = () => this.logger;

‎packages/objectql/src/summary-batch-accumulation.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,20 @@ describe('[#34821] summaryPatchCanMove — a roll-up a predicate update\'s patch
405405
it('a filter holding a condition whose fields it cannot read is taken to move', () => {
406406
expect(summaryPatchCanMove(desc({ fn: 'count', filter: { $expr: { $gt: ['$amount', 1] } } }), { kind: 'b' })).toBe(true);
407407
});
408+
409+
it('moves when the patch writes a field the filter reads as a { $field } comparand or an addDays offset, and not otherwise', () => {
410+
const late = desc({ fn: 'count', summaryField: 'n', filter: { closed_day: { $gt: { $field: 'due_day' } } } });
411+
expect(summaryPatchCanMove(late, { due_day: 1 })).toBe(true);
412+
expect(summaryPatchCanMove(late, { closed_day: 1 })).toBe(true);
413+
const shifted = desc({ fn: 'count', summaryField: 'n', filter: { $or: [{ closed_on: { $lt: { $field: 'due_on', addDays: { $field: 'grace' } } } }] } });
414+
expect(summaryPatchCanMove(shifted, { grace: 2 })).toBe(true);
415+
expect(summaryPatchCanMove(shifted, { due_on: '2026-01-01' })).toBe(true);
416+
// CONTROL: a patch writing none of the filter's fields, as key or as referent.
417+
expect(summaryPatchCanMove(late, { other: 1 })).toBe(false);
418+
expect(summaryPatchCanMove(shifted, { other: 1 })).toBe(false);
419+
// A referent naming no field by a string is a condition this cannot read.
420+
expect(summaryPatchCanMove(desc({ fn: 'count', filter: { closed_day: { $gt: { $field: 7 } } } }), { other: 1 })).toBe(true);
421+
});
408422
});
409423

410424
describe('[#34821] each stand-down of a predicate update\'s fold is reported once, naming the roll-up and why', () => {

‎packages/objectql/src/summary-batch-accumulation.ts‎

Lines changed: 47 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -92,8 +92,15 @@ export interface BatchSummaryAccumulator {
9292
* row and not as a related binding. A copy; `row` itself is never mutated.
9393
* A row no admitted row moves, and an unbound header (`null` /
9494
* `undefined`, the fail-closed signal), are returned as they are.
95+
*
96+
* [#34821] `visible`, when given, names the only columns of `row` the
97+
* reader was served (the insert preview's caller-visible header): no other
98+
* column is moved or computed onto the copy, so it reads as served — the
99+
* same at every row — and decides nothing it did not decide at the first.
100+
* A roll-up the reader was not served is still moved, from the stored
101+
* parent, for the visible fields calculated from it.
95102
*/
96-
overlayRow<R extends Record<string, unknown> | null | undefined>(object: string, row: R): R;
103+
overlayRow<R extends Record<string, unknown> | null | undefined>(object: string, row: R, visible?: ReadonlySet<string>): R;
97104
/** Count `row` in. Call it only once the row's rules have admitted it. */
98105
accept(row: Record<string, unknown>): void;
99106
/**
@@ -248,18 +255,19 @@ export function createBatchSummaryAccumulator(
248255
/**
249256
* The summary values the admitted rows move parent `parentId` (a row of
250257
* `object`) to, or `undefined` when none moves. Each is moved from the value
251-
* `row` carries, or, for a roll-up `row` was not handed (and for no row),
252-
* from the stored parent the dependents read: both are read before the
253-
* batch writes anything.
258+
* `row` carries, or, for a roll-up `row` was not handed or not served
259+
* (`visible`), and for no row, from the stored parent the dependents read:
260+
* both are read before the batch writes anything.
254261
*/
255-
const movedOf = (object: string, parentId: string, row?: Record<string, unknown>): Record<string, number> | undefined => {
262+
const movedOf = (object: string, parentId: string, row?: Record<string, unknown>, visible?: ReadonlySet<string>): Record<string, number> | undefined => {
256263
const stored = dependents?.stored?.(object, parentId);
257264
let out: Record<string, number> | undefined;
258265
for (const [desc, byParent] of deltas) {
259266
if (dropped.has(desc) || desc.parentObject !== object) continue;
260267
const delta = byParent.get(parentId);
261268
if (!delta) continue;
262-
const from = row && desc.summaryField in row ? row : stored && desc.summaryField in stored ? stored : undefined;
269+
const carried = row !== undefined && desc.summaryField in row && (!visible || visible.has(desc.summaryField));
270+
const from = carried ? row : stored && desc.summaryField in stored ? stored : undefined;
263271
if (!from) continue;
264272
const value = moved(desc, from[desc.summaryField], delta);
265273
if (value === undefined) continue;
@@ -269,14 +277,16 @@ export function createBatchSummaryAccumulator(
269277
};
270278

271279
/** A copy of `row` (a stored row of `object`) with every summary the admitted rows move, or `undefined` when none moves. */
272-
const patchRow = (object: string, row: Record<string, unknown>): Record<string, unknown> | undefined => {
280+
const patchRow = (object: string, row: Record<string, unknown>, visible?: ReadonlySet<string>): Record<string, unknown> | undefined => {
273281
const parentId = singleId(row.id);
274282
if (parentId === undefined) return undefined;
275-
const values = movedOf(object, parentId, row);
283+
const values = movedOf(object, parentId, row, visible);
276284
if (!values) return undefined;
285+
/** A column the reader was handed, and (with `visible`) served. */
286+
const served = (field: string): boolean => field in row && (!visible || visible.has(field));
277287
let patched: Record<string, unknown> | undefined;
278288
for (const [field, value] of Object.entries(values)) {
279-
if (!(field in row)) continue; // the reader was not handed this roll-up
289+
if (!served(field)) continue; // the reader was not handed this roll-up
280290
patched ??= { ...row };
281291
patched[field] = value;
282292
}
@@ -286,7 +296,7 @@ export function createBatchSummaryAccumulator(
286296
const computed = dependents?.(object, parentId, values);
287297
if (computed) {
288298
for (const [field, value] of Object.entries(computed)) {
289-
if (!(field in row)) continue;
299+
if (!served(field)) continue;
290300
patched ??= { ...row };
291301
patched[field] = value;
292302
}
@@ -309,9 +319,9 @@ export function createBatchSummaryAccumulator(
309319
return out ?? binding;
310320
};
311321

312-
const overlayRow = <R extends Record<string, unknown> | null | undefined>(object: string, row: R): R => {
322+
const overlayRow = <R extends Record<string, unknown> | null | undefined>(object: string, row: R, visible?: ReadonlySet<string>): R => {
313323
if (!row || deltas.size === 0) return row;
314-
return (patchRow(object, row) as R | undefined) ?? row;
324+
return (patchRow(object, row, visible) as R | undefined) ?? row;
315325
};
316326

317327
const foldedSummaries = (rows: readonly unknown[], objects: ReadonlySet<string>): Map<string, { fields: Set<string>; parentIds: Set<string> }> => {
@@ -389,7 +399,27 @@ export type SummaryFoldStandDown = 'filter' | 'not_a_number' | 'exclusion_budget
389399
/** [#34821] Told once per roll-up a fold stands down, with why: the trace that makes the published limit observable. */
390400
export type SummaryFoldStandDownSink = (desc: SummaryDescriptor, reason: SummaryFoldStandDown) => void;
391401

392-
/** The fields a filter names, or `undefined` when it holds a condition this cannot read the fields of. */
402+
/**
403+
* [#34821] Add to `into` every field a condition's value reads as a
404+
* `{ $field }` comparand, an `addDays: { $field }` offset included (the
405+
* fold's walker resolves both against the row); `false` when one names no
406+
* field by a string.
407+
*/
408+
function addFieldReferents(value: unknown, into: Set<string>): boolean {
409+
if (Array.isArray(value)) return value.every((v) => addFieldReferents(v, into));
410+
if (!value || typeof value !== 'object' || value instanceof Date) return true;
411+
for (const [key, inner] of Object.entries(value as Record<string, unknown>)) {
412+
if (key === '$field') {
413+
if (typeof inner !== 'string' || inner === '') return false;
414+
into.add(inner.split('.')[0]!);
415+
continue;
416+
}
417+
if (!addFieldReferents(inner, into)) return false;
418+
}
419+
return true;
420+
}
421+
422+
/** The fields a filter names, as keys or as `{ $field }` referents, or `undefined` when it holds a condition this cannot read the fields of. */
393423
function filterFieldNames(cond: unknown, into: Set<string>): Set<string> | undefined {
394424
if (Array.isArray(cond)) {
395425
for (const c of cond) if (!filterFieldNames(c, into)) return undefined;
@@ -403,14 +433,16 @@ function filterFieldNames(cond: unknown, into: Set<string>): Set<string> | undef
403433
}
404434
if (key.startsWith('$')) return undefined;
405435
into.add(key.split('.')[0]!);
436+
if (!addFieldReferents(value, into)) return undefined;
406437
}
407438
return into;
408439
}
409440

410441
/**
411442
* [#34821] Whether a patch can move roll-up `desc` at all: it writes the
412-
* foreign key, the source field (not a `count`'s) or a field the filter names (or a filter
413-
* this cannot read the fields of). A patch that cannot leaves every matched
443+
* foreign key, the source field (not a `count`'s) or a field the filter names
444+
* (as a key, or as a `{ $field }` comparand or `addDays` offset), or holds a
445+
* filter this cannot read the fields of. A patch that cannot leaves every matched
414446
* row's contribution where it stands, so the roll-up is not folded and its
415447
* rules read the stored value, as the by-id update reads it, at no cost: a
416448
* base aggregated from the children differs from the stored value only where

0 commit comments

Comments
 (0)