Skip to content

Commit d19c04b

Browse files
committed
fix(objectql): the predicate update's fold carries one image per parent through the stored pass
L2 delta S4: the fold computed the parent's stored computed fields from the row as stored before the update at every matched row, while one by one each recompute's write starts from the row the previous recompute stored. A stored field reading its own stored value (a high-water mark) or three stored fields chained against declaration order then diverged from the third row on. After each judged row the fold now tells the dependents every parent that row names (advance), which writes that parent's image again from the previous image, and the next row reads that image. Pinned over three rows against the one-by-one reference: a high-water mark and a three-field chain against declaration order, plus a fold unit pin for the parents advanced. N7: an empty object beneath a field is the nested form too (isNoOperatorObject), as the engine reads it. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WGufzfr1xZSFZzCR8HnqXX
1 parent c14d8dd commit d19c04b

4 files changed

Lines changed: 142 additions & 13 deletions

File tree

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

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2394,6 +2394,13 @@ export class UpdateFacet {
23942394
* computed it: a planned formula reading one (`room = ceiling - total`,
23952395
* `ceiling = budget + extra`) reads it as the by-id rule's read does.
23962396
*
2397+
* The stored pass carries one image per parent through the update, as one by
2398+
* one does: after each matched row is judged, the parents it names are
2399+
* written again (`advance`), from the row the previous write stored, and the
2400+
* next row reads that row. A stored computed field reading its own stored
2401+
* value (a high-water mark) or a chain of them declared against their reading
2402+
* order then holds what one by one holds at every row, not only the second.
2403+
*
23972404
* Each pass runs synchronously, with the read path's own evaluator
23982405
* ({@link applyFormulaPlan}). An object no such field reads a folded roll-up
23992406
* of reads nothing.
@@ -2447,22 +2454,41 @@ async function loadSummaryFoldDependents(
24472454
formulaLabels: host.formulaOptionLabels(schema, formulaPlan, systemCtx),
24482455
});
24492456
}
2450-
return (object, parentId, moved) => {
2451-
const entry = served.get(object);
2452-
const stored = entry?.rows.get(parentId);
2453-
if (!entry || !stored) return undefined;
2454-
// The write's image: the stored row, no formula on it, the folded roll-ups in place.
2455-
const scratch: Record<string, unknown> = { ...stored, ...moved };
2457+
type Served = NonNullable<ReturnType<typeof served.get>>;
2458+
/** What the recompute's write stores from `from` with the folded roll-ups `moved`: no formula on it, the stored fields computed. */
2459+
const written = (entry: Served, from: Record<string, unknown>, moved: Readonly<Record<string, number | null>>): Record<string, unknown> => {
2460+
const scratch: Record<string, unknown> = { ...from, ...moved };
24562461
for (const name of entry.formulaFields) delete scratch[name];
24572462
// Twice, as the write computes them: before its hooks, then over the row with the moved values.
24582463
for (let pass = 0; pass < 2 && entry.storedPlan.length > 0; pass += 1) {
24592464
applyFormulaPlan(entry.storedPlan, [scratch], systemCtx, entry.permissions, undefined, entry.related, entry.storedLabels);
24602465
}
2466+
return scratch;
2467+
};
2468+
/** Parent (`object|id`) → the row the last recompute the fold carried for it stored. */
2469+
const images = new Map<string, Record<string, unknown>>();
2470+
const dependents = ((object, parentId, moved) => {
2471+
const entry = served.get(object);
2472+
const stored = entry?.rows.get(parentId);
2473+
if (!entry || !stored) return undefined;
2474+
// The row the rule reads: the one the previous row's recompute stored, or, before any, the
2475+
// write's image over the stored row.
2476+
const image = images.get(`${object}|${parentId}`);
2477+
const scratch = image ? { ...image, ...moved } : written(entry, stored, moved);
24612478
// The read's row: the formulas the plan does not recompute back at their stored values.
24622479
for (const name of entry.unplannedFormulas) if (name in stored) scratch[name] = stored[name];
24632480
if (entry.formulaPlan.length > 0) applyFormulaPlan(entry.formulaPlan, [scratch], systemCtx, entry.permissions, undefined, entry.related, entry.formulaLabels);
24642481
const values: Record<string, unknown> = {};
24652482
for (const step of [...entry.storedPlan, ...entry.formulaPlan]) values[step.name] = scratch[step.name];
24662483
return values;
2484+
}) as SummaryDependents;
2485+
// After each matched row, the recompute writes the parents it names: the next write starts from that row.
2486+
dependents.advance = (object, parentId, moved) => {
2487+
const entry = served.get(object);
2488+
const stored = entry?.rows.get(parentId);
2489+
if (!entry || !stored || entry.storedPlan.length === 0) return;
2490+
const key = `${object}|${parentId}`;
2491+
images.set(key, written(entry, images.get(key) ?? stored, moved));
24672492
};
2493+
return dependents;
24682494
}

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,25 @@ describe('[#34465] the fold hands the folded roll-ups to what computes the paren
248248
expect(binding.order!.row).toEqual({ id: 'o1', remaining: 20 });
249249
expect(asked).toEqual([['xt_order', 'o1', { total: 80 }], ['xt_order', 'o1', { total: 110 }]]);
250250
});
251+
252+
it('tells the dependents, after each judged row, every parent that row names (as stored and as left) with the roll-ups it leaves', () => {
253+
const sum = desc({});
254+
const matched: MatchedRowStates[] = [
255+
{ previous: { id: 'a', order: 'o1', amount: 40 }, next: { id: 'a', order: 'o2', amount: 40 } },
256+
{ previous: { id: 'b', order: 'o1', amount: 40 }, next: { id: 'b', order: 'o1', amount: 70 } },
257+
];
258+
const base = (s: number) => ({ count: 0, sum: s, nonNull: 0, min: null, max: null });
259+
const fold = createPredicateUpdateSummaryFold(new Map([[sum, new Map([['o1', base(80)], ['o2', base(0)]])]]), matched, CHILD_FIELDS)!;
260+
const advanced: unknown[] = [];
261+
const dependents = Object.assign(() => undefined, { advance: (object: string, parentId: string, moved: Readonly<Record<string, number | null>>) => { advanced.push([object, parentId, { ...moved }]); } });
262+
fold.setDependents(dependents);
263+
fold.advance(0);
264+
fold.advance(1);
265+
expect(advanced).toEqual([
266+
['xt_order', 'o1', { total: 40 }], ['xt_order', 'o2', { total: 40 }],
267+
['xt_order', 'o1', { total: 70 }],
268+
]);
269+
});
251270
});
252271

