From ba8fc3bc6b672189365576dc8cc97b806ea9250e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:37:07 +0000 Subject: [PATCH 1/8] fix(objectql): a bulk insert computes a parent's formula fields over the roll-ups its rows move; fold stand-downs traced The insert accumulator recomputes parent formula / stored computed fields built on an accumulated roll-up, and screens filters reading through a reference in the nested form. A predicate update leaves unfolded a roll-up its patch cannot move, and each fold stand-down logs one debug line. Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- packages/objectql/src/engine-insert.ts | 17 ++ packages/objectql/src/engine-update.ts | 24 +- .../src/summary-batch-accumulation.test.ts | 127 +++++++++- .../src/summary-batch-accumulation.ts | 185 ++++++++++++-- packages/objectql/src/summary-rollup.test.ts | 237 +++++++++++++++++- 5 files changed, 557 insertions(+), 33 deletions(-) diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index ec04835b3f6..de08f1bca73 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -60,6 +60,7 @@ import { coerceBooleanFields, normalizeBlankTypedValues, normalizeMultiValueFiel import { emitValidationAdvisories, evaluateValidationRules, hasParentScopedRequiredWhen, preserveAuditIgnoredOnInsertWarning, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js'; import type { staticReadonlyInsertSubject } from './validation/rule-validator.js'; import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js'; +import { loadSummaryFoldDependents } from './engine-update.js'; import { resolveMasterDetailRelation } from './master-detail.js'; import { recordHookPayloadWrites } from './hook-write-provenance.js'; import type { HookWriteRecording } from './hook-write-provenance.js'; @@ -1348,6 +1349,22 @@ export class InsertFacet { const header = insertParentForRow?.(row); return insertParentMaster ? batchSummaries!.overlayRow(insertParentMaster, header) : header; }; + // [#34821] And a formula or stored computed field of such a parent + // calculated from an accumulated roll-up (`remaining = budget - + // total`), computed again over the moved values as the predicate + // update's fold computes it. Loaded only for the parents a rule of + // this batch reads (a related binding or a header): an insert no rule + // reads a parent of pays nothing here. + if (batchSummaries) { + const readParents = new Set(); + for (let i = 0; i < rows.length; i++) { + if (rowErrors[i] !== undefined) continue; + for (const entry of Object.values(insertRelatedForRow(rows[i]) ?? {})) if (entry?.row) readParents.add(entry.object); + if (insertParentMaster && insertParentForRow?.(rows[i])) readParents.add(insertParentMaster); + } + const folded = readParents.size > 0 ? batchSummaries.foldedSummaries(rows, readParents) : undefined; + if (folded && folded.size > 0) batchSummaries.setDependents(await loadSummaryFoldDependents(this, folded, opCtx.context)); + } // [#18783] The subject's effective object permissions, for an option // gated on `current_user.can(…)`: ONE resolution for the whole batch, // and none at all unless a row picks such an option. A resolution diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 215cfc4ea66..948b825bb6d 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -61,8 +61,8 @@ import type { ReferentialClearExemption } from './validation/rule-validator.js'; import { recordHookPayloadWrites } from './hook-write-provenance.js'; import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonly-fault.js'; import { resolveMasterDetailRelation } from './master-detail.js'; -import { createPredicateUpdateSummaryFold, loadPredicateUpdateSummaryBases } from './summary-batch-accumulation.js'; -import type { SummaryDependents } from './summary-batch-accumulation.js'; +import { createPredicateUpdateSummaryFold, loadPredicateUpdateSummaryBases, summaryPatchCanMove } from './summary-batch-accumulation.js'; +import type { SummaryDependents, SummaryFoldStandDownSink } from './summary-batch-accumulation.js'; import { SUMMARY_GROUPED_AGGREGATE_CHUNK } from './summary-aggregate.js'; import { declaredColumnSet, rowsWithDeclaredColumnsOnly, selectedStoredColumns, storedColumnsLeftUnwritten, withDeclaredColumnsOnly, withSelectedColumnsAnswered } from './declared-read-columns.js'; import { externalPredicateWriteRefusal, isExternalDriverFloor } from './external-driver-floor.js'; @@ -2181,15 +2181,25 @@ export class UpdateFacet { // rule reads one and more than one row matched; still all // rows judged before the one `updateMany`. const matchedRows = priorRows ?? []; - const readSummaries = matchedRows.length > 1 ? this.summaryDescriptorsReadByRules(object) : []; + // [#34821] A roll-up the patch cannot move (it writes no + // foreign key, source or filter field of it) is not folded: + // its rules read the stored value, as the by-id update does. + const readSummaries = matchedRows.length > 1 + ? this.summaryDescriptorsReadByRules(object).filter((desc) => summaryPatchCanMove(desc, bulkPatch)) + : []; const matchedStates = readSummaries.length > 0 ? matchedRows.map((row) => ({ previous: row ?? {}, next: { ...(row ?? {}), ...bulkPatch } })) : []; + // [#34821] A roll-up left unfolded leaves one trace, naming it and why. + const standDown: SummaryFoldStandDownSink = (desc, reason) => this.logger.debug('Roll-up left unfolded in a predicate update: its rules read the stored value', { + object, parentObject: desc.parentObject, field: desc.summaryField, reason, + }); const summaryFold = readSummaries.length > 0 ? createPredicateUpdateSummaryFold( - await loadPredicateUpdateSummaryBases(this.facade, readSummaries, matchedStates, { ...(opCtx.context ?? {}), isSystem: true }), + await loadPredicateUpdateSummaryBases(this.facade, readSummaries, matchedStates, { ...(opCtx.context ?? {}), isSystem: true }, standDown), matchedStates, (updateSchema as any)?.fields, + standDown, ) : undefined; if (summaryFold) { @@ -2470,6 +2480,8 @@ export class UpdateFacet { * through another such field (`remaining = budget - spent`, `spent` a * roll-up). A rule reading `record.project.remaining` reads such a field, and * one by one it would read it over the roll-up the earlier rows moved. + * [#34821] A multi-row insert's accumulator reads the same, for the roll-ups + * its admitted rows move (`engine-insert.ts`). * * Read the way a by-id update's rule reads the parent: the values as SYSTEM * (`resolvePredicateRelated` reads related rows under system authority). So @@ -2511,7 +2523,7 @@ export class UpdateFacet { * ({@link applyFormulaPlan}). An object no such field reads a folded roll-up * of reads nothing. */ -async function loadSummaryFoldDependents( +export async function loadSummaryFoldDependents( host: Pick, folded: Map; parentIds: Set }>, context: Parameters[3], @@ -2596,5 +2608,7 @@ async function loadSummaryFoldDependents( const key = `${object}|${parentId}`; images.set(key, written(entry, images.get(key) ?? stored, moved)); }; + // [#34821] The parent as stored: the base a bulk insert's accumulator moves a roll-up from. + dependents.stored = (object, parentId) => served.get(object)?.rows.get(parentId); return dependents; } diff --git a/packages/objectql/src/summary-batch-accumulation.test.ts b/packages/objectql/src/summary-batch-accumulation.test.ts index dfec75d057b..92bd923d438 100644 --- a/packages/objectql/src/summary-batch-accumulation.test.ts +++ b/packages/objectql/src/summary-batch-accumulation.test.ts @@ -9,8 +9,8 @@ */ import { describe, it, expect } from 'vitest'; -import { createBatchSummaryAccumulator, createPredicateUpdateSummaryFold, loadPredicateUpdateSummaryBases, MIN_MAX_EXCLUDED_ID_BUDGET } from './summary-batch-accumulation.js'; -import type { MatchedRowStates, SummaryBase, SummaryBases } from './summary-batch-accumulation.js'; +import { createBatchSummaryAccumulator, createPredicateUpdateSummaryFold, loadPredicateUpdateSummaryBases, MIN_MAX_EXCLUDED_ID_BUDGET, summaryPatchCanMove } from './summary-batch-accumulation.js'; +import type { MatchedRowStates, SummaryBase, SummaryBases, SummaryDependents, SummaryFoldStandDown } from './summary-batch-accumulation.js'; import type { SummaryDescriptor } from './summary-aggregate.js'; import type { RelatedRecordBinding } from './validation/rule-validator.js'; @@ -318,3 +318,126 @@ describe('[#34465] loadPredicateUpdateSummaryBases — the base a predicate upda expect((await loadPredicateUpdateSummaryBases(nested.engine, [desc({ fn: 'min', summaryField: 'low', filter: { kind: { $in: ['a'] } } })], matched)).size).toBe(1); }); }); + +describe('[#34821] the bulk insert accumulator screens a filter reading through a reference as the predicate update\'s fold does', () => { + it('a filter in the nested one-level form, at any depth of $and / $or / $not, is not accumulated: no accumulator when it is the only roll-up', () => { + for (const filter of [{ account: { status: 'x' } }, { $not: { account: { status: 'x' } } }, { $or: [{ kind: 'a' }, { account: { status: 'x' } }] }, { account: {} }]) { + expect(createBatchSummaryAccumulator([desc({ fn: 'count', filter })], CHILD_FIELDS)).toBeUndefined(); + } + }); + + it('CONTROL: a field condition spelled with operators is still accumulated', () => { + const acc = createBatchSummaryAccumulator([desc({ fn: 'count', summaryField: 'n', filter: { kind: { $in: ['a'] } } })], CHILD_FIELDS)!; + acc.accept({ order: 'o1', kind: 'a' }); + expect(acc.overlay(bound({ id: 'o1', n: 1 }))!.order!.row).toEqual({ id: 'o1', n: 2 }); + }); +}); + +describe('[#34821] the bulk insert accumulator hands the moved roll-ups to what computes the parent fields calculated from them', () => { + const sum = desc({}); + + it('names, per parent object a rule reads, the roll-ups it moves and the parents the rows name', () => { + const acc = createBatchSummaryAccumulator([sum, desc({ parentObject: 'xt_other', summaryField: 'n', fn: 'count' })], CHILD_FIELDS)!; + const rows = [{ order: 'o1' }, { order: 'o2' }, { order: null }, null]; + expect(acc.foldedSummaries(rows, new Set(['xt_order']))).toEqual(new Map([['xt_order', { fields: new Set(['total']), parentIds: new Set(['o1', 'o2']) }]])); + expect(acc.foldedSummaries(rows, new Set())).toEqual(new Map()); + }); + + it('a binding naming only the calculated field: the roll-up is moved from the stored parent, and the calculated field patched with what the dependents compute', () => { + const acc = createBatchSummaryAccumulator([sum], CHILD_FIELDS)!; + const asked: unknown[] = []; + const dependents = Object.assign((object: string, parentId: string, moved: Readonly>) => { + asked.push([object, parentId, { ...moved }]); + return { remaining: 100 - (moved.total ?? 0), other: 'x' }; + }, { stored: (object: string, parentId: string) => (object === 'xt_order' && parentId === 'o1' ? { id: 'o1', total: 80 } : undefined) }) as SummaryDependents; + acc.setDependents(dependents); + const binding: RelatedRecordBinding = { order: { object: 'xt_order', row: { id: 'o1', remaining: 20 } } }; + // No admitted row yet: nothing moves, the dependents are not asked. + expect(acc.overlay(binding)).toBe(binding); + acc.accept({ order: 'o1', amount: 30 }); + expect(acc.overlay(binding)!.order!.row).toEqual({ id: 'o1', remaining: -10 }); + expect(binding.order!.row).toEqual({ id: 'o1', remaining: 20 }); + expect(asked).toEqual([['xt_order', 'o1', { total: 110 }]]); + }); + + it('a binding carrying the roll-up moves it from the value it carries; the header overlay reads the same', () => { + const acc = createBatchSummaryAccumulator([sum], CHILD_FIELDS)!; + acc.setDependents(Object.assign((_o: string, _p: string, moved: Readonly>) => ({ remaining: 100 - (moved.total ?? 0) }), { stored: () => ({ id: 'o1', total: 0 }) }) as SummaryDependents); + acc.accept({ order: 'o1', amount: 30 }); + expect(acc.overlay(bound({ id: 'o1', total: 80, remaining: 20 }))!.order!.row).toEqual({ id: 'o1', total: 110, remaining: -10 }); + expect(acc.overlayRow('xt_order', { id: 'o1', total: 80, remaining: 20 })).toEqual({ id: 'o1', total: 110, remaining: -10 }); + }); + + it('tells the dependents, after each admitted row, every parent that row names with the roll-ups it moves them to', () => { + const acc = createBatchSummaryAccumulator([sum], CHILD_FIELDS)!; + const advanced: unknown[] = []; + acc.setDependents(Object.assign(() => undefined, { + stored: (_o: string, parentId: string) => ({ id: parentId, total: parentId === 'o1' ? 80 : 0 }), + advance: (object: string, parentId: string, moved: Readonly>) => { advanced.push([object, parentId, { ...moved }]); }, + }) as SummaryDependents); + acc.accept({ order: 'o1', amount: 30 }); + acc.accept({ order: 'o2', amount: 5 }); + acc.accept({ order: 'o1', amount: -50 }); + expect(advanced).toEqual([ + ['xt_order', 'o1', { total: 110 }], + ['xt_order', 'o2', { total: 5 }], + ['xt_order', 'o1', { total: 60 }], + ]); + }); +}); + +describe('[#34821] summaryPatchCanMove — a roll-up a predicate update\'s patch cannot move is not folded', () => { + const filtered = desc({ fn: 'count', summaryField: 'n', filter: { $and: [{ kind: 'a' }, { $or: [{ is_primary: true }, { $not: { note: 'x' } }] }] } }); + + it('moves when the patch writes the foreign key, the source field, or a field the filter names at any depth', () => { + expect(summaryPatchCanMove(desc({}), { order: 'o2' })).toBe(true); + expect(summaryPatchCanMove(desc({}), { amount: 1 })).toBe(true); + expect(summaryPatchCanMove(desc({ fn: 'avg' }), { amount: null })).toBe(true); + for (const field of ['kind', 'is_primary', 'note']) expect(summaryPatchCanMove(filtered, { [field]: null })).toBe(true); + }); + + it('cannot move when the patch writes none of them; a count reads no source field', () => { + expect(summaryPatchCanMove(desc({}), { kind: 'b', note: 'n' })).toBe(false); + expect(summaryPatchCanMove(filtered, { amount: 5 })).toBe(false); + expect(summaryPatchCanMove(desc({ fn: 'count', sourceField: undefined }), { amount: 5 })).toBe(false); + }); + + it('a filter holding a condition whose fields it cannot read is taken to move', () => { + expect(summaryPatchCanMove(desc({ fn: 'count', filter: { $expr: { $gt: ['$amount', 1] } } }), { kind: 'b' })).toBe(true); + }); +}); + +describe('[#34821] each stand-down of a predicate update\'s fold is reported once, naming the roll-up and why', () => { + const recorder = (answer: () => any[]) => ({ aggregate: async () => answer() }); + const matched: MatchedRowStates[] = [ + { previous: { id: 'a', order: 'o1', amount: 1 }, next: { id: 'a', order: 'o1', amount: 2 } }, + { previous: { id: 'b', order: 'o1', amount: 2 }, next: { id: 'b', order: 'o1', amount: 3 } }, + ]; + const sink = () => { + const told: Array<[string, SummaryFoldStandDown]> = []; + return { told, standDown: (d: SummaryDescriptor, reason: SummaryFoldStandDown) => { told.push([d.summaryField, reason]); } }; + }; + + it('the base loader: a filter reading through a reference, an answer that is no number, a min / max past the exclusion budget', async () => { + const { told, standDown } = sink(); + await loadPredicateUpdateSummaryBases(recorder(() => [{ order: 'o1', value: 1 }]), [desc({ fn: 'count', summaryField: 'nested', filter: { account: { status: 'x' } } })], matched, undefined, standDown); + await loadPredicateUpdateSummaryBases(recorder(() => [{ order: 'o1', value: '2026-01-01' }]), [desc({ fn: 'min', summaryField: 'first_day', sourceField: 'day' })], matched, undefined, standDown); + const many: MatchedRowStates[] = Array.from({ length: MIN_MAX_EXCLUDED_ID_BUDGET + 1 }, (_, i) => ({ previous: { id: `r${i}`, order: 'o1' }, next: { id: `r${i}`, order: 'o1' } })); + await loadPredicateUpdateSummaryBases(recorder(() => []), [desc({ fn: 'max', summaryField: 'highest' })], many, undefined, standDown); + // CONTROL: a roll-up the loader folds is not reported. + await loadPredicateUpdateSummaryBases(recorder(() => [{ order: 'o1', value: 3 }]), [desc({})], matched, undefined, standDown); + expect(told).toEqual([['nested', 'filter'], ['first_day', 'not_a_number'], ['highest', 'exclusion_budget']]); + }); + + it('the fold: a filter the walker refuses, a matched value that is no number', () => { + const { told, standDown } = sink(); + const base = new Map([['o1', { count: 0, sum: 3, nonNull: 0, min: null, max: null }]]); + const refused = desc({ fn: 'count', summaryField: 'refused', filter: { kind: { $nope: 1 } } }); + const texty = desc({ summaryField: 'texty', sourceField: 'note' }); + const kept = desc({}); + const rows: MatchedRowStates[] = [{ previous: { id: 'a', order: 'o1', amount: 1, kind: 'a', note: 'x' }, next: { id: 'a', order: 'o1', amount: 2, kind: 'a', note: 'y' } }]; + const fold = createPredicateUpdateSummaryFold(new Map([[refused, base], [texty, base], [kept, base]]), rows, CHILD_FIELDS, standDown); + expect(fold!.foldedSummaries().get('xt_order')!.fields).toEqual(new Set(['total'])); + expect(told).toEqual([['refused', 'filter'], ['texty', 'not_a_number']]); + }); +}); diff --git a/packages/objectql/src/summary-batch-accumulation.ts b/packages/objectql/src/summary-batch-accumulation.ts index 5078351317d..a0228b58a80 100644 --- a/packages/objectql/src/summary-batch-accumulation.ts +++ b/packages/objectql/src/summary-batch-accumulation.ts @@ -46,8 +46,17 @@ * - `avg` — the stored average does not say how many rows it averages. * - `sum` / `min` / `max` meeting a value that is not a number (a date, a * text), or a stored value that is not one. - * - a summary whose `filter` names a dotted path (it reads through another - * reference, which the new row does not carry), or that the walker refuses. + * - a summary whose `filter` reads through another reference, in either + * spelling (a dotted path, or the nested one-level form + * `{ account: { status: 'x' } }`): the new row does not carry the related + * record. Or one the walker refuses. + * + * [#34821] A formula or stored computed field of the parent calculated from + * an accumulated roll-up (`remaining = budget - total`) is computed again + * over the moved values, as the recompute's write and the next read compute + * it one by one: the caller hands the accumulator what computes them + * ({@link BatchSummaryAccumulator.setDependents}), the same + * {@link SummaryDependents} the predicate update's fold below reads. * * Concurrent writes are out of scope: two batches in flight each read the * stored value they started from. @@ -87,6 +96,15 @@ export interface BatchSummaryAccumulator { overlayRow | null | undefined>(object: string, row: R): R; /** Count `row` in. Call it only once the row's rules have admitted it. */ accept(row: Record): void; + /** + * [#34821] The roll-ups this accumulator moves whose parent object is one of + * `objects` (the parents the batch's rules read), per parent object: their + * fields and the parents `rows` name. What {@link setDependents} is loaded + * for. + */ + foldedSummaries(rows: readonly unknown[], objects: ReadonlySet): Map; parentIds: Set }>; + /** [#34821] Hand the accumulator what computes a parent's fields calculated from its moved roll-ups ({@link SummaryDependents}). */ + setDependents(dependents: SummaryDependents): void; } const ACCUMULABLE: ReadonlySet = new Set(['count', 'sum', 'min', 'max']); @@ -150,7 +168,9 @@ export function createBatchSummaryAccumulator( descriptors: readonly SummaryDescriptor[], childFields: unknown, ): BatchSummaryAccumulator | undefined { - const live = descriptors.filter((d) => ACCUMULABLE.has(d.fn) && !filterNamesDottedPath(d.filter)); + // [#34821] The screen the predicate update's fold applies: a filter reading + // through a reference in the nested form is no more exact than a dotted one. + const live = descriptors.filter((d) => ACCUMULABLE.has(d.fn) && !filterReadsThroughReference(d.filter)); if (live.length === 0) return undefined; const classes = declaredFieldClasses(childFields); const jsonStored = declaredJsonStoredFields(childFields); @@ -158,6 +178,8 @@ export function createBatchSummaryAccumulator( const deltas = new Map>(); const dropped = new Set(); + let dependents: SummaryDependents | undefined; + const accept = (row: Record): void => { for (const desc of live) { if (dropped.has(desc)) continue; @@ -196,6 +218,18 @@ export function createBatchSummaryAccumulator( } byParent.set(parentId, delta); } + // [#34821] One by one, the recompute writes every parent the row names + // after its insert; the next write starts from the row that write stored. + if (!dependents?.advance) return; + const named = new Map(); + for (const desc of live) { + const parentId = singleId(row[desc.fkField]); + if (parentId !== undefined) named.set(`${desc.parentObject}|${parentId}`, { object: desc.parentObject, parentId }); + } + for (const { object, parentId } of named.values()) { + const values = movedOf(object, parentId); + if (values) dependents.advance(object, parentId, values); + } }; /** The summary value `stored` moves to under `delta`, or `undefined` when it cannot be said exactly. */ @@ -211,20 +245,51 @@ export function createBatchSummaryAccumulator( } }; - /** A copy of `row` (a stored row of `object`) with every summary the admitted rows move, or `undefined` when none moves. */ - const patchRow = (object: string, row: Record): Record | undefined => { - const parentId = singleId(row.id); - if (parentId === undefined) return undefined; - let patched: Record | undefined; + /** + * The summary values the admitted rows move parent `parentId` (a row of + * `object`) to, or `undefined` when none moves. Each is moved from the value + * `row` carries, or, for a roll-up `row` was not handed (and for no row), + * from the stored parent the dependents read: both are read before the + * batch writes anything. + */ + const movedOf = (object: string, parentId: string, row?: Record): Record | undefined => { + const stored = dependents?.stored?.(object, parentId); + let out: Record | undefined; for (const [desc, byParent] of deltas) { if (dropped.has(desc) || desc.parentObject !== object) continue; - if (!(desc.summaryField in row)) continue; // the reader was not handed this roll-up const delta = byParent.get(parentId); if (!delta) continue; - const value = moved(desc, row[desc.summaryField], delta); + const from = row && desc.summaryField in row ? row : stored && desc.summaryField in stored ? stored : undefined; + if (!from) continue; + const value = moved(desc, from[desc.summaryField], delta); if (value === undefined) continue; + (out ??= {})[desc.summaryField] = value; + } + return out; + }; + + /** A copy of `row` (a stored row of `object`) with every summary the admitted rows move, or `undefined` when none moves. */ + const patchRow = (object: string, row: Record): Record | undefined => { + const parentId = singleId(row.id); + if (parentId === undefined) return undefined; + const values = movedOf(object, parentId, row); + if (!values) return undefined; + let patched: Record | undefined; + for (const [field, value] of Object.entries(values)) { + if (!(field in row)) continue; // the reader was not handed this roll-up patched ??= { ...row }; - patched[desc.summaryField] = value; + patched[field] = value; + } + // [#34821] A formula or stored computed field of the parent calculated + // from a moved roll-up is computed again with the moved values, as the + // predicate update's fold computes it. + const computed = dependents?.(object, parentId, values); + if (computed) { + for (const [field, value] of Object.entries(computed)) { + if (!(field in row)) continue; + patched ??= { ...row }; + patched[field] = value; + } } return patched; }; @@ -249,7 +314,22 @@ export function createBatchSummaryAccumulator( return (patchRow(object, row) as R | undefined) ?? row; }; - return { accept, overlay, overlayRow }; + const foldedSummaries = (rows: readonly unknown[], objects: ReadonlySet): Map; parentIds: Set }> => { + const out = new Map; parentIds: Set }>(); + for (const desc of live) { + if (!objects.has(desc.parentObject)) continue; + let entry = out.get(desc.parentObject); + if (!entry) out.set(desc.parentObject, (entry = { fields: new Set(), parentIds: new Set() })); + entry.fields.add(desc.summaryField); + for (const row of rows) { + const parentId = row && typeof row === 'object' ? singleId((row as Record)[desc.fkField]) : undefined; + if (parentId !== undefined) entry.parentIds.add(parentId); + } + } + return out; + }; + + return { accept, overlay, overlayRow, foldedSummaries, setDependents: (fn) => { dependents = fn; } }; } /** @@ -296,6 +376,57 @@ export function createBatchSummaryAccumulator( */ export const MIN_MAX_EXCLUDED_ID_BUDGET = 5000; +/** + * [#34821] Why a predicate update's fold leaves a roll-up unfolded, so its + * rules read the value the binding carries (the stored one): its `filter` + * reads through a reference or the in-memory walker refuses it; a value that + * is not a number; or a `min` / `max` whose exclusion does not fit + * {@link MIN_MAX_EXCLUDED_ID_BUDGET}. Each stands the roll-up down for every + * parent of that update. + */ +export type SummaryFoldStandDown = 'filter' | 'not_a_number' | 'exclusion_budget'; + +/** [#34821] Told once per roll-up a fold stands down, with why: the trace that makes the published limit observable. */ +export type SummaryFoldStandDownSink = (desc: SummaryDescriptor, reason: SummaryFoldStandDown) => void; + +/** The fields a filter names, or `undefined` when it holds a condition this cannot read the fields of. */ +function filterFieldNames(cond: unknown, into: Set): Set | undefined { + if (Array.isArray(cond)) { + for (const c of cond) if (!filterFieldNames(c, into)) return undefined; + return into; + } + if (!cond || typeof cond !== 'object') return into; + for (const [key, value] of Object.entries(cond as Record)) { + if (key === '$and' || key === '$or' || key === '$not') { + if (!filterFieldNames(value, into)) return undefined; + continue; + } + if (key.startsWith('$')) return undefined; + into.add(key.split('.')[0]!); + } + return into; +} + +/** + * [#34821] Whether a patch can move roll-up `desc` at all: it writes the + * foreign key, the source field (not a `count`'s) or a field the filter names (or a filter + * this cannot read the fields of). A patch that cannot leaves every matched + * row's contribution where it stands, so the roll-up is not folded and its + * rules read the stored value, as the by-id update reads it, at no cost: a + * base aggregated from the children differs from the stored value only where + * that is stale or held at a column scale. + */ +export function summaryPatchCanMove(desc: SummaryDescriptor, patch: Readonly>): boolean { + if (desc.fkField in patch) return true; + // A `count` counts rows, whatever its source field holds. + if (desc.fn !== 'count' && desc.sourceField !== undefined && desc.sourceField in patch) return true; + if (!desc.filter) return false; + const named = filterFieldNames(desc.filter, new Set()); + if (!named) return true; + for (const field of named) if (field in patch) return true; + return false; +} + /** Whether a roll-up's base counts the matched rows as stored (else it leaves them out). */ function baseHoldsMatched(fn: SummaryDescriptor['fn']): boolean { return fn === 'count' || fn === 'sum' || fn === 'avg'; @@ -343,10 +474,11 @@ export async function loadPredicateUpdateSummaryBases( descriptors: readonly SummaryDescriptor[], matched: readonly MatchedRowStates[], execCtx?: unknown, + standDown?: SummaryFoldStandDownSink, ): Promise { const bases: SummaryBases = new Map(); for (const desc of descriptors) { - if (filterReadsThroughReference(desc.filter)) continue; + if (filterReadsThroughReference(desc.filter)) { standDown?.(desc, 'filter'); continue; } if (desc.fn !== 'count' && desc.sourceField === undefined) continue; const holdsMatched = baseHoldsMatched(desc.fn); const parents = new Set(); @@ -382,7 +514,7 @@ export async function loadPredicateUpdateSummaryBases( current.push(id); excludedInCurrent += held; } - if (!fits) continue; + if (!fits) { standDown?.(desc, 'exclusion_budget'); continue; } if (current.length > 0) statements.push(current); const byParent = new Map(); // The aggregate's aliases must not be the group key's name. @@ -424,7 +556,7 @@ export async function loadPredicateUpdateSummaryBases( byParent.set(String(key), base); } } - if (!numeric) continue; + if (!numeric) { standDown?.(desc, 'not_a_number'); continue; } // A parent no row matched has the empty set's base. for (const id of parents) if (!byParent.has(id)) byParent.set(id, { count: 0, sum: 0, nonNull: 0, min: null, max: null }); bases.set(desc, byParent); @@ -462,6 +594,12 @@ export interface PredicateUpdateSummaryFold { */ export type SummaryDependents = ((object: string, parentId: string, moved: Readonly>) => Record | undefined) & { advance?: (object: string, parentId: string, moved: Readonly>) => void; + /** + * [#34821] The parent row as stored before the write, as the dependents + * read it: the base the bulk insert's accumulator moves a roll-up from when + * the reader's row does not carry it. + */ + stored?: (object: string, parentId: string) => Readonly> | undefined; }; /** What one row adds to one parent's roll-up. */ @@ -485,27 +623,28 @@ export function createPredicateUpdateSummaryFold( bases: SummaryBases, matched: readonly MatchedRowStates[], childFields: unknown, + standDown?: SummaryFoldStandDownSink, ): PredicateUpdateSummaryFold | undefined { if (bases.size === 0) return undefined; const classes = declaredFieldClasses(childFields); const jsonStored = declaredJsonStoredFields(childFields); const live = new Map(bases); - /** The row's contribution to `desc`, `null` for none, `undefined` when it cannot be said exactly. */ - const contributionOf = (desc: SummaryDescriptor, row: Record): Contribution | null | undefined => { + /** The row's contribution to `desc`, `null` for none, or why it cannot be said exactly. */ + const contributionOf = (desc: SummaryDescriptor, row: Record): Contribution | null | SummaryFoldStandDown => { const parentId = singleId(row[desc.fkField]); if (parentId === undefined) return null; if (desc.filter) { try { if (!matchesAggregationFilter(row, desc.filter as any, 0, classes, jsonStored)) return null; } catch { - return undefined; + return 'filter'; } } if (desc.fn === 'count') return { parentId, value: undefined }; const raw = row[desc.sourceField!]; if (raw == null) return { parentId, value: undefined }; - if (typeof raw !== 'number' || !Number.isFinite(raw)) return undefined; + if (typeof raw !== 'number' || !Number.isFinite(raw)) return 'not_a_number'; return { parentId, value: raw }; }; @@ -513,15 +652,15 @@ export function createPredicateUpdateSummaryFold( const contributions = new Map>(); for (const desc of [...live.keys()]) { const list: Array<[Contribution | null, Contribution | null]> = []; - let exact = true; + let inexact: SummaryFoldStandDown | undefined; for (const { previous, next } of matched) { const was = contributionOf(desc, previous); const now = contributionOf(desc, next); - if (was === undefined || now === undefined) { exact = false; break; } + if (typeof was === 'string' || typeof now === 'string') { inexact = typeof was === 'string' ? was : now as SummaryFoldStandDown; break; } list.push([was, now]); } - if (exact) contributions.set(desc, list); - else live.delete(desc); + if (inexact === undefined) contributions.set(desc, list); + else { live.delete(desc); standDown?.(desc, inexact); } } if (live.size === 0) return undefined; diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index f26f7a8710d..50887eb2bfb 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -1779,9 +1779,10 @@ describe('[#34465] a predicate update judges each matched row against the parent expect(await engine.update('inv_line', { amount: 3 }, { where: { inv: p.id }, multi: true })).toBe(2); const write = log.findIndex((e, i) => i >= start && e.op === 'updateMany'); const before = log.slice(start, write).filter((e) => e.object === 'aggregate:inv_line'); - // primaries, line_count, total, low, mean: every roll-up of inv_line a rule or predicate reads - // (total twice over: directly, and through remaining and headroom). - expect(before).toHaveLength(5); + // total, low, mean: every roll-up of inv_line a rule or predicate reads (total twice over: + // directly, and through remaining and headroom) that the patch can move. [#34821] primaries + // (a count filtered on is_primary) and line_count (a count) cannot move under an amount patch. + expect(before).toHaveLength(3); expect(before.every((e) => Array.isArray(e.ast.groupBy) && e.ast.groupBy[0] === 'inv')).toBe(true); }); }); @@ -1857,3 +1858,233 @@ describe('[#34465] a min / max roll-up whose filter reads through a reference in expect([...storeFor('ord_line').values()].map((r) => r.tag)).toEqual(['x', 'x', 'x']); }); }); + +describe('[#34821] a multi-row insert judges a rule reading a parent field calculated from a roll-up as one by one judges it', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + let log: ReturnType['log']; + + beforeEach(async () => { + engine = new ObjectQL(); + const d = makeDriver(); + storeFor = d.storeFor; + log = d.log; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject({ + name: 'bud', + fields: { + name: { type: 'text' }, + budget: { type: 'number' }, + line_count: { type: 'summary', summaryOperations: { object: 'bud_line', field: 'amount', function: 'count' } }, + total: { type: 'summary', summaryOperations: { object: 'bud_line', field: 'amount', function: 'sum' } }, + // Calculated from the roll-up: on read (a formula) and on write (a stored computed field). + remaining: { type: 'formula', expression: 'record.budget - record.total', returnType: 'number' }, + headroom: { type: 'number', expression: { dialect: 'cel', source: 'record.budget - record.total' } }, + // A stored computed field reading its own stored value and the roll-up: a high-water mark. + peak: { type: 'number', expression: { dialect: 'cel', source: 'record.peak == null || record.total > record.peak ? record.total : record.peak' } }, + // CONTROL: calculated from a roll-up of an object no rule of which reads this parent. + memo_total: { type: 'summary', summaryOperations: { object: 'bud_memo', field: 'amount', function: 'sum' } }, + memo_left: { type: 'formula', expression: 'record.budget - record.memo_total', returnType: 'number' }, + }, + } as any); + engine.registry.registerObject({ name: 'bud_memo', fields: { amount: { type: 'number' }, bud: { type: 'lookup', reference: 'bud' } } } as any); + engine.registry.registerObject({ + name: 'bud_line', + fields: { + amount: { type: 'number' }, + tag: { type: 'text' }, + bud: { type: 'master_detail', reference: 'bud' }, + // A field-level parent. predicate reading the header's calculated field. + note: { type: 'text', requiredWhen: 'parent.headroom < 50' }, + }, + validations: [ + { name: 'remaining_cover', type: 'script', severity: 'error', message: 'line over the remaining budget', condition: "record.tag == 'rem' && record.amount > record.bud.remaining" }, + { name: 'headroom_cover', type: 'script', severity: 'error', message: 'line over the budget headroom', condition: "record.tag == 'head' && record.amount > record.bud.headroom" }, + { name: 'peak_cap', type: 'script', severity: 'error', message: 'budget peak at 50 or more', condition: "record.tag == 'peak' && record.bud.peak >= 50" }, + // Reads the roll-up itself: what a predicate update whose patch cannot move it reads. + { name: 'total_cap', type: 'script', severity: 'error', message: 'budget total over 100', condition: "record.tag == 'cap' && record.bud.total > 100" }, + ], + } as any); + }); + + const bud = (id: string) => storeFor('bud').get(id); + const lines = (budId: string) => [...storeFor('bud_line').values()].filter((r) => r.bud === budId); + + async function refusalOf(write: Promise): Promise { + try { await write; } catch (err) { return err; } + throw new Error('expected the write to be refused'); + } + + function expectRuleRefusal(err: unknown, message: string): void { + expect(err).toBeInstanceOf(ValidationError); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mapDataError(err).status).toBe(400); + expect((err as ValidationError).fields.map((f) => f.message).join(' | ')).toContain(message); + } + + for (const [tag, message] of [['rem', 'line over the remaining budget'], ['head', 'line over the budget headroom']] as const) { + it(`one by one (the reference answer), ${tag}: the third line reads the field over the total the first two moved, and is refused`, async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + await engine.insert('bud_line', { bud: p.id, amount: 40, tag, note: 'n' }); + await engine.insert('bud_line', { bud: p.id, amount: 40, tag, note: 'n' }); + expectRuleRefusal(await refusalOf(engine.insert('bud_line', { bud: p.id, amount: 40, tag, note: 'n' })), message); + expect(bud(p.id).total).toBe(80); + }); + + it(`multi-row insert, ${tag}: three lines in one call, the third is refused as one by one refuses it, and nothing is written`, async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + expectRuleRefusal(await refusalOf(engine.insert('bud_line', [1, 2, 3].map(() => ({ bud: p.id, amount: 40, tag, note: 'n' })))), message); + expect(lines(p.id)).toHaveLength(0); + expect(bud(p.id).total).toBe(0); + }); + } + + it('multi-row insert, under the line: three lines that fit the budget are all admitted, and the roll-up and its calculated fields land as one by one lands them', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + const ids = await engine.insert('bud_line', [1, 2, 3].map((n) => ({ bud: p.id, amount: 30, tag: n === 3 ? 'head' : 'rem', note: 'n' }))); + expect(ids).toHaveLength(3); + expect(bud(p.id)).toMatchObject({ total: 90, headroom: 10, peak: 90 }); + }); + + it('one by one (the reference answer): a field-level parent. predicate reading the header\'s calculated field requires the note on the third line', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + await engine.insert('bud_line', { bud: p.id, amount: 40, tag: 'x' }); + await engine.insert('bud_line', { bud: p.id, amount: 40, tag: 'x' }); + const err = await refusalOf(engine.insert('bud_line', { bud: p.id, amount: 1, tag: 'x' })); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mapDataError(err).status).toBe(400); + expect((err as ValidationError).fields.map((f) => f.field)).toContain('note'); + }); + + it('multi-row insert: the header the parent. predicate reads carries the calculated field over the moved total, so the third line needs the note too', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + const err = await refusalOf(engine.insert('bud_line', [{ bud: p.id, amount: 40, tag: 'x' }, { bud: p.id, amount: 40, tag: 'x' }, { bud: p.id, amount: 1, tag: 'x' }])); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mapDataError(err).status).toBe(400); + expect((err as ValidationError).fields.map((f) => f.field)).toContain('note'); + expect(lines(p.id)).toHaveLength(0); + }); + + it('one by one (the reference answer): a high-water mark reads every total so far, so the third line reads 80 and is refused', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + await engine.insert('bud_line', { bud: p.id, amount: 80, tag: 'x', note: 'n' }); + await engine.insert('bud_line', { bud: p.id, amount: -60, tag: 'x', note: 'n' }); + expect(bud(p.id)).toMatchObject({ total: 20, peak: 80 }); + expectRuleRefusal(await refusalOf(engine.insert('bud_line', { bud: p.id, amount: 1, tag: 'peak', note: 'n' })), 'budget peak at 50 or more'); + }); + + it('multi-row insert: the parent\'s stored image is carried from row to row as each recompute stores it, so the third line reads the peak 80 and is refused', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + // Computed once over the stored row with the moved total (20), the peak would read 20 and the rule admit the line. + expectRuleRefusal(await refusalOf(engine.insert('bud_line', [ + { bud: p.id, amount: 80, tag: 'x', note: 'n' }, { bud: p.id, amount: -60, tag: 'x', note: 'n' }, { bud: p.id, amount: 1, tag: 'peak', note: 'n' }, + ])), 'budget peak at 50 or more'); + expect(lines(p.id)).toHaveLength(0); + }); + + it('CONTROL: a multi-row insert no rule of which reads the parent reads no parent row for the calculated fields over its roll-up', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + const parentReads = (from: number) => log.slice(from).filter((e) => e.op === 'find' && e.object === 'bud' && e.ast?.where?.id?.$in); + let start = log.length; + await engine.insert('bud_memo', [{ bud: p.id, amount: 1 }, { bud: p.id, amount: 2 }]); + expect(parentReads(start)).toEqual([]); + // The probe sees such a read: an insert whose rules read the parent makes them. + start = log.length; + await engine.insert('bud_line', [{ bud: p.id, amount: 1, tag: 'x', note: 'n' }, { bud: p.id, amount: 2, tag: 'x', note: 'n' }]); + expect(parentReads(start).length).toBeGreaterThan(0); + }); +}); + +describe('[#34821] a predicate update whose patch cannot move a roll-up its rules read reads the stored value, as the by-id update does, and leaves a trace where it stands one down', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + let log: ReturnType['log']; + + beforeEach(async () => { + engine = new ObjectQL(); + const d = makeDriver(); + storeFor = d.storeFor; + log = d.log; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject({ + name: 'cap_head', + fields: { + name: { type: 'text' }, + total: { type: 'summary', summaryOperations: { object: 'cap_line', field: 'amount', function: 'sum' } }, + first_day: { type: 'summary', summaryOperations: { object: 'cap_line', field: 'day', function: 'min' } }, + }, + } as any); + engine.registry.registerObject({ + name: 'cap_line', + fields: { + amount: { type: 'number' }, + day: { type: 'date' }, + tag: { type: 'text' }, + head: { type: 'master_detail', reference: 'cap_head' }, + }, + validations: [ + { name: 'total_cap', type: 'script', severity: 'error', message: 'head total over 100', condition: "record.tag == 'cap' && record.head.total > 100" }, + { name: 'day_set', type: 'script', severity: 'error', message: 'head first day is set', condition: "record.tag == 'day' && record.head.first_day == null" }, + ], + } as any); + }); + + const head = (id: string) => storeFor('cap_head').get(id); + + async function refusalOf(write: Promise): Promise { + try { await write; } catch (err) { return err; } + throw new Error('expected the write to be refused'); + } + + /** Two lines of 40 under one head, the stored total then left stale at 150 (the children sum to 80). */ + async function seedStale() { + const p = await engine.insert('cap_head', { name: 'H' }); + const [a] = await engine.insert('cap_line', [{ head: p.id, amount: 40, tag: 'x' }, { head: p.id, amount: 40, tag: 'x' }]); + storeFor('cap_head').set(p.id, { ...head(p.id), total: 150 }); + return { p, a }; + } + + it('the by-id form (the reference answer): a patch that cannot move the total reads the stored 150, and is refused', async () => { + const { a } = await seedStale(); + const err = await refusalOf(engine.update('cap_line', { id: a.id, tag: 'cap' })); + expect(err).toBeInstanceOf(ValidationError); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mapDataError(err).status).toBe(400); + }); + + it('predicate update: its first row reads the stored 150 as the by-id form does, not a base aggregated from the children, and nothing is aggregated before the write', async () => { + const { p } = await seedStale(); + const real = engine.aggregate.bind(engine); + (engine as any).aggregate = async (object: string, query: any, options?: any) => { log.push({ op: 'find', object: `aggregate:${object}`, ast: query }); return real(object, query, options); }; + const start = log.length; + // Folded over the base (80), both rows would be admitted. + const err = await refusalOf(engine.update('cap_line', { tag: 'cap' }, { where: { head: p.id }, multi: true })); + expect(err).toBeInstanceOf(ValidationError); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mapDataError(err).status).toBe(400); + expect((err as ValidationError).fields.map((f) => f.message).join(' | ')).toContain('head total over 100'); + expect(log.slice(start).filter((e) => e.object.startsWith('aggregate:'))).toEqual([]); + expect([...storeFor('cap_line').values()].map((r) => r.tag)).toEqual(['x', 'x']); + }); + + it('CONTROL: a patch that can move the total is still folded', async () => { + const { p } = await seedStale(); + // Over the base: the first row reads 80 (admitted, total then 90), the second 90. + expect(await engine.update('cap_line', { tag: 'cap', amount: 45 }, { where: { head: p.id }, multi: true })).toBe(2); + expect(head(p.id).total).toBe(90); + }); + + it('a roll-up the fold stands down leaves one debug line naming it and why', async () => { + const p = await engine.insert('cap_head', { name: 'H' }); + await engine.insert('cap_line', [{ head: p.id, amount: 1, day: '2026-01-02', tag: 'x' }, { head: p.id, amount: 2, day: '2026-01-03', tag: 'x' }]); + const debug: unknown[][] = []; + const logger = (engine as any).logger; + const realDebug = logger.debug.bind(logger); + logger.debug = (...args: unknown[]) => { debug.push(args); return realDebug(...args); }; + expect(await engine.update('cap_line', { tag: 'day', day: '2026-01-01' }, { where: { head: p.id }, multi: true })).toBe(2); + const traces = debug.filter(([message]) => String(message).startsWith('Roll-up left unfolded')); + expect(traces).toEqual([[expect.any(String), { object: 'cap_line', parentObject: 'cap_head', field: 'first_day', reason: 'not_a_number' }]]); + }); +}); From ebc2b344825643e80d9e902f7970e66dee1fce25 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 05:39:40 +0000 Subject: [PATCH 2/8] chore(changeset): objectql roll-up fold follow-ups Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .changeset/34821-rollup-fold-followups.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .changeset/34821-rollup-fold-followups.md diff --git a/.changeset/34821-rollup-fold-followups.md b/.changeset/34821-rollup-fold-followups.md new file mode 100644 index 00000000000..7bacce2f109 --- /dev/null +++ b/.changeset/34821-rollup-fold-followups.md @@ -0,0 +1,16 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): a multi-row insert judges a rule reading a parent field calculated from a roll-up as one-by-one inserts judge it + +Clause-②: no +Metadata-protocol: none + +A multi-row insert already moved a parent roll-up (`count`, `sum`, `min`, `max`) by the rows of the batch admitted before each row, for a rule reading it through a reference or a field-level `parent.` predicate. A formula or stored computed field of that parent built on the roll-up (`remaining = budget - total`) still read its stored value, so "a line may not exceed the remaining budget" admitted a third line of 40 against a budget of 100 in one call and refused it one at a time. The write now computes those fields over the moved roll-ups, as a predicate update already did, carrying the parent's stored image from row to row as each recompute stores it. Only a batch with a rule reading that parent pays the one extra read of its parent rows. + +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. + +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`). + +The multi-row insert preview (`validate` with `mode: 'insert'`) does not yet compute these parent fields over the moved roll-ups. From e4710f140a2cefc27e8101e330f63ab8b97fdb6d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 06:29:00 +0000 Subject: [PATCH 3/8] fix(objectql)!: the multi-row insert preview computes parent formula fields over the moved roll-ups The write and its preview share one door (attachInsertSummaryDependents); the validate host carries the formula services it needs. The changeset is re-declared Clause-2 no (narrowing) with its ADR-0087 disposition. Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .changeset/34821-rollup-fold-followups.md | 13 +++++--- packages/objectql/src/engine-insert.ts | 15 ++++----- packages/objectql/src/engine-update.ts | 34 +++++++++++++++++++- packages/objectql/src/engine-validate.ts | 18 ++++++++++- packages/objectql/src/engine.ts | 6 ++++ packages/objectql/src/summary-rollup.test.ts | 20 ++++++++++++ 6 files changed, 91 insertions(+), 15 deletions(-) diff --git a/.changeset/34821-rollup-fold-followups.md b/.changeset/34821-rollup-fold-followups.md index 7bacce2f109..56c006791e7 100644 --- a/.changeset/34821-rollup-fold-followups.md +++ b/.changeset/34821-rollup-fold-followups.md @@ -2,15 +2,20 @@ '@objectstack/objectql': patch --- -fix(objectql): a multi-row insert judges a rule reading a parent field calculated from a roll-up as one-by-one inserts judge it +fix(objectql)!: a multi-row insert judges a rule reading a parent field calculated from a roll-up as one-by-one inserts judge it -Clause-②: no +Clause-②: no (narrowing) Metadata-protocol: none -A multi-row insert already moved a parent roll-up (`count`, `sum`, `min`, `max`) by the rows of the batch admitted before each row, for a rule reading it through a reference or a field-level `parent.` predicate. A formula or stored computed field of that parent built on the roll-up (`remaining = budget - total`) still read its stored value, so "a line may not exceed the remaining budget" admitted a third line of 40 against a budget of 100 in one call and refused it one at a time. The write now computes those fields over the moved roll-ups, as a predicate update already did, carrying the parent's stored image from row to row as each recompute stores it. Only a batch with a rule reading that parent pays the one extra read of its parent rows. + + +**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`). + +- 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. +- 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. 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. 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`). -The multi-row insert preview (`validate` with `mode: 'insert'`) does not yet compute these parent fields over the moved roll-ups. +The fix for a caller: insert the rows the rule refuses on their own, or split the batch so each part fits the rule. diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index de08f1bca73..44a179fa978 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -60,7 +60,7 @@ import { coerceBooleanFields, normalizeBlankTypedValues, normalizeMultiValueFiel import { emitValidationAdvisories, evaluateValidationRules, hasParentScopedRequiredWhen, preserveAuditIgnoredOnInsertWarning, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js'; import type { staticReadonlyInsertSubject } from './validation/rule-validator.js'; import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js'; -import { loadSummaryFoldDependents } from './engine-update.js'; +import { attachInsertSummaryDependents } from './engine-update.js'; import { resolveMasterDetailRelation } from './master-detail.js'; import { recordHookPayloadWrites } from './hook-write-provenance.js'; import type { HookWriteRecording } from './hook-write-provenance.js'; @@ -1356,14 +1356,11 @@ export class InsertFacet { // this batch reads (a related binding or a header): an insert no rule // reads a parent of pays nothing here. if (batchSummaries) { - const readParents = new Set(); - for (let i = 0; i < rows.length; i++) { - if (rowErrors[i] !== undefined) continue; - for (const entry of Object.values(insertRelatedForRow(rows[i]) ?? {})) if (entry?.row) readParents.add(entry.object); - if (insertParentMaster && insertParentForRow?.(rows[i])) readParents.add(insertParentMaster); - } - const folded = readParents.size > 0 ? batchSummaries.foldedSummaries(rows, readParents) : undefined; - if (folded && folded.size > 0) batchSummaries.setDependents(await loadSummaryFoldDependents(this, folded, opCtx.context)); + await attachInsertSummaryDependents( + this, batchSummaries, rows, insertRelatedForRow, insertParentMaster, + insertParentForRow ? (i) => insertParentForRow(rows[i]) : undefined, + opCtx.context, (i) => rowErrors[i] !== undefined, + ); } // [#18783] The subject's effective object permissions, for an option // gated on `current_user.can(…)`: ONE resolution for the whole batch, diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 948b825bb6d..758b9dff503 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -62,7 +62,8 @@ import { recordHookPayloadWrites } from './hook-write-provenance.js'; import { dispatchHooksExplainingWithheldReadonly } from './hook-withheld-readonly-fault.js'; import { resolveMasterDetailRelation } from './master-detail.js'; import { createPredicateUpdateSummaryFold, loadPredicateUpdateSummaryBases, summaryPatchCanMove } from './summary-batch-accumulation.js'; -import type { SummaryDependents, SummaryFoldStandDownSink } from './summary-batch-accumulation.js'; +import type { BatchSummaryAccumulator, SummaryDependents, SummaryFoldStandDownSink } from './summary-batch-accumulation.js'; +import type { RelatedRecordBinding } from './validation/rule-validator.js'; import { SUMMARY_GROUPED_AGGREGATE_CHUNK } from './summary-aggregate.js'; import { declaredColumnSet, rowsWithDeclaredColumnsOnly, selectedStoredColumns, storedColumnsLeftUnwritten, withDeclaredColumnsOnly, withSelectedColumnsAnswered } from './declared-read-columns.js'; import { externalPredicateWriteRefusal, isExternalDriverFloor } from './external-driver-floor.js'; @@ -2523,6 +2524,37 @@ export class UpdateFacet { * ({@link applyFormulaPlan}). An object no such field reads a folded roll-up * of reads nothing. */ +/** + * [#34821] Hand a multi-row insert's accumulator what computes its parents' + * fields calculated from the roll-ups it moves ({@link loadSummaryFoldDependents}), + * for the parents a rule of the batch reads: a related row bound for a row + * (`relatedFor`) or the master-detail header (`master`, through `headerFor`). + * An insert no rule of which reads a parent reads nothing here. One door for + * the write (`insert()`) and its preview (`validate()`, mode insert), so the + * preview judges the batch the way the write does. `skip(i)` names a row the + * door already refused. + */ +export async function attachInsertSummaryDependents( + host: Parameters[0], + accumulator: BatchSummaryAccumulator, + rows: readonly Record[], + relatedFor: (row: Record) => RelatedRecordBinding | undefined, + master: string | undefined, + headerFor: ((i: number) => unknown) | undefined, + context: Parameters[2], + skip: (i: number) => boolean = () => false, +): Promise { + const readParents = new Set(); + for (let i = 0; i < rows.length; i++) { + if (skip(i)) continue; + for (const entry of Object.values(relatedFor(rows[i]!) ?? {})) if (entry?.row) readParents.add(entry.object); + if (master && headerFor?.(i)) readParents.add(master); + } + if (readParents.size === 0) return; + const folded = accumulator.foldedSummaries(rows, readParents); + if (folded.size > 0) accumulator.setDependents(await loadSummaryFoldDependents(host, folded, context)); +} + export async function loadSummaryFoldDependents( host: Pick, folded: Map; parentIds: Set }>, diff --git a/packages/objectql/src/engine-validate.ts b/packages/objectql/src/engine-validate.ts index 3725a92a823..52b029c9a3b 100644 --- a/packages/objectql/src/engine-validate.ts +++ b/packages/objectql/src/engine-validate.ts @@ -50,6 +50,7 @@ import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; import { validateRecordInScope, normalizeBlankTypedValues, normalizeNumericStringValues, ValidationError, valueShapeStrictEffective, mediaStrictEffective } from './validation/record-validator.js'; import { evaluateValidationRules, hasParentScopedRequiredWhen, stripReadonlyFields, stripRuntimeOwnedFields } from './validation/rule-validator.js'; import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js'; +import { attachInsertSummaryDependents } from './engine-update.js'; import { formulaValuesFor } from './engine-top-level.js'; import { resolveMasterDetailRelation } from './master-detail.js'; import { assertRecordCurrencyCodes, followParentCurrencyCodes, parentCodeFieldServingOf, recordCurrencyPairs, RecordCurrencyCodeRequiredError, touchesRecordCurrency } from './validation/record-currency-code.js'; @@ -98,6 +99,12 @@ export interface ValidateHost { resolvePredicateRelated: ObjectQL['resolvePredicateRelated']; resolveOptionPermissions: ObjectQL['resolveOptionPermissions']; getSummaryDescriptors: ObjectQL['getSummaryDescriptors']; + // [#34821] What computes a parent's fields calculated from the roll-ups a multi-row insert moves. + readonly facade: ObjectQL; + getSchema: ObjectQL['getSchema']; + resolveFormulaPermissions: ObjectQL['resolveFormulaPermissions']; + resolveFormulaRelated: ObjectQL['resolveFormulaRelated']; + formulaOptionLabels: ObjectQL['formulaOptionLabels']; assertReferencesResolve: ObjectQL['assertReferencesResolve']; previewHomeAmounts: ObjectQL['previewHomeAmounts']; homeAmountServing: ObjectQL['homeAmountServing']; @@ -108,7 +115,7 @@ export interface ValidateHost { /** The body of `ObjectQL#validate`; the method's docblock there is its contract. */ export async function validate( - this: Pick, + this: Pick, object: string, data: Record | Record[], options?: { @@ -520,6 +527,15 @@ export async function validate( const previewParentMaster = batchSummaries && previewParents ? resolveMasterDetailRelation(schemaForValidation as any)?.master : undefined; + // [#34821] And the parent's formula and stored computed fields calculated + // from a moved roll-up, through the write's own door. + if (batchSummaries) { + await attachInsertSummaryDependents( + this, batchSummaries, judgedViews, previewRelatedForRow, previewParentMaster, + previewParents ? (i) => previewParents.parents[i] : undefined, + options?.context, (i) => wallRefusalOf(i) !== undefined, + ); + } // [#26684] Judged one row after another, as the write's validation loop // judges them: a row's admission (the reference check below) is awaited diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index df822b86d9f..a8532f590a4 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4667,6 +4667,12 @@ export class ObjectQL implements IObjectQLEngine { resolvePredicateRelated: (...a) => this.resolvePredicateRelated(...a), resolveOptionPermissions: (...a) => this.resolveOptionPermissions(...a), getSummaryDescriptors: (...a) => this.getSummaryDescriptors(...a), + // [#34821] The parent fields calculated from the roll-ups a multi-row insert preview moves. + facade: this, + getSchema: (...a) => this.getSchema(...a), + resolveFormulaPermissions: (...a) => this.resolveFormulaPermissions(...a), + resolveFormulaRelated: (...a) => this.resolveFormulaRelated(...a), + formulaOptionLabels: (...a) => this.formulaOptionLabels(...a), assertReferencesResolve: (...a) => this.assertReferencesResolve(...a), previewHomeAmounts: (...a) => this.previewHomeAmounts(...a), homeAmountServing: (...a) => this.homeAmountServing(...a), diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 50887eb2bfb..431d5dbcf68 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -1947,6 +1947,26 @@ describe('[#34821] a multi-row insert judges a rule reading a parent field calcu expect(bud(p.id)).toMatchObject({ total: 90, headroom: 10, peak: 90 }); }); + it('multi-row insert preview: three lines of 40 under a budget of 100, the preview refuses the third as the write does', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + const batch = [1, 2, 3].map(() => ({ bud: p.id, amount: 40, tag: 'rem', note: 'n' })); + const preview = await engine.validate('bud_line', batch, { mode: 'insert' }); + expect(preview.valid).toBe(false); + expect(preview.results!.map((r) => r.valid)).toEqual([true, true, false]); + expect(preview.results![2]!.errors.map((e) => e.message).join(' | ')).toContain('line over the remaining budget'); + expectRuleRefusal(await refusalOf(engine.insert('bud_line', batch)), 'line over the remaining budget'); + expect(lines(p.id)).toHaveLength(0); + }); + + it('multi-row insert preview, under the line: three lines of 30 are all valid, and the write admits them', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + const batch = [1, 2, 3].map(() => ({ bud: p.id, amount: 30, tag: 'rem', note: 'n' })); + const preview = await engine.validate('bud_line', batch, { mode: 'insert' }); + expect(preview.results!.map((r) => r.valid)).toEqual([true, true, true]); + expect(await engine.insert('bud_line', batch)).toHaveLength(3); + expect(bud(p.id).total).toBe(90); + }); + it('one by one (the reference answer): a field-level parent. predicate reading the header\'s calculated field requires the note on the third line', async () => { const p = await engine.insert('bud', { name: 'B', budget: 100 }); await engine.insert('bud_line', { bud: p.id, amount: 40, tag: 'x' }); From 90eaeed9ca084e406e392ba76f0206800c2b832c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 07:03:12 +0000 Subject: [PATCH 4/8] fix(objectql): keep the validate host's new members within the facade's line ceiling Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- packages/objectql/src/engine.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index a8532f590a4..b8777659c23 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4667,12 +4667,7 @@ export class ObjectQL implements IObjectQLEngine { resolvePredicateRelated: (...a) => this.resolvePredicateRelated(...a), resolveOptionPermissions: (...a) => this.resolveOptionPermissions(...a), getSummaryDescriptors: (...a) => this.getSummaryDescriptors(...a), - // [#34821] The parent fields calculated from the roll-ups a multi-row insert preview moves. - facade: this, - getSchema: (...a) => this.getSchema(...a), - resolveFormulaPermissions: (...a) => this.resolveFormulaPermissions(...a), - resolveFormulaRelated: (...a) => this.resolveFormulaRelated(...a), - formulaOptionLabels: (...a) => this.formulaOptionLabels(...a), + facade: this, getSchema: (...a) => this.getSchema(...a), resolveFormulaPermissions: (...a) => this.resolveFormulaPermissions(...a), resolveFormulaRelated: (...a) => this.resolveFormulaRelated(...a), formulaOptionLabels: (...a) => this.formulaOptionLabels(...a), // [#34821] assertReferencesResolve: (...a) => this.assertReferencesResolve(...a), previewHomeAmounts: (...a) => this.previewHomeAmounts(...a), homeAmountServing: (...a) => this.homeAmountServing(...a), From 6169c1ed8dbba450fb81429e6dc520bb422de872 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:00:15 +0000 Subject: [PATCH 5/8] docs(changeset): drop the 34465 note's "bulk create does not yet" parenthetical DELIBERATE CORRECTION: this branch makes a multi-row insert compute a parent field calculated from a roll-up over the moved values, so the pending note's parenthetical is false once it lands. Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- .changeset/34465-predicate-update-parent-summary-rule.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/34465-predicate-update-parent-summary-rule.md b/.changeset/34465-predicate-update-parent-summary-rule.md index bf088393fd5..428f9cc692f 100644 --- a/.changeset/34465-predicate-update-parent-summary-rule.md +++ b/.changeset/34465-predicate-update-parent-summary-rule.md @@ -9,7 +9,7 @@ Metadata-protocol: none -**BREAKING** for a predicate update (`update(object, patch, { where, multi: true })`, a flow `update_record` step with `multi: true`) of a child object whose validation rule reads a roll-up `summary` of a parent one hop through a reference (`record.inv.primaries > 0`), or whose field-level `requiredWhen` reads one on `parent` (`parent.line_count >= 3`), or that reads a `formula` or stored computed field of the parent calculated from one (`record.project.remaining`, `remaining = budget - spent`). A bulk create and a bulk update already equal one-by-one writes for a rule reading the summary itself (a bulk create does not yet for a rule reading a parent field calculated from one: its accumulator moves the summary key alone, #34821); this extends that to the update that selects its rows by a filter, calculated parent fields included. +**BREAKING** for a predicate update (`update(object, patch, { where, multi: true })`, a flow `update_record` step with `multi: true`) of a child object whose validation rule reads a roll-up `summary` of a parent one hop through a reference (`record.inv.primaries > 0`), or whose field-level `requiredWhen` reads one on `parent` (`parent.line_count >= 3`), or that reads a `formula` or stored computed field of the parent calculated from one (`record.project.remaining`, `remaining = budget - spent`). A bulk create and a bulk update already equal one-by-one writes for a rule reading the summary itself; this extends that to the update that selects its rows by a filter, calculated parent fields included. - FROM: the matched rows' related parents and master-detail headers were read once, and every row judged the summary as it stood before the update: "one primary line per invoice" (`record.is_primary == true && record.inv.primaries > 0`) refused the second of two lines made primary one by one, and admitted both made primary by one predicate update. - TO: each matched row judges the summary as the rows judged before it leave it, for `count`, `sum`, `min`, `max` and `avg`, a row moving to another parent included: the base is read in the database (every child as stored for `count` / `sum` / `avg`, the children outside the matched set for `min` / `max`, one grouped aggregate per summary a rule reads) and the matched rows are folded in memory. A parent field calculated from a folded summary is computed again over the parent with the folded value. The update is refused with `VALIDATION_FAILED` and writes nothing, as it does for any refused row. Only an object with such a rule, on an update matching more than one row, reads the base (and, when a calculated field reads a folded summary, the parents' stored rows once). From 3b3cd84b14b1d5deef3f27b1a087c1704451bb7f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:33:11 +0000 Subject: [PATCH 6/8] 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 --- .changeset/34821-rollup-fold-followups.md | 6 +- content/docs/data-modeling/fields.mdx | 20 ++- .../src/engine-master-detail-related.ts | 9 +- packages/objectql/src/engine-validate.ts | 3 +- packages/objectql/src/engine.ts | 2 +- .../src/summary-batch-accumulation.test.ts | 14 ++ .../src/summary-batch-accumulation.ts | 62 ++++++-- packages/objectql/src/summary-rollup.test.ts | 139 +++++++++++++++++- 8 files changed, 228 insertions(+), 27 deletions(-) diff --git a/.changeset/34821-rollup-fold-followups.md b/.changeset/34821-rollup-fold-followups.md index 56c006791e7..60d1380ba91 100644 --- a/.changeset/34821-rollup-fold-followups.md +++ b/.changeset/34821-rollup-fold-followups.md @@ -12,10 +12,12 @@ Metadata-protocol: none **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`). - 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. -- 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. +- 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. +- 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. +- 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. 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. -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`). +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`). The fix for a caller: insert the rows the rule refuses on their own, or split the batch so each part fits the rule. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 25236373f8e..793205e1896 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -463,10 +463,19 @@ refuse is not counted. A detail object's `requiredWhen` that reads the summary on `parent` (the master-detail header, for example `requiredWhen: 'parent.line_count >= 2'`) reads it the same way, so the third of three bare lines in one batch is refused as the third single insert is. +A rule that reads a formula or a stored computed field of the parent calculated +from the summary (`record.budget.remaining`, `parent.headroom < 50`) reads it +calculated over the summary as the earlier rows moved it, so a row is refused, +or admitted, as the same row inserted on its own after them would be. This holds for `count`, and for `sum`, `min` and `max` over number values. An `avg` summary, a `sum`/`min`/`max` meeting a value that -is not a number, and a summary whose `filter` reads a dotted path through -another reference keep reading the stored value, as they did before. +is not a number, and a summary whose `filter` reads through another reference, +as a dotted path or in the nested form `{ account: { status: 'x' } }`, keep +reading the stored value, as they did before; a field calculated from one of +them and from a summary that moves reads the first as stored. A preview of the +batch (`validate` in insert mode) judges each row the same way, except that a +column of the master-detail header the caller is not served reads as empty at +every row. An import's **dry run** previews its create rows in the batches the import writes them in (200 rows each) and refuses the rows the import refuses, with 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 reading a formula or stored computed field of the parent calculated from it, read it as the matched rows judged before leave it, for every summary function, `avg` included, and a row that moves to another parent leaves the old one and -joins the new one. If any row is refused, none is written. Three cases keep -reading the stored value for every parent the update reads that summary for: a +joins the new one. If any row is refused, none is written. Four cases keep +reading the stored value for every parent the update reads that summary for, +as a by-id update reads it: a summary the patch cannot move (it writes neither +the reference to the parent, nor the summed field, nor a field the summary's +`filter` reads, as a key or as a `{ $field }` comparand), a summary whose `filter` reads through another reference, as a dotted path or in the nested form `{ account: { status: 'x' } }` (or one the in-memory filter cannot evaluate), a summary meeting a value that is not a number, and a `min` / `max` diff --git a/packages/objectql/src/engine-master-detail-related.ts b/packages/objectql/src/engine-master-detail-related.ts index cb7e62376cb..715919f5ed1 100644 --- a/packages/objectql/src/engine-master-detail-related.ts +++ b/packages/objectql/src/engine-master-detail-related.ts @@ -289,7 +289,9 @@ export async function settleMasterDetailLanding( * is judged as empty: the header is materialised over the master's declared * fields after the columns are kept, so such a column reads `null`. So the * verdict never depends on a header value the caller could not have read in - * full. + * full. [#34821] `servedColumns[i]` names the columns kept for `parents[i]`: + * a multi-row preview moves and computes the batch's roll-ups onto those + * only, so a withheld column reads `null` at every row. */ export async function resolvePreviewParents( this: Pick, @@ -300,6 +302,7 @@ export async function resolvePreviewParents( ): Promise<{ parents: Array | null>; previousParents: Array | null | undefined>; + servedColumns: Array | null>; }> { const rel = resolveMasterDetailRelation(schema as any); const landingIds = views.map((view) => (rel ? masterIdOf(rel.fk, null, view) : undefined)); @@ -318,6 +321,8 @@ export async function resolvePreviewParents( priorIds.forEach((id, i) => { if (repoints[i]) ids.add(String(id)); }); const headers = new Map>(); + /** [#34821] Header id → the columns kept: what a batch overlay may move or compute onto. */ + const keptColumns = new Map>(); // [#24358] ⛔ A stored-metadata-body header is never read here either, as // the write's own header read never reads one: every header binds unbound. if (rel && ids.size > 0 && !isStoredMetadataBodyObject(rel.master)) { @@ -351,6 +356,7 @@ export async function resolvePreviewParents( } } headers.set(id, this.materializeParentHeader(rel.master, kept)); + keptColumns.set(id, new Set(Object.keys(kept))); } } } @@ -358,6 +364,7 @@ export async function resolvePreviewParents( return { parents: landingIds.map(headerOf), previousParents: priorIds.map((id, i) => (priorUnknown[i] ? null : repoints[i] ? headerOf(id) : undefined)), + servedColumns: landingIds.map((id) => (id == null ? null : (keptColumns.get(String(id)) ?? null))), }; } diff --git a/packages/objectql/src/engine-validate.ts b/packages/objectql/src/engine-validate.ts index 52b029c9a3b..199f3143e76 100644 --- a/packages/objectql/src/engine-validate.ts +++ b/packages/objectql/src/engine-validate.ts @@ -651,7 +651,8 @@ export async function validate( // [#22474] The header the write binds: the insert's // `insertParentForRow`, the update's landing header and, for a // repoint, `roWhenPreviousParent`. - parent: previewParentMaster ? batchSummaries!.overlayRow(previewParentMaster, previewParents?.parents[i]) : previewParents?.parents[i], + // [#34821] Onto the columns the caller was served only (`servedColumns`). + parent: previewParentMaster ? batchSummaries!.overlayRow(previewParentMaster, previewParents?.parents[i], previewParents?.servedColumns[i] ?? new Set()) : previewParents?.parents[i], previousParent: previewParents?.previousParents[i], related: batchSummaries ? batchSummaries.overlay(previewRelatedForRow(judgedViews[i])) : previewRelatedForRow(judgedViews[i]), permissions: previewPermissionsFor(row), diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index b8777659c23..853f053d8f4 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -2799,7 +2799,7 @@ export class ObjectQL implements IObjectQLEngine { context: ExecutionContext | undefined, ): Promise<{ parents: Array | null>; - previousParents: Array | null | undefined>; + previousParents: Array | null | undefined>; servedColumns: Array | null>; }> { // [#25522 cut 14] The body moved to `engine-master-detail-related.ts`, its docblock with it (see `MasterDetailRelatedHost`). const readLogger = () => this.logger; diff --git a/packages/objectql/src/summary-batch-accumulation.test.ts b/packages/objectql/src/summary-batch-accumulation.test.ts index 92bd923d438..aea4968bf5e 100644 --- a/packages/objectql/src/summary-batch-accumulation.test.ts +++ b/packages/objectql/src/summary-batch-accumulation.test.ts @@ -405,6 +405,20 @@ describe('[#34821] summaryPatchCanMove — a roll-up a predicate update\'s patch it('a filter holding a condition whose fields it cannot read is taken to move', () => { expect(summaryPatchCanMove(desc({ fn: 'count', filter: { $expr: { $gt: ['$amount', 1] } } }), { kind: 'b' })).toBe(true); }); + + it('moves when the patch writes a field the filter reads as a { $field } comparand or an addDays offset, and not otherwise', () => { + const late = desc({ fn: 'count', summaryField: 'n', filter: { closed_day: { $gt: { $field: 'due_day' } } } }); + expect(summaryPatchCanMove(late, { due_day: 1 })).toBe(true); + expect(summaryPatchCanMove(late, { closed_day: 1 })).toBe(true); + const shifted = desc({ fn: 'count', summaryField: 'n', filter: { $or: [{ closed_on: { $lt: { $field: 'due_on', addDays: { $field: 'grace' } } } }] } }); + expect(summaryPatchCanMove(shifted, { grace: 2 })).toBe(true); + expect(summaryPatchCanMove(shifted, { due_on: '2026-01-01' })).toBe(true); + // CONTROL: a patch writing none of the filter's fields, as key or as referent. + expect(summaryPatchCanMove(late, { other: 1 })).toBe(false); + expect(summaryPatchCanMove(shifted, { other: 1 })).toBe(false); + // A referent naming no field by a string is a condition this cannot read. + expect(summaryPatchCanMove(desc({ fn: 'count', filter: { closed_day: { $gt: { $field: 7 } } } }), { other: 1 })).toBe(true); + }); }); describe('[#34821] each stand-down of a predicate update\'s fold is reported once, naming the roll-up and why', () => { diff --git a/packages/objectql/src/summary-batch-accumulation.ts b/packages/objectql/src/summary-batch-accumulation.ts index a0228b58a80..0fb68dc79f6 100644 --- a/packages/objectql/src/summary-batch-accumulation.ts +++ b/packages/objectql/src/summary-batch-accumulation.ts @@ -92,8 +92,15 @@ export interface BatchSummaryAccumulator { * row and not as a related binding. A copy; `row` itself is never mutated. * A row no admitted row moves, and an unbound header (`null` / * `undefined`, the fail-closed signal), are returned as they are. + * + * [#34821] `visible`, when given, names the only columns of `row` the + * reader was served (the insert preview's caller-visible header): no other + * column is moved or computed onto the copy, so it reads as served — the + * same at every row — and decides nothing it did not decide at the first. + * A roll-up the reader was not served is still moved, from the stored + * parent, for the visible fields calculated from it. */ - overlayRow | null | undefined>(object: string, row: R): R; + overlayRow | null | undefined>(object: string, row: R, visible?: ReadonlySet): R; /** Count `row` in. Call it only once the row's rules have admitted it. */ accept(row: Record): void; /** @@ -248,18 +255,19 @@ export function createBatchSummaryAccumulator( /** * The summary values the admitted rows move parent `parentId` (a row of * `object`) to, or `undefined` when none moves. Each is moved from the value - * `row` carries, or, for a roll-up `row` was not handed (and for no row), - * from the stored parent the dependents read: both are read before the - * batch writes anything. + * `row` carries, or, for a roll-up `row` was not handed or not served + * (`visible`), and for no row, from the stored parent the dependents read: + * both are read before the batch writes anything. */ - const movedOf = (object: string, parentId: string, row?: Record): Record | undefined => { + const movedOf = (object: string, parentId: string, row?: Record, visible?: ReadonlySet): Record | undefined => { const stored = dependents?.stored?.(object, parentId); let out: Record | undefined; for (const [desc, byParent] of deltas) { if (dropped.has(desc) || desc.parentObject !== object) continue; const delta = byParent.get(parentId); if (!delta) continue; - const from = row && desc.summaryField in row ? row : stored && desc.summaryField in stored ? stored : undefined; + const carried = row !== undefined && desc.summaryField in row && (!visible || visible.has(desc.summaryField)); + const from = carried ? row : stored && desc.summaryField in stored ? stored : undefined; if (!from) continue; const value = moved(desc, from[desc.summaryField], delta); if (value === undefined) continue; @@ -269,14 +277,16 @@ export function createBatchSummaryAccumulator( }; /** A copy of `row` (a stored row of `object`) with every summary the admitted rows move, or `undefined` when none moves. */ - const patchRow = (object: string, row: Record): Record | undefined => { + const patchRow = (object: string, row: Record, visible?: ReadonlySet): Record | undefined => { const parentId = singleId(row.id); if (parentId === undefined) return undefined; - const values = movedOf(object, parentId, row); + const values = movedOf(object, parentId, row, visible); if (!values) return undefined; + /** A column the reader was handed, and (with `visible`) served. */ + const served = (field: string): boolean => field in row && (!visible || visible.has(field)); let patched: Record | undefined; for (const [field, value] of Object.entries(values)) { - if (!(field in row)) continue; // the reader was not handed this roll-up + if (!served(field)) continue; // the reader was not handed this roll-up patched ??= { ...row }; patched[field] = value; } @@ -286,7 +296,7 @@ export function createBatchSummaryAccumulator( const computed = dependents?.(object, parentId, values); if (computed) { for (const [field, value] of Object.entries(computed)) { - if (!(field in row)) continue; + if (!served(field)) continue; patched ??= { ...row }; patched[field] = value; } @@ -309,9 +319,9 @@ export function createBatchSummaryAccumulator( return out ?? binding; }; - const overlayRow = | null | undefined>(object: string, row: R): R => { + const overlayRow = | null | undefined>(object: string, row: R, visible?: ReadonlySet): R => { if (!row || deltas.size === 0) return row; - return (patchRow(object, row) as R | undefined) ?? row; + return (patchRow(object, row, visible) as R | undefined) ?? row; }; const foldedSummaries = (rows: readonly unknown[], objects: ReadonlySet): Map; parentIds: Set }> => { @@ -389,7 +399,27 @@ export type SummaryFoldStandDown = 'filter' | 'not_a_number' | 'exclusion_budget /** [#34821] Told once per roll-up a fold stands down, with why: the trace that makes the published limit observable. */ export type SummaryFoldStandDownSink = (desc: SummaryDescriptor, reason: SummaryFoldStandDown) => void; -/** The fields a filter names, or `undefined` when it holds a condition this cannot read the fields of. */ +/** + * [#34821] Add to `into` every field a condition's value reads as a + * `{ $field }` comparand, an `addDays: { $field }` offset included (the + * fold's walker resolves both against the row); `false` when one names no + * field by a string. + */ +function addFieldReferents(value: unknown, into: Set): boolean { + if (Array.isArray(value)) return value.every((v) => addFieldReferents(v, into)); + if (!value || typeof value !== 'object' || value instanceof Date) return true; + for (const [key, inner] of Object.entries(value as Record)) { + if (key === '$field') { + if (typeof inner !== 'string' || inner === '') return false; + into.add(inner.split('.')[0]!); + continue; + } + if (!addFieldReferents(inner, into)) return false; + } + return true; +} + +/** The fields a filter names, as keys or as `{ $field }` referents, or `undefined` when it holds a condition this cannot read the fields of. */ function filterFieldNames(cond: unknown, into: Set): Set | undefined { if (Array.isArray(cond)) { for (const c of cond) if (!filterFieldNames(c, into)) return undefined; @@ -403,14 +433,16 @@ function filterFieldNames(cond: unknown, into: Set): Set | undef } if (key.startsWith('$')) return undefined; into.add(key.split('.')[0]!); + if (!addFieldReferents(value, into)) return undefined; } return into; } /** * [#34821] Whether a patch can move roll-up `desc` at all: it writes the - * foreign key, the source field (not a `count`'s) or a field the filter names (or a filter - * this cannot read the fields of). A patch that cannot leaves every matched + * foreign key, the source field (not a `count`'s) or a field the filter names + * (as a key, or as a `{ $field }` comparand or `addDays` offset), or holds a + * filter this cannot read the fields of. A patch that cannot leaves every matched * row's contribution where it stands, so the roll-up is not folded and its * rules read the stored value, as the by-id update reads it, at no cost: a * base aggregated from the children differs from the stored value only where diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 431d5dbcf68..5e5d72a57f8 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -20,11 +20,13 @@ function makeDriver() { // Minimal FilterCondition matcher: implicit equality, a few operators, and the // logical `$and`/`$or`/`$not` the engine emits when a summary carries a filter // (`{ $and: [{ fk: parentId }, }] }`). Enough to exercise the merge. - const checkOp = (value: any, cond: any): boolean => { + const checkOp = (value: any, cond: any, row?: any): boolean => { if (cond === null || typeof cond !== 'object' || Array.isArray(cond) || cond instanceof Date) { return value === cond; } - return Object.entries(cond).every(([op, target]: [string, any]) => { + return Object.entries(cond).every(([op, raw]: [string, any]) => { + // [#34821] A `{ $field }` comparand reads the row's own column. + const target = raw && typeof raw === 'object' && typeof raw.$field === 'string' ? row?.[raw.$field] : raw; switch (op) { case '$eq': return value === target; case '$ne': return value !== target; @@ -49,7 +51,7 @@ function makeDriver() { if (k === '$and') return (v as any[]).every((w) => matches(row, w)); if (k === '$or') return (v as any[]).some((w) => matches(row, w)); if (k === '$not') return !matches(row, v); - return checkOp(row?.[k], v); + return checkOp(row?.[k], v, row); }); }; let n = 0; @@ -2003,6 +2005,60 @@ describe('[#34821] a multi-row insert judges a rule reading a parent field calcu expect(lines(p.id)).toHaveLength(0); }); + /** + * A field-level read rule on the header, shaped like the security + * middleware's result mask (`hide` deletes the key): `userId` is not served + * `columns`. A system read is not masked. + */ + function withholdBudColumns(userId: string, columns: string[]) { + engine.registerMiddleware(async (ctx: any, next: () => Promise) => { + await next(); + if (ctx.object !== 'bud' || ctx.context?.isSystem || ctx.context?.userId !== userId) return; + if (!['find', 'findOne'].includes(ctx.operation)) return; + const hide = (r: any) => { if (r && typeof r === 'object') for (const c of columns) delete r[c]; }; + if (Array.isArray(ctx.result)) ctx.result.forEach(hide); else hide(ctx.result); + }); + } + + const noteless = (budId: string) => [{ bud: budId, amount: 40, tag: 'x' }, { bud: budId, amount: 40, tag: 'x' }, { bud: budId, amount: 1, tag: 'x' }]; + + it('multi-row insert preview, a caller not served the calculated header field: every row judges it as empty, as the first row does, whatever the header holds', async () => { + withholdBudColumns('carol', ['budget', 'headroom', 'remaining']); + const carol = { userId: 'carol' }; + const verdicts: boolean[][] = []; + for (const budget of [100, 1000]) { + const p = await engine.insert('bud', { name: 'B', budget }); + // Precondition: the read door serves carol the header, without the withheld columns. + const served = await engine.findOne('bud', { where: { id: p.id }, context: carol } as any); + expect(served).toMatchObject({ id: p.id }); + for (const c of ['budget', 'headroom', 'remaining']) expect(served).not.toHaveProperty(c); + for (const batch of [noteless(p.id), [1, 2, 3].map(() => ({ bud: p.id, amount: 40, tag: 'rem', note: 'n' }))]) { + const preview = await engine.validate('bud_line', batch, { mode: 'insert', context: carol as any }); + const rows = preview.results!.map((r) => r.valid); + // No row reads a value the first row could not: the earlier rows' amounts steer no withheld column. + expect(rows).toEqual(rows.map(() => rows[0])); + verdicts.push(rows); + } + } + // Identical whatever the withheld budget holds. + expect(verdicts.slice(2)).toEqual(verdicts.slice(0, 2)); + }); + + it('multi-row insert preview, a caller served the calculated field but not its input: the served field moves as one by one serves it, and the third line needs the note', async () => { + withholdBudColumns('dave', ['budget']); + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + const preview = await engine.validate('bud_line', noteless(p.id), { mode: 'insert', context: { userId: 'dave' } as any }); + expect(preview.results!.map((r) => r.valid)).toEqual([true, true, false]); + expect(preview.results![2]!.errors.map((e) => e.field)).toContain('note'); + }); + + it('CONTROL: a system preview of the same batch needs the note on the third line, as the write does', async () => { + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + const preview = await engine.validate('bud_line', noteless(p.id), { mode: 'insert' }); + expect(preview.results!.map((r) => r.valid)).toEqual([true, true, false]); + expect((await refusalOf(engine.insert('bud_line', noteless(p.id))) as ValidationError).fields.map((f) => f.field)).toContain('note'); + }); + it('CONTROL: a multi-row insert no rule of which reads the parent reads no parent row for the calculated fields over its roll-up', async () => { const p = await engine.insert('bud', { name: 'B', budget: 100 }); const parentReads = (from: number) => log.slice(from).filter((e) => e.op === 'find' && e.object === 'bud' && e.ast?.where?.id?.$in); @@ -2108,3 +2164,80 @@ describe('[#34821] a predicate update whose patch cannot move a roll-up its rule expect(traces).toEqual([[expect.any(String), { object: 'cap_line', parentObject: 'cap_head', field: 'first_day', reason: 'not_a_number' }]]); }); }); + +describe('[#34821] a predicate update whose patch writes only a { $field } comparand of a roll-up\'s filter moves that roll-up, as the by-id update does', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + + beforeEach(async () => { + engine = new ObjectQL(); + const d = makeDriver(); + storeFor = d.storeFor; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject({ + name: 'late_head', + fields: { + name: { type: 'text' }, + // Counts the lines closed after their due day: the patched due day is a comparand, never a key. + late_count: { type: 'summary', summaryOperations: { object: 'late_line', field: 'id', function: 'count', filter: { closed_day: { $gt: { $field: 'due_day' } } } } }, + }, + } as any); + engine.registry.registerObject({ + name: 'late_line', + fields: { + closed_day: { type: 'number' }, + due_day: { type: 'number' }, + tag: { type: 'text' }, + head: { type: 'master_detail', reference: 'late_head' }, + }, + validations: [ + { name: 'one_late', type: 'script', severity: 'error', message: 'head already has a late line', condition: "record.tag == 'late' && record.head.late_count > 0" }, + ], + } as any); + }); + + const head = (id: string) => storeFor('late_head').get(id); + + async function refusalOf(write: Promise): Promise { + try { await write; } catch (err) { return err; } + throw new Error('expected the write to be refused'); + } + + function expectRuleRefusal(err: unknown): void { + expect(err).toBeInstanceOf(ValidationError); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mapDataError(err).status).toBe(400); + expect((err as ValidationError).fields.map((f) => f.message).join(' | ')).toContain('head already has a late line'); + } + + /** Two lines closed on day 5, due on day 10: neither is late. */ + async function seed() { + const p = await engine.insert('late_head', { name: 'H' }); + const [a, b] = await engine.insert('late_line', [{ head: p.id, closed_day: 5, due_day: 10, tag: 'x' }, { head: p.id, closed_day: 5, due_day: 10, tag: 'x' }]); + expect(head(p.id).late_count).toBe(0); + return { p, a, b }; + } + + it('one by one (the reference answer): the first line made late moves the count, so the second reads 1 and is refused', async () => { + const { p, a, b } = await seed(); + await engine.update('late_line', { id: a.id, due_day: 1, tag: 'late' }); + expect(head(p.id).late_count).toBe(1); + expectRuleRefusal(await refusalOf(engine.update('late_line', { id: b.id, due_day: 1, tag: 'late' }))); + }); + + it('predicate update: the second matched row reads the count the first moved, and the update is refused', async () => { + const { p } = await seed(); + // Read as stored (0) at every row, both rows would be admitted. + expectRuleRefusal(await refusalOf(engine.update('late_line', { due_day: 1, tag: 'late' }, { where: { head: p.id }, multi: true }))); + expect([...storeFor('late_line').values()].map((r) => r.tag)).toEqual(['x', 'x']); + expect(head(p.id).late_count).toBe(0); + }); + + it('CONTROL: a patch writing no field the filter reads, as key or comparand, still reads the stored count', async () => { + const { p } = await seed(); + // Stale at 1 (the children count 0): the by-id update reads it, and so must the predicate update. + storeFor('late_head').set(p.id, { ...head(p.id), late_count: 1 }); + expectRuleRefusal(await refusalOf(engine.update('late_line', { tag: 'late' }, { where: { head: p.id }, multi: true }))); + }); +}); From c2a5fd120400ea10e157c0314e3817660f33de99 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 08:36:34 +0000 Subject: [PATCH 7/8] test(objectql): pin the multi-row insert preview's batch overlay on per-caller header columns through a parent. predicate The carol and erin personas read the header through a field-level read rule. A requiredWhen on parent. reads the header the preview binds per caller; a record.REF rule reads the related binding, a system read. Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- packages/objectql/src/summary-rollup.test.ts | 43 ++++++++++++++------ 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 5e5d72a57f8..a71533aa43e 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -1899,6 +1899,8 @@ describe('[#34821] a multi-row insert judges a rule reading a parent field calcu bud: { type: 'master_detail', reference: 'bud' }, // A field-level parent. predicate reading the header's calculated field. note: { type: 'text', requiredWhen: 'parent.headroom < 50' }, + // Reads the header's formula on `parent`, guarded against a column the reader is not served (`null`). + memo: { type: 'text', requiredWhen: "record.tag == 'remg' && parent.remaining != null && parent.remaining < 50" }, }, validations: [ { name: 'remaining_cover', type: 'script', severity: 'error', message: 'line over the remaining budget', condition: "record.tag == 'rem' && record.amount > record.bud.remaining" }, @@ -2022,26 +2024,41 @@ describe('[#34821] a multi-row insert judges a rule reading a parent field calcu const noteless = (budId: string) => [{ bud: budId, amount: 40, tag: 'x' }, { bud: budId, amount: 40, tag: 'x' }, { bud: budId, amount: 1, tag: 'x' }]; + const guarded = (budId: string, amounts: number[]) => amounts.map((amount) => ({ bud: budId, amount, tag: 'remg', note: 'n' })); + const validOf = async (batch: Record[], context?: Record) => + (await engine.validate('bud_line', batch, { mode: 'insert', ...(context ? { context: context as any } : {}) })).results!.map((r) => r.valid); + it('multi-row insert preview, a caller not served the calculated header field: every row judges it as empty, as the first row does, whatever the header holds', async () => { - withholdBudColumns('carol', ['budget', 'headroom', 'remaining']); + withholdBudColumns('carol', ['remaining']); const carol = { userId: 'carol' }; const verdicts: boolean[][] = []; for (const budget of [100, 1000]) { const p = await engine.insert('bud', { name: 'B', budget }); - // Precondition: the read door serves carol the header, without the withheld columns. + // Precondition: the read door serves carol the header and its inputs, without the withheld column. const served = await engine.findOne('bud', { where: { id: p.id }, context: carol } as any); - expect(served).toMatchObject({ id: p.id }); - for (const c of ['budget', 'headroom', 'remaining']) expect(served).not.toHaveProperty(c); - for (const batch of [noteless(p.id), [1, 2, 3].map(() => ({ bud: p.id, amount: 40, tag: 'rem', note: 'n' }))]) { - const preview = await engine.validate('bud_line', batch, { mode: 'insert', context: carol as any }); - const rows = preview.results!.map((r) => r.valid); - // No row reads a value the first row could not: the earlier rows' amounts steer no withheld column. - expect(rows).toEqual(rows.map(() => rows[0])); - verdicts.push(rows); - } + expect(served).toMatchObject({ id: p.id, budget, total: 0 }); + expect(served).not.toHaveProperty('remaining'); + verdicts.push(await validOf(guarded(p.id, [40, 40, 1]), carol)); } - // Identical whatever the withheld budget holds. - expect(verdicts.slice(2)).toEqual(verdicts.slice(0, 2)); + // CONTROL: a reader served the column needs the memo on the third line (remaining 20), as the write does. + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + expect(await validOf(guarded(p.id, [40, 40, 1]))).toEqual([true, true, false]); + expect((await refusalOf(engine.insert('bud_line', guarded(p.id, [40, 40, 1]))) as ValidationError).fields.map((f) => f.field)).toContain('memo'); + // No row reads a value the first row could not, whatever the withheld column holds: + // the earlier rows' amounts steer no withheld column. + expect(verdicts).toEqual([[true, true, true], [true, true, true]]); + }); + + it('multi-row insert preview, a caller not served the roll-up itself: it moves from the stored value, not from the empty column, so the served calculated field reads as one by one serves it', async () => { + withholdBudColumns('erin', ['total']); + const p = await engine.insert('bud', { name: 'B', budget: 100 }); + await engine.insert('bud_line', { bud: p.id, amount: 40, tag: 'x', note: 'n' }); + // One by one: the first line reads remaining 60, the second 40 and needs the memo. + // Moved from the empty column instead, the second would read 80. + const erin = await engine.validate('bud_line', guarded(p.id, [20, 1]), { mode: 'insert', context: { userId: 'erin' } as any }); + expect(erin.results!.map((r) => r.valid)).toEqual([true, false]); + expect(erin.results![1]!.errors.map((e) => e.field)).toContain('memo'); + expect(await validOf(guarded(p.id, [20, 1]))).toEqual([true, false]); }); it('multi-row insert preview, a caller served the calculated field but not its input: the served field moves as one by one serves it, and the third line needs the note', async () => { From 5d69a3251f5b34b96546b3d6b264585dbc096795 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 09:10:58 +0000 Subject: [PATCH 8/8] test(objectql): type the M2 pin's header read options instead of erasing them The findOne options in the carol pin carried `as any`, one more test site for the query-options erasure ratchet (236 to 237). The options are on contract, so the cast goes. Claude-Session: https://claude.ai/code/session_01L9qibwJEh7hMPPvagWM1g7 Co-authored-by: Claude --- packages/objectql/src/summary-rollup.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index a71533aa43e..375cc98fce0 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -2035,7 +2035,7 @@ describe('[#34821] a multi-row insert judges a rule reading a parent field calcu for (const budget of [100, 1000]) { const p = await engine.insert('bud', { name: 'B', budget }); // Precondition: the read door serves carol the header and its inputs, without the withheld column. - const served = await engine.findOne('bud', { where: { id: p.id }, context: carol } as any); + const served = await engine.findOne('bud', { where: { id: p.id }, context: carol }); expect(served).toMatchObject({ id: p.id, budget, total: 0 }); expect(served).not.toHaveProperty('remaining'); verdicts.push(await validOf(guarded(p.id, [40, 40, 1]), carol));