diff --git a/.changeset/34465-predicate-update-parent-summary-rule.md b/.changeset/34465-predicate-update-parent-summary-rule.md new file mode 100644 index 00000000000..bf088393fd5 --- /dev/null +++ b/.changeset/34465-predicate-update-parent-summary-rule.md @@ -0,0 +1,23 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql)!: a predicate update judges each matched row against the parent summaries the rows judged before it move, as consecutive by-id updates do + +Clause-②: no (narrowing) +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. + +- 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). +- The answer moves both ways. Mostly it narrows: main admitted a row that one-by-one refuses, and it is refused now. It also admits a row main refused when the rows judged before it move the summary toward admitting it, as one by one does. For example, with `parent.line_count >= 3` requiring a field, a row leaving that parent lowers the count the later rows read. + +**Not moved.** A rule that reads no summary, a predicate update matching one row, a by-id update, hooks and flow steps (they read the value from before the update), and a rule of the parent itself (it judges the summary once, after the write). Three cases keep reading the stored value, as before, and each one covers that summary for EVERY parent the update reads it for, not only the parent that caused it: +- a summary whose `filter` reads through another reference, as a dotted path (`{ 'account.kind': 'x' }`) or in the nested form (`{ account: { status: 'x' } }`), or that the in-memory filter walker refuses; +- a summary meeting a value that is not a number, in any matched row or in any parent's base; +- a `min` / `max` when any one parent holds more than 5,000 matched rows. + +The fix for a caller: update the rows the rule refuses on their own, or narrow the filter so the update matches the rows the rule admits. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index a583b8ad41a..5ee12f2fdf4 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -477,6 +477,21 @@ recomputes after each row, so each row's rules, and the parent's own rules judging each recompute, read it as one-by-one updates would, for every summary function, `avg` included. A `parent.` predicate that reads a field that is not a summary, and is not calculated from one, does not count. +**A predicate update equals one-by-one updates too:** an update that selects +its rows by a filter (`update(object, patch, { where, multi: true })`, a flow +`update_record` step with `multi: true`) judges every matched row before its +one write. A validation rule reading a parent summary one hop through a +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 +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` +when one parent holds more than 5,000 matched rows. A rule of the parent +itself judges the summary once, after the write. **Hooks and flow steps read the value from before the batch:** inside one bulk create or bulk update, a hook or flow step that reads a parent's summary reads it as stored before the batch, on create and update alike. diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index a6fbb7129cd..c08d0d9a306 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -152,13 +152,19 @@ const ruleReadsByIndex = new WeakMap>(); * (`summary-rule-reads.ts`). */ function rollUpReadByARule(host: Pick, descriptors: readonly SummaryDescriptor[]): boolean { + const read = summaryFieldsReadByRulesOf(host); + return descriptors.some((d) => read.has(ruleReadKey(d.parentObject, d.summaryField))); +} + +/** The `.` keys a rule reads, cached per built summary index ({@link ruleReadsByIndex}). */ +function summaryFieldsReadByRulesOf(host: Pick): Set { const index = host.summaryIndex; let read = index ? ruleReadsByIndex.get(index) : undefined; if (!read) { read = summaryFieldsReadByRules(host._registry.getAllObjects(), index ? [...index.values()].flat() : []); if (index) ruleReadsByIndex.set(index, read); } - return descriptors.some((d) => read.has(ruleReadKey(d.parentObject, d.summaryField))); + return read; } /** @@ -456,6 +462,18 @@ export class SummariesAndExpansionFacet { return [...new Set(this.getSummaryDescriptors(childObject).map((desc) => desc.fkField))]; } + /** [#34465] The roll-ups over `childObject` whose summary field a rule reads + * — the same judgement that keeps a recompute from being deferred + * (`summary-rule-reads.ts`, ruling 6928862195 B). A predicate update folds + * exactly these into the values its rules read, so each matched row is + * judged as one-by-one updates judge it. Empty when no rule reads any. */ + static summaryDescriptorsReadByRules(this: Pick, childObject: string): SummaryDescriptor[] { + const descriptors = this.getSummaryDescriptors(childObject); + if (descriptors.length === 0) return []; + const read = summaryFieldsReadByRulesOf(this); + return descriptors.filter((d) => read.has(ruleReadKey(d.parentObject, d.summaryField))); + } + /** The body of `ObjectQL#getOwnedSummaryDescriptors`; the method's docblock there is its contract. */ static getOwnedSummaryDescriptors(this: Pick, parentObject: string): SummaryDescriptor[] { this.ensureSummaryIndexes(); diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 28044fb359b..94c73dac7da 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -60,14 +60,18 @@ import { emitValidationAdvisories, evaluateValidationRules, hasParentScopedReado 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 { 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'; import { ENGINE_UPDATE_REJECT_MESSAGE, engineUpdateDispatchRejectError, resolveEngineUpdateDispatch } from './engine-update-dispatch.js'; import type { EngineUpdateDispatchData, EngineUpdateDispatchInput } from './engine-update-dispatch.js'; import { - ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, WRITE_PRECONDITION_OPTION, applyStoredExpressionsToPatch, + ENGINE_UPDATE_OPTION_KEYS, ENGINE_WHERE_SLOTS, WRITE_PRECONDITION_OPTION, applyFormulaPlan, applyStoredExpressionsToPatch, computeStoredExpressions, declaredDatetimeLowering, foldEngineOptionAliases, hydrateWriteFormulas, - lowerWhereFilterArray, masterIdOf, planStoredExpressions, rejectUnknownEngineOptions, + lowerWhereFilterArray, masterIdOf, planFormulaProjection, planStoredExpressions, rejectUnknownEngineOptions, + storedExpressionsReading, replacedStoredExpressionFields, settleBulkStoredExpressions, shouldSkipStateMachine, staticReadonlyStoredView, stripComputedWriteFields, undeclaredWriteFieldErrors, updateStaticReadonlySubject, writeFailureLogMeta, callerInputRefusalLogMeta, @@ -135,6 +139,7 @@ export interface UpdateHost { resolveOptionPermissions: ObjectQLClass['resolveOptionPermissions']; resolvePredicateRelated: ObjectQLClass['resolvePredicateRelated']; settleMasterDetailLanding: ObjectQLClass['settleMasterDetailLanding']; + summaryDescriptorsReadByRules: ObjectQLClass['summaryDescriptorsReadByRules']; summaryForeignKeyColumns: ObjectQLClass['summaryForeignKeyColumns']; triggerHooks: ObjectQLClass['triggerHooks']; update: ObjectQLClass['update']; @@ -147,7 +152,7 @@ export interface UpdateHost { /** The bodies of the "Update" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class UpdateFacet { /** The body of `ObjectQL#update`; the method's docblock there is its contract. */ - static async update(this: Pick, object: string, data: any, options?: EngineUpdateOptions & WriteObservabilityOptions): Promise | number | null> { + static async update(this: Pick, object: string, data: any, options?: EngineUpdateOptions & WriteObservabilityOptions): Promise | number | null> { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterUpdate`, or a refusal after a `beforeUpdate` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. @@ -2073,9 +2078,35 @@ export class UpdateFacet { ); if (referencesFirst) await checkReferences(); if (rulesNeedRows) { - for (const row of priorRows ?? []) { + // [#34465] Batch equals one-by-one for a rule that reads a + // roll-up of a parent: each matched row is judged against + // the value the rows judged before it move that roll-up to, + // as consecutive by-id updates would read it (ruling + // 6377847361, C; ruling record 6928862195, B). Only when a + // 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) : []; + const matchedStates = readSummaries.length > 0 + ? matchedRows.map((row) => ({ previous: row ?? {}, next: { ...(row ?? {}), ...bulkPatch } })) + : []; + const summaryFold = readSummaries.length > 0 + ? createPredicateUpdateSummaryFold( + await loadPredicateUpdateSummaryBases(this.facade, readSummaries, matchedStates, { ...(opCtx.context ?? {}), isSystem: true }), + matchedStates, + (updateSchema as any)?.fields, + ) + : undefined; + if (summaryFold) { + summaryFold.setDependents(await loadSummaryFoldDependents(this, summaryFold.foldedSummaries(), opCtx.context)); + } + const foldMaster = summaryFold && parentForRow ? resolveMasterDetailRelation(updateSchema as any)?.master : undefined; + for (const [i, row] of matchedRows.entries()) { try { - emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record, 'update', { previous: row, logger: this.logger, currentUser: bulkEvalUser, skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, parent: parentForRow?.(row), previousParent: previousParentForRow?.(row), related: bulkRelatedForRow?.({ ...(row ?? {}), ...bulkPatch }), permissions: bulkPermissions }), this.logger, object); + const header = parentForRow?.(row); + const related = bulkRelatedForRow?.({ ...(row ?? {}), ...bulkPatch }); + emitValidationAdvisories(options?.onValidationAdvisory, evaluateValidationRules(updateSchema as any, hookContext.input.data as Record, 'update', { previous: row, logger: this.logger, currentUser: bulkEvalUser, skipStateMachine: shouldSkipStateMachine(opCtx.context), messages: updateMsgCtx, parent: foldMaster ? summaryFold!.overlayRow(foldMaster, header) : header, previousParent: foldMaster ? summaryFold!.overlayRow(foldMaster, previousParentForRow?.(row)) : previousParentForRow?.(row), related: summaryFold ? summaryFold.overlay(related) : related, permissions: bulkPermissions }), this.logger, object); + summaryFold?.advance(i); } catch (err) { if (err instanceof ValidationError && row?.id != null) { throw new ValidationError(err.fields.map((f) => ({ ...f, message: `${f.message} (record ${String(row.id)})` }))); @@ -2324,3 +2355,140 @@ export class UpdateFacet { return opCtx.result; } } + +/** + * [#34465] What computes, for the parents a predicate update's summary fold + * moves, their fields calculated from the folded roll-ups: a `formula` + * (computed on read) or a stored computed field (an `expression` on a field + * that is not a formula, computed on the recompute's write), directly or + * 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. + * + * Read the way a by-id update's rule reads the parent: the values as SYSTEM + * (`resolvePredicateRelated` reads related rows under system authority). So + * the parents' stored rows, the plan's permission map (with the SYSTEM + * context's own permission resolution), its one-hop related rows and its + * option labels are all resolved under the SYSTEM context, ONCE over the + * stored parents: none of them moves while the update is judged, only the + * roll-ups do. + * + * Computed as one by one computes them, in two passes over each parent: + * + * 1. the stored computed fields, as the recompute's write computes them: + * over the stored image (the row WITHOUT its formula fields, which a write's + * image never carries, so a stored field reading a formula computes + * `null` here as it does on every write), in their own plan order, with the + * DECLARED option labels, and TWICE: a by-id write computes them before its + * `beforeUpdate` hooks, moves the changed values onto the patch, and + * computes them again over the row with that patch before the statement. + * So a stored field declared BEFORE the stored field it reads (`flag` over + * `headroom`, `headroom` over the roll-up) is written over the moved value, + * and the second evaluation here reads it the same way; + * 2. then the formulas, as the next read computes them: over that row with + * the stored fields just computed and the stored row's values of the + * formulas the plan does not hold back on it, in the read plan's order, + * with the option labels the SYSTEM read of the parent uses. A formula + * outside the plan reads no folded roll-up, so it does not move while the + * update is judged, and the SYSTEM read of the stored parent already + * computed it: a planned formula reading one (`room = ceiling - total`, + * `ceiling = budget + extra`) reads it as the by-id rule's read does. + * + * The stored pass carries one image per parent through the update, as one by + * one does: after each matched row is judged, the parents it names are + * written again (`advance`), from the row the previous write stored, and the + * next row reads that row. A stored computed field reading its own stored + * value (a high-water mark) or a chain of them declared against their reading + * order then holds what one by one holds at every row, not only the second. + * + * Each pass runs synchronously, with the read path's own evaluator + * ({@link applyFormulaPlan}). An object no such field reads a folded roll-up + * of reads nothing. + */ +async function loadSummaryFoldDependents( + host: Pick, + folded: Map; parentIds: Set }>, + context: Parameters[3], +): Promise { + type Plan = ReturnType; + const served = new Map>; + permissions: Awaited>; + related: Awaited>; + storedLabels: ReturnType; + formulaLabels: ReturnType; + }>(); + const systemCtx = { ...(context ?? {}), isSystem: true } as typeof context; + const systemResolution = host.permissionResolution(systemCtx); + for (const [object, { fields, parentIds }] of folded) { + const schema = host.getSchema(object) as any; + if (!schema) continue; + const storedAll = planStoredExpressions(schema); + const formulaAll = planFormulaProjection(schema, undefined).plan; + const readers = new Set(storedExpressionsReading([...storedAll, ...formulaAll], fields)); + const storedPlan = storedAll.filter((entry) => readers.has(entry)); + const formulaPlan = formulaAll.filter((entry) => readers.has(entry)); + if (storedPlan.length + formulaPlan.length === 0 || parentIds.size === 0) continue; + const rows = new Map>(); + const ids = [...parentIds]; + for (let start = 0; start < ids.length; start += SUMMARY_GROUPED_AGGREGATE_CHUNK) { + const found = await host.facade.find(object, { where: { id: { $in: ids.slice(start, start + SUMMARY_GROUPED_AGGREGATE_CHUNK) } }, context: systemCtx }) as Array>; + for (const row of found ?? []) if (row?.id != null) rows.set(String(row.id), row); + } + if (rows.size === 0) continue; + const storedRows = [...rows.values()]; + const plan = [...storedPlan, ...formulaPlan]; + served.set(object, { + storedPlan, + formulaPlan, + formulaFields: formulaAll.map((entry) => entry.name), + unplannedFormulas: formulaAll.filter((entry) => !readers.has(entry)).map((entry) => entry.name), + rows, + permissions: await host.resolveFormulaPermissions(object, plan, storedRows, systemCtx, systemResolution), + related: await host.resolveFormulaRelated(schema, plan, storedRows, systemCtx), + storedLabels: declaredOptionLabels(schema, storedPlan), + formulaLabels: host.formulaOptionLabels(schema, formulaPlan, systemCtx), + }); + } + type Served = NonNullable>; + /** What the recompute's write stores from `from` with the folded roll-ups `moved`: no formula on it, the stored fields computed. */ + const written = (entry: Served, from: Record, moved: Readonly>): Record => { + const scratch: Record = { ...from, ...moved }; + for (const name of entry.formulaFields) delete scratch[name]; + // Twice, as the write computes them: before its hooks, then over the row with the moved values. + for (let pass = 0; pass < 2 && entry.storedPlan.length > 0; pass += 1) { + applyFormulaPlan(entry.storedPlan, [scratch], systemCtx, entry.permissions, undefined, entry.related, entry.storedLabels); + } + return scratch; + }; + /** Parent (`object|id`) → the row the last recompute the fold carried for it stored. */ + const images = new Map>(); + const dependents = ((object, parentId, moved) => { + const entry = served.get(object); + const stored = entry?.rows.get(parentId); + if (!entry || !stored) return undefined; + // The row the rule reads: the one the previous row's recompute stored, or, before any, the + // write's image over the stored row. + const image = images.get(`${object}|${parentId}`); + const scratch = image ? { ...image, ...moved } : written(entry, stored, moved); + // The read's row: the formulas the plan does not recompute back at their stored values. + for (const name of entry.unplannedFormulas) if (name in stored) scratch[name] = stored[name]; + if (entry.formulaPlan.length > 0) applyFormulaPlan(entry.formulaPlan, [scratch], systemCtx, entry.permissions, undefined, entry.related, entry.formulaLabels); + const values: Record = {}; + for (const step of [...entry.storedPlan, ...entry.formulaPlan]) values[step.name] = scratch[step.name]; + return values; + }) as SummaryDependents; + // After each matched row, the recompute writes the parents it names: the next write starts from that row. + dependents.advance = (object, parentId, moved) => { + const entry = served.get(object); + const stored = entry?.rows.get(parentId); + if (!entry || !stored || entry.storedPlan.length === 0) return; + const key = `${object}|${parentId}`; + images.set(key, written(entry, images.get(key) ?? stored, moved)); + }; + return dependents; +} diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 46e72924393..0fd49a7868d 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4082,6 +4082,11 @@ export class ObjectQL implements IObjectQLEngine { return SummariesAndExpansionFacet.summaryForeignKeyColumns.call(summariesAndExpansionHost.of(this), childObject); } + private summaryDescriptorsReadByRules(childObject: string): SummaryDescriptor[] { + // [#34465] The body is in `engine-summaries-and-expansion.ts`, its docblock with it (see `SummariesAndExpansionHost`). + return SummariesAndExpansionFacet.summaryDescriptorsReadByRules.call(summariesAndExpansionHost.of(this), childObject); + } + /** Roll-up descriptors for the summary fields `parentObject` OWNS (#5749) — * i.e. the ones a NEW row of `parentObject` must have seeded. * @@ -6228,6 +6233,7 @@ export class ObjectQL implements IObjectQLEngine { resolveOptionPermissions: (...a) => engine.resolveOptionPermissions(...a), resolvePredicateRelated: (...a) => engine.resolvePredicateRelated(...a), settleMasterDetailLanding: (...a) => engine.settleMasterDetailLanding(...a), + summaryDescriptorsReadByRules: (...a) => engine.summaryDescriptorsReadByRules(...a), summaryForeignKeyColumns: (...a) => engine.summaryForeignKeyColumns(...a), triggerHooks: (...a) => engine.triggerHooks(...a), update: (...a) => engine.update(...a), diff --git a/packages/objectql/src/summary-batch-accumulation.test.ts b/packages/objectql/src/summary-batch-accumulation.test.ts index 24116c5964e..dfec75d057b 100644 --- a/packages/objectql/src/summary-batch-accumulation.test.ts +++ b/packages/objectql/src/summary-batch-accumulation.test.ts @@ -9,7 +9,8 @@ */ import { describe, it, expect } from 'vitest'; -import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js'; +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 type { SummaryDescriptor } from './summary-aggregate.js'; import type { RelatedRecordBinding } from './validation/rule-validator.js'; @@ -154,3 +155,166 @@ describe('[#34466] overlayRow — the master-detail header a field-level parent. expect(acc.overlayRow('xt_order', narrow)).toBe(narrow); }); }); + +describe('[#34465] createPredicateUpdateSummaryFold — consecutive by-id updates, folded over a base', () => { + const base = (over: Partial): SummaryBase => ({ count: 0, sum: 0, nonNull: 0, min: null, max: null, ...over }); + const states = (...pairs: Array<[Record, Record]>): MatchedRowStates[] => + pairs.map(([previous, next]) => ({ previous, next })); + const total = (fold: ReturnType, field: string, id = 'o1') => + fold!.overlay(bound({ id, [field]: 'stored' }))!.order!.row![field]; + + it('count / sum / avg over a base that holds the matched rows as stored: each judged row leaves its old part and takes its new one', () => { + const count = desc({ summaryField: 'primaries', fn: 'count', filter: { is_primary: true } }); + const sum = desc({ summaryField: 'total' }); + const avg = desc({ summaryField: 'mean', fn: 'avg' }); + const matched = states( + [{ id: 'a', order: 'o1', amount: 10, is_primary: false }, { id: 'a', order: 'o1', amount: 30, is_primary: true }], + [{ id: 'b', order: 'o1', amount: 20, is_primary: false }, { id: 'b', order: 'o1', amount: 30, is_primary: true }], + ); + // Stored: a, b and one row outside the match (amount 30, primary). + const bases: SummaryBases = new Map([ + [count, new Map([['o1', base({ count: 1 })]])], + [sum, new Map([['o1', base({ sum: 60 })]])], + [avg, new Map([['o1', base({ sum: 60, nonNull: 3 })]])], + ]); + const fold = createPredicateUpdateSummaryFold(bases, matched, CHILD_FIELDS)!; + expect([total(fold, 'primaries'), total(fold, 'total'), total(fold, 'mean')]).toEqual([1, 60, 20]); + fold.advance(0); + expect([total(fold, 'primaries'), total(fold, 'total'), total(fold, 'mean')]).toEqual([2, 80, 80 / 3]); + fold.advance(1); + expect([total(fold, 'primaries'), total(fold, 'total'), total(fold, 'mean')]).toEqual([3, 90, 30]); + }); + + it('min / max over a base that leaves the matched rows out: a matched row holding the extreme takes it with it', () => { + const min = desc({ summaryField: 'lowest', fn: 'min' }); + const max = desc({ summaryField: 'highest', fn: 'max' }); + const matched = states( + [{ id: 'a', order: 'o1', amount: 5 }, { id: 'a', order: 'o1', amount: 70 }], + [{ id: 'b', order: 'o1', amount: 90 }, { id: 'b', order: 'o1', amount: 70 }], + ); + const bases: SummaryBases = new Map([ + [min, new Map([['o1', base({ min: 50 })]])], + [max, new Map([['o1', base({ max: 50 })]])], + ]); + const fold = createPredicateUpdateSummaryFold(bases, matched, CHILD_FIELDS)!; + expect([total(fold, 'lowest'), total(fold, 'highest')]).toEqual([5, 90]); + fold.advance(0); + expect([total(fold, 'lowest'), total(fold, 'highest')]).toEqual([50, 90]); + fold.advance(1); + expect([total(fold, 'lowest'), total(fold, 'highest')]).toEqual([50, 70]); + }); + + it('a reparent: the row leaves the old parent and joins the new one; the header overlay reads the same values', () => { + const count = desc({ summaryField: 'line_count', fn: 'count' }); + const matched = states([{ id: 'a', order: 'o1' }, { id: 'a', order: 'o2' }]); + const fold = createPredicateUpdateSummaryFold(new Map([[count, new Map([['o1', base({ count: 2 })], ['o2', base({ count: 0 })]])]]), matched, CHILD_FIELDS)!; + fold.advance(0); + expect(fold.overlayRow('xt_order', { id: 'o1', line_count: 2 })).toEqual({ id: 'o1', line_count: 1 }); + expect(fold.overlayRow('xt_order', { id: 'o2', line_count: 0 })).toEqual({ id: 'o2', line_count: 1 }); + expect(fold.overlayRow('xt_order', null)).toBeNull(); + }); + + it('leaves the stored value where it cannot say it exactly: a non-number value, a dotted-path filter, a parent with no base', () => { + const sum = desc({}); + const matched = states([{ id: 'a', order: 'o1', amount: '12' }, { id: 'a', order: 'o1', amount: 3 }]); + expect(createPredicateUpdateSummaryFold(new Map([[sum, new Map([['o1', base({ sum: 12 })]])]]), matched, CHILD_FIELDS)).toBeUndefined(); + const plain = states([{ id: 'a', order: 'o1', amount: 1 }, { id: 'a', order: 'o1', amount: 2 }]); + const fold = createPredicateUpdateSummaryFold(new Map([[sum, new Map([['o1', base({ sum: 1 })]])]]), plain, CHILD_FIELDS)!; + const other = bound({ id: 'o9', total: 7 }); + expect(fold.overlay(other)).toBe(other); + expect(createPredicateUpdateSummaryFold(new Map(), plain, CHILD_FIELDS)).toBeUndefined(); + }); +}); + +describe('[#34465] the fold hands the folded roll-ups to what computes the parent fields calculated from them', () => { + it('patches a calculated field the row carries, with the folded values; leaves the rest of the row and a field it does not carry', () => { + const sum = desc({}); + const matched: MatchedRowStates[] = [ + { previous: { id: 'a', order: 'o1', amount: 40 }, next: { id: 'a', order: 'o1', amount: 70 } }, + { previous: { id: 'b', order: 'o1', amount: 40 }, next: { id: 'b', order: 'o1', amount: 70 } }, + ]; + const fold = createPredicateUpdateSummaryFold(new Map([[sum, new Map([['o1', { count: 0, sum: 80, nonNull: 0, min: null, max: null }]])]]), matched, CHILD_FIELDS)!; + expect(fold.foldedSummaries()).toEqual(new Map([['xt_order', { fields: new Set(['total']), parentIds: new Set(['o1']) }]])); + const asked: unknown[] = []; + fold.setDependents((object, parentId, moved) => { + asked.push([object, parentId, { ...moved }]); + return { remaining: 100 - (moved.total ?? 0), other: 'x' }; + }); + // A binding that names only the calculated field (the rule reads `record.order.remaining`). + const binding: RelatedRecordBinding = { order: { object: 'xt_order', row: { id: 'o1', remaining: 20 } } }; + expect(fold.overlay(binding)!.order!.row).toEqual({ id: 'o1', remaining: 20 }); + fold.advance(0); + expect(fold.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: 80 }], ['xt_order', 'o1', { total: 110 }]]); + }); + + it('tells the dependents, after each judged row, every parent that row names (as stored and as left) with the roll-ups it leaves', () => { + const sum = desc({}); + const matched: MatchedRowStates[] = [ + { previous: { id: 'a', order: 'o1', amount: 40 }, next: { id: 'a', order: 'o2', amount: 40 } }, + { previous: { id: 'b', order: 'o1', amount: 40 }, next: { id: 'b', order: 'o1', amount: 70 } }, + ]; + const base = (s: number) => ({ count: 0, sum: s, nonNull: 0, min: null, max: null }); + const fold = createPredicateUpdateSummaryFold(new Map([[sum, new Map([['o1', base(80)], ['o2', base(0)]])]]), matched, CHILD_FIELDS)!; + const advanced: unknown[] = []; + const dependents = Object.assign(() => undefined, { advance: (object: string, parentId: string, moved: Readonly>) => { advanced.push([object, parentId, { ...moved }]); } }); + fold.setDependents(dependents); + fold.advance(0); + fold.advance(1); + expect(advanced).toEqual([ + ['xt_order', 'o1', { total: 40 }], ['xt_order', 'o2', { total: 40 }], + ['xt_order', 'o1', { total: 70 }], + ]); + }); +}); + +describe('[#34465] loadPredicateUpdateSummaryBases — the base a predicate update folds over', () => { + const recorder = (answer: (query: any) => any[]) => { + const calls: any[] = []; + return { calls, engine: { aggregate: async (_object: string, query: any) => { calls.push(query); return answer(query); } } }; + }; + const matched: MatchedRowStates[] = [ + { previous: { id: 'a', order: 'o1', amount: 1 }, next: { id: 'a', order: 'o2', amount: 1 } }, + { previous: { id: 'b', order: 'o1', amount: 2 }, next: { id: 'b', order: 'o1', amount: 2 } }, + ]; + + it('count / sum read every child as stored, min / max exclude the matched ids, avg reads its sum and non-null count; every parent named as stored or as left', async () => { + const { calls, engine } = recorder(() => [{ order: 'o1', value: 7, value_count: 3 }]); + const sum = desc({}); + const min = desc({ summaryField: 'lowest', fn: 'min' }); + const avg = desc({ summaryField: 'mean', fn: 'avg' }); + const bases = await loadPredicateUpdateSummaryBases(engine, [sum, min, avg], matched); + expect(calls.map((q) => q.where)).toEqual([ + { order: { $in: ['o1', 'o2'] } }, + { $and: [{ order: { $in: ['o1', 'o2'] } }, { id: { $nin: ['a', 'b'] } }] }, + { $and: [{ order: { $in: ['o1', 'o2'] } }, { amount: { $ne: null } }] }, + ]); + expect(calls.every((q) => q.groupBy[0] === 'order')).toBe(true); + expect(bases.get(sum)!.get('o1')!.sum).toBe(7); + expect(bases.get(sum)!.get('o2')).toEqual({ count: 0, sum: 0, nonNull: 0, min: null, max: null }); + expect(bases.get(min)!.get('o1')!.min).toBe(7); + expect(bases.get(avg)!.get('o1')).toMatchObject({ sum: 7, nonNull: 3 }); + }); + + it('leaves out a roll-up whose answer is no number, one whose filter names a dotted path, and a min / max past the exclusion budget', async () => { + const { engine } = recorder(() => [{ order: 'o1', value: '2026-01-01' }]); + expect((await loadPredicateUpdateSummaryBases(engine, [desc({ fn: 'min', summaryField: 'first_day', sourceField: 'day' })], matched)).size).toBe(0); + expect((await loadPredicateUpdateSummaryBases(engine, [desc({ fn: 'count', filter: { 'account.kind': 'x' } })], matched)).size).toBe(0); + 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' } })); + const counted = recorder(() => []); + expect((await loadPredicateUpdateSummaryBases(counted.engine, [desc({ fn: 'max', summaryField: 'highest' })], many)).size).toBe(0); + expect(counted.calls).toEqual([]); + expect((await loadPredicateUpdateSummaryBases(counted.engine, [desc({ fn: 'count', summaryField: 'n' })], many)).size).toBe(1); + }); + + it('leaves out, before any statement, a roll-up whose filter reads through a reference in the nested form; an operator object beneath a field is no such read', async () => { + const nested = recorder(() => [{ order: 'o1', value: 1 }]); + for (const filter of [{ account: { status: 'x' } }, { $and: [{ kind: 'a' }, { account: { status: 'x' } }] }, { account: { status: { $in: ['x'] } } }]) { + expect((await loadPredicateUpdateSummaryBases(nested.engine, [desc({ fn: 'min', summaryField: 'low', filter })], matched)).size).toBe(0); + } + expect(nested.calls).toEqual([]); + // CONTROL: a field condition spelled with operators is evaluated in memory, so its roll-up is loaded. + expect((await loadPredicateUpdateSummaryBases(nested.engine, [desc({ fn: 'min', summaryField: 'low', filter: { kind: { $in: ['a'] } } })], matched)).size).toBe(1); + }); +}); diff --git a/packages/objectql/src/summary-batch-accumulation.ts b/packages/objectql/src/summary-batch-accumulation.ts index 6d5e97b4ab7..5078351317d 100644 --- a/packages/objectql/src/summary-batch-accumulation.ts +++ b/packages/objectql/src/summary-batch-accumulation.ts @@ -53,10 +53,12 @@ * stored value they started from. */ -import type { SummaryDescriptor } from './summary-aggregate.js'; -import { summaryEmptySetValue } from './summary-aggregate.js'; +import type { SummaryAggregateEngine, SummaryDescriptor } from './summary-aggregate.js'; +import { SUMMARY_GROUPED_AGGREGATE_CHUNK, summaryEmptySetValue } from './summary-aggregate.js'; +import { ROLLUP_AGGREGATE_OPTION } from './record-currency-aggregate-door.js'; import { declaredFieldClasses, declaredJsonStoredFields, matchesAggregationFilter } from './having-filter.js'; import type { RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js'; +import { isNoOperatorObject } from './no-operator-object-door.js'; /** One parent's delta from the batch's admitted rows, for one descriptor. */ interface ParentDelta { @@ -102,6 +104,34 @@ function filterNamesDottedPath(cond: unknown): boolean { return false; } +/** + * [#34465] Does the filter read through a reference anywhere, in either + * spelling: a dotted path (`{ 'account.kind': 'x' }`), or the nested + * one-level form (`{ account: { status: 'x' } }`, a plain object holding a + * key that is no operator beneath a field), which is the form a summary + * filter reads a related record with. The in-memory walker does not refuse + * the nested form: it compares the row's scalar id with the object and + * answers "no match" for every state, so the predicate update's fold must + * leave such a roll-up out before any statement, as it leaves the dotted one. + */ +function filterReadsThroughReference(cond: unknown): boolean { + if (filterNamesDottedPath(cond)) return true; + if (Array.isArray(cond)) return cond.some(filterReadsThroughReference); + if (!cond || typeof cond !== 'object') return false; + for (const [key, value] of Object.entries(cond as Record)) { + if (key === '$and' || key === '$or' || key === '$not') { + if (filterReadsThroughReference(value)) return true; + continue; + } + if (key.startsWith('$')) continue; + // An empty object beneath a field is the nested form too, as the engine reads it (`isNoOperatorObject`). + if (isNoOperatorObject(value)) return true; + if (value && typeof value === 'object' && !Array.isArray(value) && !(value instanceof Date) + && Object.keys(value).some((inner) => !inner.startsWith('$'))) return true; + } + return false; +} + /** A single reference id, or `undefined` for an empty or multi-value slot. */ function singleId(value: unknown): string | undefined { if (value == null || value === '' || Array.isArray(value) || typeof value === 'object') return undefined; @@ -221,3 +251,417 @@ export function createBatchSummaryAccumulator( return { accept, overlay, overlayRow }; } + +/** + * [#34465] Batch equals one-by-one for a PREDICATE update (`multi: true`) + * whose rules read a parent roll-up — the third door of the family after the + * bulk insert above (ruling 6377847361, C) and `updateMany` (ruling record + * 6928862195, B), inheriting both (route A, recorded on the card). + * + * A predicate update judges every matched row before its one `updateMany` + * statement, against related rows and master-detail headers read ONCE for + * the batch, and recomputes the roll-ups once after it. One by one, the k-th + * update is judged while the rows before it already stand in their new state + * and the rest (the k-th included) in their stored one, with the roll-ups + * recomputed between. So for each roll-up a rule reads, this computes that + * value exactly: + * + * - a base read in the database ({@link loadPredicateUpdateSummaryBases}), + * one grouped aggregate per read roll-up and chunk of parents. For `count`, + * `sum` and `avg` (its sum and non-null count) the base is every child as + * stored, the matched rows included; for `min` / `max` it is the children + * OUTSIDE the matched set (`id` not in it), since an extreme cannot be + * taken back out; + * - folded in memory with the matched rows: as row k is judged, every row + * before it has left its stored contribution and taken the one the update + * gives it. + * + * `count`, `sum`, `min`, `max` and `avg` are all exact, a reparent included + * (a row leaves one parent and joins another). The batch is still judged in + * full before the one statement, so it stays all-or-nothing. A roll-up whose + * value the fold cannot say exactly keeps reading the value the binding + * carries (the stored one, as before), the limits the insert arm names: a + * value that is not a number, and a `filter` reading through a reference + * (a dotted path, or the nested one-level form `{ account: { status: 'x' } }`) + * or one the in-memory walker refuses; and a `min` / `max` under a parent holding more + * than {@link MIN_MAX_EXCLUDED_ID_BUDGET} matched rows, whose exclusion + * would not fit one statement. + */ + +/** + * The most matched ids one `min` / `max` base aggregate excludes (`id $nin`). + * Parents are packed so a statement names at most this many, plus at most + * {@link SUMMARY_GROUPED_AGGREGATE_CHUNK} parent ids: far below every + * dialect's bound-parameter limit (SQLite 32766, PostgreSQL 65535). + */ +export const MIN_MAX_EXCLUDED_ID_BUDGET = 5000; + +/** 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'; +} + +/** One matched row of a predicate update: as stored, and as the update leaves it. */ +export interface MatchedRowStates { + previous: Record; + next: Record; +} + +/** One parent's base, as the database aggregates it (see {@link baseHoldsMatched}). */ +export interface SummaryBase { + count: number; + sum: number; + /** Rows whose source value is not null (an `avg`'s denominator). */ + nonNull: number; + min: number | null; + max: number | null; +} + +/** Descriptor → parent id → base. A descriptor absent from the map is not folded. */ +export type SummaryBases = Map>; + +/** A database value as a finite number, or `undefined` when it is not one. */ +function finiteNumber(value: unknown): number | undefined { + if (typeof value === 'number') return Number.isFinite(value) ? value : undefined; + if (typeof value === 'string' && value.trim() !== '') { + const n = Number(value); + return Number.isFinite(n) ? n : undefined; + } + return undefined; +} + +/** + * Read, for each roll-up in `descriptors` and each parent the matched rows + * name (as stored or as left), its base: every child as stored for `count` / + * `sum` / `avg`, the children outside the matched set for `min` / `max`. A + * descriptor whose answer is not a number (a `min` over dates), or whose + * exclusion does not fit {@link MIN_MAX_EXCLUDED_ID_BUDGET}, is left out, and + * its roll-up is not folded. + */ +export async function loadPredicateUpdateSummaryBases( + engine: SummaryAggregateEngine, + descriptors: readonly SummaryDescriptor[], + matched: readonly MatchedRowStates[], + execCtx?: unknown, +): Promise { + const bases: SummaryBases = new Map(); + for (const desc of descriptors) { + if (filterReadsThroughReference(desc.filter)) continue; + if (desc.fn !== 'count' && desc.sourceField === undefined) continue; + const holdsMatched = baseHoldsMatched(desc.fn); + const parents = new Set(); + /** Parent id (as stored) → the matched ids the database still holds under it. */ + const heldUnder = new Map(); + for (const { previous, next } of matched) { + const was = singleId(previous[desc.fkField]); + const now = singleId(next[desc.fkField]); + if (was !== undefined) parents.add(was); + if (now !== undefined) parents.add(now); + const id = singleId(previous.id); + if (!holdsMatched && was !== undefined && id !== undefined) { + const list = heldUnder.get(was) ?? []; + list.push(id); + heldUnder.set(was, list); + } + } + if (parents.size === 0) continue; + // Pack the parents into statements: at most one chunk of parent ids, and + // (min / max) at most the budget of excluded ids. + const statements: string[][] = []; + let current: string[] = []; + let excludedInCurrent = 0; + let fits = true; + for (const id of parents) { + const held = heldUnder.get(id)?.length ?? 0; + if (held > MIN_MAX_EXCLUDED_ID_BUDGET) { fits = false; break; } + if (current.length >= SUMMARY_GROUPED_AGGREGATE_CHUNK || excludedInCurrent + held > MIN_MAX_EXCLUDED_ID_BUDGET) { + statements.push(current); + current = []; + excludedInCurrent = 0; + } + current.push(id); + excludedInCurrent += held; + } + if (!fits) continue; + if (current.length > 0) statements.push(current); + const byParent = new Map(); + // The aggregate's aliases must not be the group key's name. + const alias = desc.fkField === 'value' ? 'summary_value' : 'value'; + const countAlias = desc.fkField === 'value_count' ? 'summary_value_count' : 'value_count'; + let numeric = true; + for (const chunk of statements) { + if (!numeric) break; + const excluded = chunk.flatMap((id) => heldUnder.get(id) ?? []); + const clauses: Record[] = [{ [desc.fkField]: { $in: chunk } }]; + if (excluded.length > 0) clauses.push({ id: { $nin: excluded } }); + if (desc.filter) clauses.push(desc.filter); + if (desc.fn === 'avg') clauses.push({ [desc.sourceField!]: { $ne: null } }); + const aggregations = desc.fn === 'avg' + ? [{ function: 'sum', field: desc.sourceField, alias }, { function: 'count', alias: countAlias }] + : [{ function: desc.fn, ...(desc.fn === 'count' ? {} : { field: desc.sourceField }), alias }]; + const rows = await engine.aggregate(desc.childObject, { + where: clauses.length === 1 ? clauses[0] : { $and: clauses }, + groupBy: [desc.fkField], + aggregations, + context: execCtx, + // [ADR-0144 D6, amended] Each group is one parent's rows through + // `fkField`, the channel the roll-up's own grouped aggregate rides; every + // id here is one concrete id (`singleId`). + }, { [ROLLUP_AGGREGATE_OPTION]: desc.fkField }); + for (const row of rows ?? []) { + const key = row?.[desc.fkField]; + if (key == null || key === '') continue; + const raw = row?.[alias]; + const value = raw == null ? undefined : finiteNumber(raw); + const rawCount = desc.fn === 'avg' ? finiteNumber(row?.[countAlias] ?? 0) : 0; + if ((raw != null && value === undefined) || rawCount === undefined) { numeric = false; break; } + const base: SummaryBase = { count: 0, sum: 0, nonNull: 0, min: null, max: null }; + if (desc.fn === 'count') base.count = value ?? 0; + else if (desc.fn === 'sum') base.sum = value ?? 0; + else if (desc.fn === 'min') base.min = value ?? null; + else if (desc.fn === 'max') base.max = value ?? null; + else if (desc.fn === 'avg') { base.sum = value ?? 0; base.nonNull = rawCount; } + byParent.set(String(key), base); + } + } + if (!numeric) 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); + } + return bases; +} + +export interface PredicateUpdateSummaryFold { + /** {@link BatchSummaryAccumulator.overlay}, with the values the rows judged so far move the roll-ups to. */ + overlay(binding: RelatedRecordBinding | undefined): RelatedRecordBinding | undefined; + /** {@link BatchSummaryAccumulator.overlayRow}, for the master-detail header. */ + overlayRow | null | undefined>(object: string, row: R): R; + /** Matched row `i` has been judged: from here on it counts in the state the update leaves it. */ + advance(i: number): void; + /** The roll-ups this fold moves, per parent object: their fields and the parents they are read for. */ + foldedSummaries(): Map; parentIds: Set }>; + /** Hand the fold what computes a parent's fields calculated from its folded roll-ups ({@link SummaryDependents}). */ + setDependents(dependents: SummaryDependents): void; +} + +/** + * The fields of parent `parentId` (a row of `object`) calculated from its + * roll-ups, as a rule reads them before the next matched row: computed over + * that parent with `moved` (the folded roll-up values) in place of the stored + * ones; `undefined` when none is. + * + * `advance`, when present, is told after each matched row is judged, once per + * parent that row names (as stored or as left) and with the roll-ups as that + * row leaves them: one by one, the recompute writes each such parent after the + * child's update, and the NEXT recompute's write starts from the row that + * write stored, not from the row as stored before the update. A stored + * computed field that reads its own stored value (a high-water mark), or a + * chain of them declared against their reading order, only comes out as one + * by one when the fold carries that image forward the same way. + */ +export type SummaryDependents = ((object: string, parentId: string, moved: Readonly>) => Record | undefined) & { + advance?: (object: string, parentId: string, moved: Readonly>) => void; +}; + +/** What one row adds to one parent's roll-up. */ +interface Contribution { parentId: string; value: number | undefined } + +/** + * The matched rows' part of one parent's roll-up, relative to its base: a bag, + * so a row can leave it again. Over a base that holds the matched rows as + * stored (count / sum / avg) the bag starts empty and goes negative as rows + * leave; `values` (min / max only) never does. + */ +interface Bag { count: number; sum: number; nonNull: number; values: Map } + +/** + * The fold for one predicate update, or `undefined` when no roll-up is folded + * (`bases` empty — the common case, which then pays nothing). `matched` is in + * the order the rows are judged; before any {@link + * PredicateUpdateSummaryFold.advance}, every matched row counts as stored. + */ +export function createPredicateUpdateSummaryFold( + bases: SummaryBases, + matched: readonly MatchedRowStates[], + childFields: unknown, +): 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 => { + 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; + } + } + 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; + return { parentId, value: raw }; + }; + + /** Descriptor → [previous, next] contribution per matched row. */ + const contributions = new Map>(); + for (const desc of [...live.keys()]) { + const list: Array<[Contribution | null, Contribution | null]> = []; + let exact = true; + for (const { previous, next } of matched) { + const was = contributionOf(desc, previous); + const now = contributionOf(desc, next); + if (was === undefined || now === undefined) { exact = false; break; } + list.push([was, now]); + } + if (exact) contributions.set(desc, list); + else live.delete(desc); + } + if (live.size === 0) return undefined; + + const bags = new Map>(); + const move = (desc: SummaryDescriptor, c: Contribution | null, sign: 1 | -1): void => { + if (!c) return; + let byParent = bags.get(desc); + if (!byParent) bags.set(desc, (byParent = new Map())); + const bag = byParent.get(c.parentId) ?? { count: 0, sum: 0, nonNull: 0, values: new Map() }; + bag.count += sign; + if (c.value !== undefined) { + bag.sum += sign * c.value; + bag.nonNull += sign; + if (baseHoldsMatched(desc.fn)) { byParent.set(c.parentId, bag); return; } + const left = (bag.values.get(c.value) ?? 0) + sign; + if (left > 0) bag.values.set(c.value, left); + else bag.values.delete(c.value); + } + byParent.set(c.parentId, bag); + }; + // A min / max base leaves the matched rows out: they start in the bag as stored. + for (const [desc, list] of contributions) if (!baseHoldsMatched(desc.fn)) for (const [was] of list) move(desc, was, 1); + + /** The roll-up's value for `parentId` in the current state, or `undefined` when this fold does not say it. */ + const valueOf = (desc: SummaryDescriptor, parentId: string): number | null | undefined => { + const base = live.get(desc)?.get(parentId); + if (!base) return undefined; + const bag = bags.get(desc)?.get(parentId); + const extreme = (pick: (a: number, b: number) => number, start: number | null): number | null => { + let out = start; + for (const v of bag?.values.keys() ?? []) out = out === null ? v : pick(out, v); + return out; + }; + switch (desc.fn) { + case 'count': return base.count + (bag?.count ?? 0); + case 'sum': return base.sum + (bag?.sum ?? 0); + case 'min': return extreme(Math.min, base.min); + case 'max': return extreme(Math.max, base.max); + case 'avg': { + const n = base.nonNull + (bag?.nonNull ?? 0); + return n === 0 ? summaryEmptySetValue('avg') : (base.sum + (bag?.sum ?? 0)) / n; + } + default: return undefined; + } + }; + + let dependents: SummaryDependents | undefined; + + /** The folded roll-up values of one parent in the current state, or `undefined` when this fold moves none of them. */ + const movedOf = (object: string, parentId: string): Record | undefined => { + const moved: Record = {}; + let any = false; + for (const desc of live.keys()) { + if (desc.parentObject !== object) continue; + const value = valueOf(desc, parentId); + if (value === undefined) continue; + moved[desc.summaryField] = value; + any = true; + } + return any ? moved : undefined; + }; + + const patchRow = (object: string, row: Record): Record | undefined => { + const parentId = singleId(row.id); + if (parentId === undefined) return undefined; + const moved = movedOf(object, parentId); + if (!moved) return undefined; + let patched: Record | undefined; + for (const [field, value] of Object.entries(moved)) { + if (!(field in row)) continue; + patched ??= { ...row }; + patched[field] = value; + } + // A formula or stored computed field of the parent calculated from a + // folded roll-up (`remaining = budget - spent`) is computed again over + // the parent with the folded values, as the recompute's write and the + // next read would compute it. + const computed = dependents?.(object, parentId, moved); + if (computed) { + for (const [field, value] of Object.entries(computed)) { + if (!(field in row)) continue; + patched ??= { ...row }; + patched[field] = value; + } + } + return patched; + }; + + const overlay = (binding: RelatedRecordBinding | undefined): RelatedRecordBinding | undefined => { + if (!binding) return binding; + let out: Record | undefined; + for (const [fk, entry] of Object.entries(binding)) { + if (!entry.row) continue; + const patched = patchRow(entry.object, entry.row); + if (patched) { + out ??= { ...binding }; + out[fk] = { ...entry, row: patched }; + } + } + return out ?? binding; + }; + + const overlayRow = | null | undefined>(object: string, row: R): R => { + if (!row) return row; + return (patchRow(object, row) as R | undefined) ?? row; + }; + + const advance = (i: number): void => { + for (const [desc, list] of contributions) { + const pair = list[i]; + if (!pair) continue; + move(desc, pair[0], -1); + move(desc, pair[1], 1); + } + // One by one, the recompute writes every parent the row names, after the row's update. + const states = matched[i]; + if (!dependents?.advance || !states) return; + const named = new Map(); + for (const desc of live.keys()) { + for (const state of [states.previous, states.next]) { + const parentId = singleId(state?.[desc.fkField]); + if (parentId !== undefined) named.set(`${desc.parentObject}|${parentId}`, { object: desc.parentObject, parentId }); + } + } + for (const { object, parentId } of named.values()) { + const moved = movedOf(object, parentId); + if (moved) dependents.advance(object, parentId, moved); + } + }; + + const foldedSummaries = (): Map; parentIds: Set }> => { + const out = new Map; parentIds: Set }>(); + for (const [desc, byParent] of live) { + 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 id of byParent.keys()) entry.parentIds.add(id); + } + return out; + }; + + return { overlay, overlayRow, advance, foldedSummaries, setDependents: (fn) => { dependents = fn; } }; +} diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 0a4236c9c05..e43c08a36af 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -6,7 +6,7 @@ import { describe, it, expect, beforeEach } from 'vitest'; import { ObjectQL } from './engine.js'; -import { ObjectSchema } from '@objectstack/spec/data'; +import { ObjectSchema, isComposedReadableIds } from '@objectstack/spec/data'; import { mapDataError } from '@objectstack/types'; import { ValidationError } from './validation/record-validator.js'; @@ -32,8 +32,13 @@ function makeDriver() { case '$gte': return value >= target; case '$lt': return value < target; case '$lte': return value <= target; - case '$in': return Array.isArray(target) && target.includes(value); + // [#34465] A nested-relation condition reaches a driver declaring `readableIdsLeaf` as a composed semi-join leaf. + case '$in': return isComposedReadableIds(target) + ? [...storeFor(target.object).values()].some((r) => r.id === value && matches(r, target.scope)) + : Array.isArray(target) && target.includes(value); case '$nin': return Array.isArray(target) && !target.includes(value); + // [#34465] The engine widens a `$nin` to `{ $or: [{ x: { $null: true } }, { x: { $nin } }] }`. + case '$null': return target ? value == null : value != null; default: return true; } }); @@ -1381,3 +1386,463 @@ describe('[#34466] a multi-row insert accumulates its earlier rows into the pare expect(lines(p.id)).toHaveLength(0); }); }); + +// [#34465] A predicate update (`multi: true`) whose rules read a parent +// roll-up answers the way consecutive by-id updates of the matched rows do +// (「批量等于逐条」: ruling 6377847361 for inserts, ruling record 6928862195 +// for updateMany; this is the third door). The matched rows are all judged +// before the one `updateMany`, and each is judged against the roll-up as the +// rows judged before it move it: a base read in the database (every child as +// stored for count / sum / avg, the children outside the matched set for +// min / max), folded in memory with the matched rows. +// +// Reverse verification, predicted before running: drop the fold from the +// validation loop and every "predicate update" refusal below goes green-to-red +// (each row reads the roll-up as stored, so both rows are admitted); the +// one-by-one references, the single-match case and the CONTROL stay green. +describe('[#34465] a predicate update judges each matched row against the parent roll-ups the rows before it move', () => { + 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: 'inv', + fields: { + name: { type: 'text' }, + primaries: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'count', filter: { is_primary: true } } }, + line_count: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'count' } }, + total: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'sum' } }, + low: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'min' } }, + mean: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'avg' } }, + memo_total: { type: 'summary', summaryOperations: { object: 'memo_line', field: 'amount', function: 'sum' } }, + budget: { type: 'number' }, + // Calculated from a roll-up: on read (a formula) and on write (a stored computed field). + remaining: { type: 'formula', expression: 'record.budget - record.total', returnType: 'number' }, + // A stored computed field declared BEFORE the stored computed field it reads (`headroom`). + head_gap: { type: 'number', expression: { dialect: 'cel', source: 'record.headroom' } }, + headroom: { type: 'number', expression: { dialect: 'cel', source: 'record.budget - record.total' } }, + // A formula reading a lookup hop as well as the roll-up, and a stored computed field reading a formula. + cap_ref: { type: 'lookup', reference: 'inv_cap' }, + cap_left: { type: 'formula', expression: 'record.cap_ref.amount - record.total', returnType: 'number' }, + slack: { type: 'number', expression: { dialect: 'cel', source: 'record.remaining' } }, + // 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' } }, + // Three stored computed fields chained against declaration order: x reads y, y reads z, z reads the roll-up. + chain_x: { type: 'number', expression: { dialect: 'cel', source: 'record.chain_y' } }, + chain_y: { type: 'number', expression: { dialect: 'cel', source: 'record.chain_z' } }, + chain_z: { type: 'number', expression: { dialect: 'cel', source: 'record.total' } }, + // A formula over the roll-up that also reads a formula reading no roll-up (`room` over `ceiling`). + extra: { type: 'number' }, + ceiling: { type: 'formula', expression: 'record.budget + record.extra', returnType: 'number' }, + room: { type: 'formula', expression: 'record.ceiling - record.total', returnType: 'number' }, + }, + } as any); + engine.registry.registerObject({ name: 'inv_cap', fields: { amount: { type: 'number' } } } as any); + // Row-level security on the cap object: a caller that is not SYSTEM reads none of it. + engine.registerMiddleware(async (ctx: any, next: () => Promise) => { + if (ctx.object === 'inv_cap' && ['find', 'findOne'].includes(ctx.operation) && !ctx.context?.isSystem) { + ctx.ast = { ...(ctx.ast ?? {}), where: { $and: [ctx.ast?.where ?? {}, { id: '__none__' }] } }; + } + await next(); + }); + engine.registry.registerObject({ + name: 'inv_line', + fields: { + amount: { type: 'number' }, + is_primary: { type: 'boolean' }, + tag: { type: 'text' }, + inv: { type: 'master_detail', reference: 'inv' }, + // Class (ii): a field-level predicate reading a roll-up on `parent`. + note: { type: 'text', requiredWhen: 'parent.line_count >= 3' }, + }, + validations: [ + // Class (i): rules reading roll-ups one hop through the reference. + { name: 'one_primary', type: 'script', severity: 'error', message: 'one primary per invoice', condition: 'record.is_primary == true && record.inv.primaries > 0' }, + { name: 'total_cap', type: 'script', severity: 'error', message: 'invoice total over 100', condition: "record.tag == 'cap' && record.inv.total > 100" }, + { name: 'mean_cap', type: 'script', severity: 'error', message: 'invoice mean over 50', condition: "record.tag == 'mean' && record.inv.mean != null && record.inv.mean > 50" }, + { name: 'low_floor', type: 'script', severity: 'error', message: 'invoice low at 50 or more', condition: "record.tag == 'low' && record.inv.low != null && record.inv.low >= 50" }, + // Rules reading a field calculated from a roll-up, not the roll-up itself. + { name: 'remaining_floor', type: 'script', severity: 'error', message: 'invoice remaining below 0', condition: "record.tag == 'rem' && record.inv.remaining < 0" }, + { name: 'headroom_floor', type: 'script', severity: 'error', message: 'invoice headroom below 0', condition: "record.tag == 'head' && record.inv.headroom < 0" }, + { name: 'cap_floor', type: 'script', severity: 'error', message: 'invoice cap left below 0', condition: "record.tag == 'capref' && record.inv.cap_left != null && record.inv.cap_left < 0" }, + // A stored computed field reading a formula: what does the rule read for it? + { name: 'slack_set', type: 'script', severity: 'error', message: 'invoice slack is set', condition: "record.tag == 'slack' && record.inv.slack != null" }, + { name: 'gap_floor', type: 'script', severity: 'error', message: 'invoice head gap below 0', condition: "record.tag == 'gap' && record.inv.head_gap < 0" }, + { name: 'peak_cap', type: 'script', severity: 'error', message: 'invoice peak at 150 or more', condition: "record.tag == 'peak' && record.inv.peak >= 150" }, + { name: 'chain_cap', type: 'script', severity: 'error', message: 'invoice chain at 150 or more', condition: "record.tag == 'chain' && record.inv.chain_x != null && record.inv.chain_x >= 150" }, + { name: 'room_floor', type: 'script', severity: 'error', message: 'invoice room below 0', condition: "record.tag == 'room' && record.inv.room != null && record.inv.room < 0" }, + ], + } as any); + // CONTROL object: a roll-up of it exists, but no rule reads one. + engine.registry.registerObject({ + name: 'memo_line', + fields: { + amount: { type: 'number' }, + inv: { type: 'master_detail', reference: 'inv' }, + }, + validations: [ + { name: 'amount_cap', type: 'script', severity: 'error', message: 'amount over 1000', condition: 'record.amount > 1000' }, + ], + } as any); + }); + + const inv = (id: string) => storeFor('inv').get(id); + const rows = (object: string, invId: string) => [...storeFor(object).values()].filter((r) => r.inv === invId); + + 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); + } + + it('one by one (the reference answer): the second line made primary is refused', async () => { + const p = await engine.insert('inv', { name: 'P' }); + const a = await engine.insert('inv_line', { inv: p.id, amount: 1, is_primary: false }); + const b = await engine.insert('inv_line', { inv: p.id, amount: 2, is_primary: false }); + await engine.update('inv_line', { id: a.id, is_primary: true }); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: b.id, is_primary: true })), 'one primary per invoice'); + expect(inv(p.id).primaries).toBe(1); + }); + + it('predicate update (count with a filter): refused as one by one refuses its second row, and nothing is written', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 1, is_primary: false }, { inv: p.id, amount: 2, is_primary: false }]); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { is_primary: true }, { where: { inv: p.id }, multi: true })), 'one primary per invoice'); + expect(rows('inv_line', p.id).map((r) => r.is_primary)).toEqual([false, false]); + expect(inv(p.id).primaries).toBe(0); + }); + + it('predicate update matching one row reads the roll-up as stored, as its one by-id update does', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 1, is_primary: false }, { inv: p.id, amount: 2, is_primary: false }]); + expect(await engine.update('inv_line', { is_primary: true }, { where: { inv: p.id, amount: 1 }, multi: true })).toBe(1); + expect(inv(p.id).primaries).toBe(1); + }); + + it('predicate update (sum): the second row reads the total the first row moves', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'cap' }, { inv: p.id, amount: 40, tag: 'cap' }]); + expect(inv(p.id).total).toBe(80); + // One by one: the first update reads 80 and is admitted (total 110); the second reads 110. + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true })), 'invoice total over 100'); + expect(inv(p.id).total).toBe(80); + }); + + it('predicate update, the other direction: a row main refused is admitted when the row before it moves the total under the cap, as one by one admits it', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 60, tag: 'free' }, { inv: p.id, amount: 60, tag: 'cap' }]); + expect(inv(p.id).total).toBe(120); + // One by one: the first (no cap) lowers the total to 70; the second reads 70 and is admitted. + // Read as stored (main), the second read 120 and refused the whole update. + expect(await engine.update('inv_line', { amount: 10 }, { where: { inv: p.id }, multi: true })).toBe(2); + expect(inv(p.id).total).toBe(20); + }); + + it('predicate update (avg): the second row reads the mean the first row moves, rows outside the match included', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'mean' }, { inv: p.id, amount: 40, tag: 'mean' }, { inv: p.id, amount: 40, tag: 'other' }]); + // One by one: the first reads 40 (admitted, mean then 60); the second reads 60. + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 100 }, { where: { inv: p.id, tag: 'mean' }, multi: true })), 'invoice mean over 50'); + expect(inv(p.id).mean).toBe(40); + }); + + it('predicate update (min): a matched row holding the extreme takes it with it', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 5, tag: 'low' }, { inv: p.id, amount: 60, tag: 'low' }, { inv: p.id, amount: 50, tag: 'other' }]); + expect(inv(p.id).low).toBe(5); + // One by one: the first reads 5 (admitted; min then 50, the row outside); the second reads 50. + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id, tag: 'low' }, multi: true })), 'invoice low at 50 or more'); + expect(inv(p.id).low).toBe(5); + }); + + it('one by one (the reference answer): a rule reading a formula over the roll-up refuses the second line', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 100 }); + const a = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'rem' }); + const b = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'rem' }); + await engine.update('inv_line', { id: a.id, amount: 70 }); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: b.id, amount: 70 })), 'invoice remaining below 0'); + }); + + it('predicate update, a rule reading a FORMULA calculated from the roll-up: the second row reads it over the total the first row moves', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 100 }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'rem' }, { inv: p.id, amount: 40, tag: 'rem' }]); + // One by one: the first reads remaining 20 (admitted; total then 110); the second reads -10. + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true })), 'invoice remaining below 0'); + expect(inv(p.id).total).toBe(80); + }); + + it('predicate update, a rule reading a STORED computed field calculated from the roll-up: the same', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 100 }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'head' }, { inv: p.id, amount: 40, tag: 'head' }]); + expect(inv(p.id).headroom).toBe(20); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true })), 'invoice headroom below 0'); + expect(inv(p.id).headroom).toBe(20); + }); + + it('predicate update, a rule reading a formula over the roll-up, under the line: admitted', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 100 }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'rem' }, { inv: p.id, amount: 40, tag: 'rem' }]); + expect(await engine.update('inv_line', { amount: 50 }, { where: { inv: p.id }, multi: true })).toBe(2); + expect(inv(p.id).total).toBe(100); + }); + + // A caller that is not SYSTEM: it cannot read the cap object (the middleware above). + const CALLER = { userId: 'u_caller' } as any; + + it('one by one (the reference answer), as a caller who cannot read the cap: a rule reading a formula over a lookup hop and the roll-up refuses the second line', async () => { + const cap = await engine.insert('inv_cap', { amount: 100 }); + const p = await engine.insert('inv', { name: 'P', cap_ref: cap.id }, { context: { isSystem: true } }); + const a = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'capref' }); + const b = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'capref' }); + await engine.update('inv_line', { id: a.id, amount: 70 }, { context: CALLER }); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: b.id, amount: 70 }, { context: CALLER })), 'invoice cap left below 0'); + }); + + it('predicate update, the same caller: the calculated field is computed as the by-id rule reads it (SYSTEM), so the second row is refused', async () => { + const cap = await engine.insert('inv_cap', { amount: 100 }); + const p = await engine.insert('inv', { name: 'P', cap_ref: cap.id }, { context: { isSystem: true } }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'capref' }, { inv: p.id, amount: 40, tag: 'capref' }]); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true, context: CALLER })), 'invoice cap left below 0'); + expect(inv(p.id).total).toBe(80); + }); + + it('one by one (the reference answer): a stored computed field that reads a formula is computed over the write\'s image, which carries no formula, so it is null and the rule admits both', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 100 }); + const a = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'slack' }); + const b = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'slack' }); + expect(inv(p.id).slack).toBeNull(); + await engine.update('inv_line', { id: a.id, amount: 70 }); + expect(inv(p.id).slack).toBeNull(); + await engine.update('inv_line', { id: b.id, amount: 70 }); + expect(inv(p.id).total).toBe(140); + }); + + it('predicate update: the stored computed field is computed as the write computes it (over the image, before any formula), so both rows are admitted', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 100 }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'slack' }, { inv: p.id, amount: 40, tag: 'slack' }]); + // Computed over the parent as READ (its formula values on it), the field would carry a value and the rule refuse. + expect(await engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true })).toBe(2); + expect(inv(p.id).total).toBe(140); + }); + + it('one by one (the reference answer): a rule reading a formula over the roll-up and over a formula that reads no roll-up refuses the second line', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 60, extra: 40 }); + const a = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'room' }); + const b = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'room' }); + // The first reads room 100 - 80 = 20 (admitted; total then 110); the second reads 100 - 110 = -10. + await engine.update('inv_line', { id: a.id, amount: 70 }); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: b.id, amount: 70 })), 'invoice room below 0'); + expect(inv(p.id).total).toBe(110); + }); + + it('predicate update: the formula the plan does not recompute keeps its stored value, so the recomputed formula reading it refuses the second row as one by one does', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 60, extra: 40 }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'room' }, { inv: p.id, amount: 40, tag: 'room' }]); + // Computed with `ceiling` missing, `room` would read null and the rule admit both rows. + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true })), 'invoice room below 0'); + expect(inv(p.id).total).toBe(80); + }); + + it('predicate update: the same, under the line: admitted', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 60, extra: 40 }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'room' }, { inv: p.id, amount: 40, tag: 'room' }]); + expect(await engine.update('inv_line', { amount: 50 }, { where: { inv: p.id }, multi: true })).toBe(2); + expect(inv(p.id).total).toBe(100); + }); + + it('one by one (the reference answer): a stored computed field declared before the stored computed field it reads tracks it on every write, and the rule refuses the second line', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 100 }); + const a = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'gap' }); + const b = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'gap' }); + expect(inv(p.id).head_gap).toBe(20); + // The recompute's write computes the stored fields twice: `head_gap` reads the `headroom` the first pass moved. + await engine.update('inv_line', { id: a.id, amount: 70 }); + expect(inv(p.id).head_gap).toBe(-10); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: b.id, amount: 70 })), 'invoice head gap below 0'); + }); + + it('predicate update: the stored pass runs twice, as the write runs it, so the field declared first reads the moved field and the second row is refused', async () => { + const p = await engine.insert('inv', { name: 'P', budget: 100 }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'gap' }, { inv: p.id, amount: 40, tag: 'gap' }]); + // Computed once in declaration order, `head_gap` would read the stored `headroom` (20) and the rule admit both rows. + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true })), 'invoice head gap below 0'); + expect(inv(p.id).head_gap).toBe(20); + }); + + it('one by one (the reference answer), three rows: a high-water mark reads every total so far, so the third line reads 160 and is refused', async () => { + const p = await engine.insert('inv', { name: 'P' }); + const a = await engine.insert('inv_line', { inv: p.id, amount: 0, tag: 'x' }); + const b = await engine.insert('inv_line', { inv: p.id, amount: 100, tag: 'x' }); + const c = await engine.insert('inv_line', { inv: p.id, amount: 0, tag: 'peak' }); + expect(inv(p.id).peak).toBe(100); + // Totals 100 -> 160 -> 120: the peak climbs to 160 at the first update and stays there. + await engine.update('inv_line', { id: a.id, amount: 60 }); + await engine.update('inv_line', { id: b.id, amount: 60 }); + expect(inv(p.id).peak).toBe(160); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: c.id, amount: 60 })), 'invoice peak at 150 or more'); + }); + + it('predicate update, three rows: each recompute starts from the row the previous one stored, so the third row reads the peak of 160 and is refused', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 0, tag: 'x' }, { inv: p.id, amount: 100, tag: 'x' }, { inv: p.id, amount: 0, tag: 'peak' }]); + // Restarted from the stored row at every row, the third would read the larger of 100 and 120 and be admitted. + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 60 }, { where: { inv: p.id }, multi: true })), 'invoice peak at 150 or more'); + expect(inv(p.id).peak).toBe(100); + }); + + it('one by one (the reference answer), three rows: a chain declared against its reading order moves one write behind, so the third line reads 150 and is refused', async () => { + const p = await engine.insert('inv', { name: 'P' }); + const a = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'x' }); + const b = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'x' }); + const c = await engine.insert('inv_line', { inv: p.id, amount: 40, tag: 'chain' }); + // Totals 120 -> 150 -> 180: `chain_x` holds the total from one write before. + await engine.update('inv_line', { id: a.id, amount: 70 }); + expect(inv(p.id).chain_x).toBe(120); + await engine.update('inv_line', { id: b.id, amount: 70 }); + expect(inv(p.id).chain_x).toBe(150); + expectRuleRefusal(await refusalOf(engine.update('inv_line', { id: c.id, amount: 70 })), 'invoice chain at 150 or more'); + }); + + it('predicate update, three rows: the chain is carried forward as one by one moves it, so the third row reads 150 and is refused', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 40, tag: 'x' }, { inv: p.id, amount: 40, tag: 'x' }, { inv: p.id, amount: 40, tag: 'chain' }]); + // Restarted from the stored row at every row, `chain_x` would read 120 at the third row and the rule admit. + expectRuleRefusal(await refusalOf(engine.update('inv_line', { amount: 70 }, { where: { inv: p.id }, multi: true })), 'invoice chain at 150 or more'); + }); + + it('predicate update that reparents: the header a parent. predicate reads counts the rows moved before', async () => { + const from = await engine.insert('inv', { name: 'FROM' }); + const to = await engine.insert('inv', { name: 'TO' }); + await engine.insert('inv_line', [{ inv: from.id, amount: 1, tag: 'move' }, { inv: from.id, amount: 2, tag: 'move' }, { inv: from.id, amount: 3, tag: 'move' }]); + await engine.insert('inv_line', [{ inv: to.id, amount: 4 }]); + expect(inv(to.id).line_count).toBe(1); + // One by one: the moves land under 1, 2, then 3 lines; the third needs a note. + const err = await refusalOf(engine.update('inv_line', { inv: to.id }, { where: { tag: 'move' }, multi: true })); + expect(err).toBeInstanceOf(ValidationError); + expect((err as ValidationError).fields.map((f) => ({ field: f.field, code: f.code }))).toEqual([{ field: 'note', code: 'required' }]); + expect(rows('inv_line', from.id)).toHaveLength(3); + expect(inv(to.id).line_count).toBe(1); + }); + + it('predicate update that reparents, below the line: two lines move under a header holding none, the second reads 1', async () => { + const from = await engine.insert('inv', { name: 'FROM' }); + const to = await engine.insert('inv', { name: 'TO' }); + await engine.insert('inv_line', [{ inv: from.id, amount: 1 }, { inv: from.id, amount: 2 }, { inv: from.id, amount: 3 }]); + expect(inv(from.id).line_count).toBe(3); + // Each moved row lands under TO (0, then 1, then 2 lines): every one passes. + expect(await engine.update('inv_line', { inv: to.id }, { where: { inv: from.id }, multi: true })).toBe(3); + expect(inv(to.id).line_count).toBe(3); + }); + + it('CONTROL: an object whose rules read no roll-up reads nothing more before its write, and admits as before', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('memo_line', [{ inv: p.id, amount: 1 }, { inv: p.id, amount: 2 }]); + 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; + expect(await engine.update('memo_line', { amount: 5 }, { where: { inv: p.id }, multi: true })).toBe(2); + const write = log.findIndex((e, i) => i >= start && e.op === 'updateMany'); + expect(log.slice(start, write).filter((e) => e.object.startsWith('aggregate:'))).toEqual([]); + expect(inv(p.id).memo_total).toBe(10); + }); + + it('the subject reads its bases before the write: one grouped aggregate per roll-up a rule reads', async () => { + const p = await engine.insert('inv', { name: 'P' }); + await engine.insert('inv_line', [{ inv: p.id, amount: 1, tag: 'x' }, { inv: p.id, amount: 2, tag: 'x' }]); + 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; + 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); + expect(before.every((e) => Array.isArray(e.ast.groupBy) && e.ast.groupBy[0] === 'inv')).toBe(true); + }); +}); + +describe('[#34465] a min / max roll-up whose filter reads through a reference in the nested form keeps its stored value in a predicate update', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + + beforeEach(async () => { + engine = new ObjectQL(); + const d = makeDriver(); + storeFor = d.storeFor; + // The nested-relation condition runs as a semi-join on a driver declaring the leaf. + d.driver.supports = { readableIdsLeaf: true }; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject({ name: 'acct', fields: { status: { type: 'text' } } } as any); + engine.registry.registerObject({ + name: 'ord', + fields: { + name: { type: 'text' }, + // The nested one-level form a summary filter reads a related record with (the dotted form is refused for a relation head). + low_active: { type: 'summary', summaryOperations: { object: 'ord_line', field: 'amount', function: 'min', filter: { acct: { status: 'active' } } } }, + }, + } as any); + engine.registry.registerObject({ + name: 'ord_line', + fields: { + amount: { type: 'number' }, + tag: { type: 'text' }, + acct: { type: 'lookup', reference: 'acct' }, + ord: { type: 'master_detail', reference: 'ord' }, + }, + validations: [ + { name: 'low_floor', type: 'script', severity: 'error', message: 'order active low under 10', condition: "record.tag == 'low' && record.ord.low_active != null && record.ord.low_active < 10" }, + ], + } as any); + }); + + const ord = (id: string) => storeFor('ord').get(id); + + async function refusalOf(write: Promise): Promise { + try { await write; } catch (err) { return err; } + throw new Error('expected the write to be refused'); + } + + async function seed() { + const acct = await engine.insert('acct', { status: 'active' }); + const p = await engine.insert('ord', { name: 'O' }); + const m1 = await engine.insert('ord_line', { ord: p.id, acct: acct.id, amount: 5, tag: 'x' }); + const m2 = await engine.insert('ord_line', { ord: p.id, acct: acct.id, amount: 50, tag: 'x' }); + await engine.insert('ord_line', { ord: p.id, acct: acct.id, amount: 80, tag: 'x' }); + expect(ord(p.id).low_active).toBe(5); + return { p, m1, m2 }; + } + + it('one by one (the reference answer): a patch that moves no roll-up reads the stored minimum, and the first line is refused', async () => { + const { m1 } = await seed(); + const err = await refusalOf(engine.update('ord_line', { id: m1.id, tag: 'low' })); + expect(err).toMatchObject({ code: 'VALIDATION_FAILED' }); + expect(mapDataError(err).status).toBe(400); + expect((err as ValidationError).fields.map((f) => f.message).join(' | ')).toContain('order active low under 10'); + }); + + it('predicate update: the roll-up is left out of the fold, so it reads the stored minimum as one by one does and is refused', async () => { + const { p } = await seed(); + // Folded over the children outside the match (80), with no matched row put back, the rule would admit both rows. + const err = await refusalOf(engine.update('ord_line', { tag: 'low' }, { where: { ord: p.id, amount: { $lt: 60 } }, 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('order active low under 10'); + expect([...storeFor('ord_line').values()].map((r) => r.tag)).toEqual(['x', 'x', 'x']); + }); +});