253272
describe('[#34465] loadPredicateUpdateSummaryBases — the base a predicate update folds over', () => {

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

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ import { SUMMARY_GROUPED_AGGREGATE_CHUNK, summaryEmptySetValue } from './summary
5858
import { ROLLUP_AGGREGATE_OPTION } from './record-currency-aggregate-door.js';
5959
import { declaredFieldClasses, declaredJsonStoredFields, matchesAggregationFilter } from './having-filter.js';
6060
import type { RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js';
61+
import { isNoOperatorObject } from './no-operator-object-door.js';
6162

6263
/** One parent's delta from the batch's admitted rows, for one descriptor. */
6364
interface ParentDelta {
@@ -123,6 +124,8 @@ function filterReadsThroughReference(cond: unknown): boolean {
123124
continue;
124125
}
125126
if (key.startsWith('$')) continue;
127+
// An empty object beneath a field is the nested form too, as the engine reads it (`isNoOperatorObject`).
128+
if (isNoOperatorObject(value)) return true;
126129
if (value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date)
127130
&& Object.keys(value).some((inner) => !inner.startsWith('$'))) return true;
128131
}
@@ -444,10 +447,22 @@ export interface PredicateUpdateSummaryFold {
444447

445448
/**
446449
* The fields of parent `parentId` (a row of `object`) calculated from its
447-
* roll-ups, computed over that parent with `moved` (the folded roll-up
448-
* values) in place of the stored ones; `undefined` when none is.
450+
* roll-ups, as a rule reads them before the next matched row: computed over
451+
* that parent with `moved` (the folded roll-up values) in place of the stored
452+
* ones; `undefined` when none is.
453+
*
454+
* `advance`, when present, is told after each matched row is judged, once per
455+
* parent that row names (as stored or as left) and with the roll-ups as that
456+
* row leaves them: one by one, the recompute writes each such parent after the
457+
* child's update, and the NEXT recompute's write starts from the row that
458+
* write stored, not from the row as stored before the update. A stored
459+
* computed field that reads its own stored value (a high-water mark), or a
460+
* chain of them declared against their reading order, only comes out as one
461+
* by one when the fold carries that image forward the same way.
449462
*/
450-
export type SummaryDependents = (object: string, parentId: string, moved: Readonly<Record<string, number | null>>) => Record<string, unknown> | undefined;
463+
export type SummaryDependents = ((object: string, parentId: string, moved: Readonly<Record<string, number | null>>) => Record<string, unknown> | undefined) & {
464+
advance?: (object: string, parentId: string, moved: Readonly<Record<string, number | null>>) => void;
465+
};
451466

452467
/** What one row adds to one parent's roll-up. */
453468
interface Contribution { parentId: string; value: number | undefined }
@@ -555,9 +570,8 @@ export function createPredicateUpdateSummaryFold(
555570

556571
let dependents: SummaryDependents | undefined;
557572

558-
const patchRow = (object: string, row: Record<string, unknown>): Record<string, unknown> | undefined => {
559-
const parentId = singleId(row.id);
560-
if (parentId === undefined) return undefined;
573+
/** The folded roll-up values of one parent in the current state, or `undefined` when this fold moves none of them. */
574+
const movedOf = (object: string, parentId: string): Record<string, number | null> | undefined => {
561575
const moved: Record<string, number | null> = {};
562576
let any = false;
563577
for (const desc of live.keys()) {
@@ -567,7 +581,14 @@ export function createPredicateUpdateSummaryFold(
567581
moved[desc.summaryField] = value;
568582
any = true;
569583
}
570-
if (!any) return undefined;
584+
return any ? moved : undefined;
585+
};
586+
587+
const patchRow = (object: string, row: Record<string, unknown>): Record<string, unknown> | undefined => {
588+
const parentId = singleId(row.id);
589+
if (parentId === undefined) return undefined;
590+
const moved = movedOf(object, parentId);
591+
if (!moved) return undefined;
571592
let patched: Record<string, unknown> | undefined;
572593
for (const [field, value] of Object.entries(moved)) {
573594
if (!(field in row)) continue;
@@ -615,6 +636,20 @@ export function createPredicateUpdateSummaryFold(
615636
move(desc, pair[0], -1);
616637
move(desc, pair[1], 1);
617638
}
639+
// One by one, the recompute writes every parent the row names, after the row's update.
640+
const states = matched[i];
641+
if (!dependents?.advance || !states) return;
642+
const named = new Map<string, { object: string; parentId: string }>();
643+
for (const desc of live.keys()) {
644+
for (const state of [states.previous, states.next]) {
645+
const parentId = singleId(state?.[desc.fkField]);
646+
if (parentId !== undefined) named.set(`${desc.parentObject}|${parentId}`, { object: desc.parentObject, parentId });
647+
}
648+
}
649+
for (const { object, parentId } of named.values()) {
650+
const moved = movedOf(object, parentId);
651+
if (moved) dependents.advance(object, parentId, moved);
652+
}
618653
};
619654

620655
const foldedSummaries = (): Map<string, { fields: Set<string>; parentIds: Set<string> }> => {

‎packages/objectql/src/summary-rollup.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1432,6 +1432,12 @@ describe('[#34465] a predicate update judges each matched row against the parent
14321432
cap_ref: { type: 'lookup', reference: 'inv_cap' },
14331433
cap_left: { type: 'formula', expression: 'record.cap_ref.amount - record.total', returnType: 'number' },
14341434
slack: { type: 'number', expression: { dialect: 'cel', source: 'record.remaining' } },
1435+
// A stored computed field reading its own stored value and the roll-up: a high-water mark.
1436+
peak: { type: 'number', expression: { dialect: 'cel', source: 'record.peak == null || record.total > record.peak ? record.total : record.peak' } },
1437+
// Three stored computed fields chained against declaration order: x reads y, y reads z, z reads the roll-up.
1438+
chain_x: { type: 'number', expression: { dialect: 'cel', source: 'record.chain_y' } },
1439+
chain_y: { type: 'number', expression: { dialect: 'cel', source: 'record.chain_z' } },
1440+
chain_z: { type: 'number', expression: { dialect: 'cel', source: 'record.total' } },
14351441
// A formula over the roll-up that also reads a formula reading no roll-up (`room` over `ceiling`).
14361442
extra: { type: 'number' },
14371443
ceiling: { type: 'formula', expression: 'record.budget + record.extra', returnType: 'number' },
@@ -1469,6 +1475,8 @@ describe('[#34465] a predicate update judges each matched row against the parent
14691475
// A stored computed field reading a formula: what does the rule read for it?
14701476
{ name: 'slack_set', type: 'script', severity: 'error', message: 'invoice slack is set', condition: "record.tag == 'slack' && record.inv.slack != null" },
14711477
{ name: 'gap_floor', type: 'script', severity: 'error', message: 'invoice head gap below 0', condition: "record.tag == 'gap' && record.inv.head_gap < 0" },
1478+
{ name: 'peak_cap', type: 'script', severity: 'error', message: 'invoice peak at 150 or more', condition: "record.tag == 'peak' && record.inv.peak >= 150" },
1479+
{ name: 'chain_cap', type: 'script', severity: 'error', message: 'invoice chain at 150 or more', condition: "record.tag == 'chain' && record.inv.chain_x != null && record.inv.chain_x >= 150" },
14721480
{ name: 'room_floor', type: 'script', severity: 'error', message: 'invoice room below 0', condition: "record.tag == 'room' && record.inv.room != null && record.inv.room < 0" },
14731481
],
14741482
} as any);
@@ -1674,6 +1682,47 @@ describe('[#34465] a predicate update judges each matched row against the parent
16741682
expect(inv(p.id).head_gap).toBe(20);
16751683
});
16761684

1685+
it('one by one (the reference answer), three rows: a high-water mark reads every total so far, so the third line reads 160 and is refused', async () => {
1686+
const p = await engine.insert('inv', { name: 'P' });
1687+
const a = await engine.insert('inv_line', { inv: p.id, amount: 0, tag: 'x' });
1688+
const b = await engine.insert('inv_line', { inv: p.id, amount: 100, tag: 'x' });
1689+
const c = await engine.insert('inv_line', { inv: p.id, amount: 0, tag: 'peak' });
1690+
expect(inv(p.id).peak).toBe(100);
1691+
// Totals 100 -> 160 -> 120: the peak climbs to 160 at the first update and stays there.
1692+
await engine.update('inv_line', { id: a.id, amount: 60 });
1693+
await engine.update('inv_line', { id: b.id, amount: 60 });
1694+
expect(inv(p.id).peak).toBe(160);
1695+
expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: c.id, amount: 60 })), 'invoice peak at 150 or more');
1696+
});
1697+
1698+
it('predicate update, three rows: each recompute starts from the row the previous one stored, so the third row reads the peak of 160 and is refused', async () => {
1699+
const p = await engine.insert('inv', { name: 'P' });
1700+
await engine.insert('inv_line', [{ inv: p.id, amount: 0, tag: 'x' }, { inv: p.id, amount: 100, tag: 'x' }, { inv: p.id, amount: 0, tag: 'peak' }]);
1701+
// Restarted from the stored row at every row, the third would read the larger of 100 and 120 and be admitted.
1702+
expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 60 }, { where: { inv: p.id }, multi: true })), 'invoice peak at 150 or more');
1703+
expect(inv(p.id).peak).toBe(100);
1704+
});
1705+
1706+
it('one by one (the reference answer), three rows: a chain declared against its reading order moves one write behind, so the third line reads 150 and is refused', async () => {
1707+
const p = await engine.insert('inv', { name: 'P' });
1708+
const a = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'x' });
1709+
const b = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'x' });
1710+
const c = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'chain' });
1711+
// Totals 120 -> 150 -> 180: `chain_x` holds the total from one write before.
1712+
await engine.update('inv_line', { id: a.id, amount: 70 });
1713+
expect(inv(p.id).chain_x).toBe(120);
1714+
await engine.update('inv_line', { id: b.id, amount: 70 });
1715+
expect(inv(p.id).chain_x).toBe(150);
1716+
expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: c.id, amount: 70 })), 'invoice chain at 150 or more');
1717+
});
1718+
1719+
it('predicate update, three rows: the chain is carried forward as one by one moves it, so the third row reads 150 and is refused', async () => {
1720+
const p = await engine.insert('inv', { name: 'P' });
1721+
await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'x' }, { inv: p.id, amount: 40, tag: 'x' }, { inv: p.id, amount: 40, tag: 'chain' }]);
1722+
// Restarted from the stored row at every row, `chain_x` would read 120 at the third row and the rule admit.
1723+
expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true })), 'invoice chain at 150 or more');
1724+
});
1725+
16771726
it('predicate update that reparents: the header a parent. predicate reads counts the rows moved before', async () => {
16781727
const from = await engine.insert('inv', { name: 'FROM' });
16791728
const to = await engine.insert('inv', { name: 'TO' });

0 commit comments

Comments
 (0)