diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md new file mode 100644 index 00000000000..33fc2f95257 --- /dev/null +++ b/.changeset/rollup-batch-deferral-33795.md @@ -0,0 +1,24 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': minor +'@objectstack/metadata-protocol': patch +--- + +feat(objectql): a bulk update recomputes its parents' roll-up summaries once, at the end of the batch + +Clause-②: yes (widening) +Metadata-protocol: semantic +Skills-docs: follow-up owed — `skills/objectstack-data/rules/relationships.md` (Roll-up Summaries: "the engine recomputes it server-side whenever a child is inserted/updated/deleted") does not say that a bulk update recomputes once at the end of the batch, that a summary a rule reads still recomputes after each row, or that a hook reads the pre-batch value meanwhile (ruling 6928862195); it moves as a governed skills-only change. `content/docs/data-modeling/fields.mdx` is updated here. + +**Added:** an optional member on the engine slot contract, `IObjectQLEngine.deferSummaryRecompute(callback)` in `@objectstack/spec` (and the same optional member on `MetadataHostEngine` in `@objectstack/metadata-protocol`). It is a callback, entered and left by the engine as `transaction` is; a nested call joins the open scope. Inside it, the roll-up `summary` recompute every write would run after itself is recorded, and runs once when the callback settles: per child object and caller, one grouped aggregate per summary field and one write per parent for the whole batch. `ObjectQL` implements it. A caller probes for it; an engine without it keeps the per-row recompute, with the same values. Every way out of the callback recomputes: resolved, the callback's result (or `ERR_SUMMARY_RECOMPUTE` with `written` set to that result when a parent cannot be recomputed); rejected, the recompute still runs for the writes that landed and the callback's error is rethrown. Opened inside a transaction, the scope's recompute runs before the commit. Only writes under the transaction the scope was opened in (or under none) are deferred: a write under another transaction opened within the scope, such as a hook's own `ctx.api.transaction` or an atomic batch reached from inside a non-atomic one, recomputes at once inside that transaction, as before, because that transaction may commit before the scope ends. + +**Changed:** the bulk update doors run their per-row loop inside that scope: `updateManyData` (`PATCH /api/v1/data/:object/updateMany`, both arms) and the `update` operation of `batchData`. A 50-row bulk update over 10 parents with two summary fields went from 400 to 182 statements (one summary field: 350 to 181; no summary field: 150, unchanged), measured on SQLite and PostgreSQL 16. The stored values are unchanged for every summary kind. + +Two things a caller can see, which is why this declares `Metadata-protocol: semantic` (when an authored hook runs and what it reads move, as in `33760-async-hook-on-commit`): + +- A hook or a flow step that reads a parent's summary during a bulk update reads the value from before the batch until the batch ends, as it does during a bulk create; before this change each row's hook saw the recompute of the rows before it. Rules do not change against today: a summary field a rule reads is not deferred (ruling 6928862195). A validation rule of any object that reads it one hop through a reference, a detail object's `requiredWhen` / `readonlyWhen` that reads it on `parent`, or a rule of the summary's own object that reads it on its own row, whether the rule names the summary or a formula or stored computed field calculated from it (and any summary a chain of summaries rolls up into one of those), a declared bound (`min`, `max`, `precision`, `unique`, …) or a declared unique index on the summary, and any stored computed field of its object calculated from it (the recompute's write judges that value whatever it declares: a bound, an option list, a number that is not finite), makes every roll-up of that child object recompute after each row inside the batch, so a bulk update answers such a rule as one-by-one updates do, for every summary function (two contacts set primary in one grid edit: the first is admitted, the second refused with the rule's text; an atomic edit that moves a line onto a capped invoice and back rolls back at the first move). A `parent.` predicate that reads a field that is not a summary (`parent.status == 'paid'`) does not turn the deferral off. A stored computed field of any object that reads the summary one hop (`record.invoice.line_count`) does turn it off, since it stores what it read at its own write; a `formula` does not, since it is computed when read. +- The parent's own write path (hooks, validation, audit entry, realtime event) runs once per recompute: once per parent for the whole batch, instead of once per child row, for a roll-up that is deferred. A roll-up a rule of the parent reads is not deferred, so those rules still judge every recompute. + +The scope is ambient, not tied to the object being updated: a write a hook issues while the batch runs under the batch's own transaction (or under none, for a non-atomic batch), on any object (a hook's own insert, update or delete, for instance a child-row hook that inserts a row into a second child object of the same parent), has its roll-up recompute deferred to the end of the batch as well, so a summary over that second object also reads its pre-batch value until the batch ends. + +Each row's own hooks, validation, audit and realtime run where they ran. An atomic bulk update whose end-of-batch recompute fails rolls back and answers the same rolled-back envelope a failed row answers (the last row that landed carries `ERR_SUMMARY_RECOMPUTE`, the rows before it `ROLLED_BACK`). A non-atomic one keeps its rows written, logs the stale summary once at `error`, and answers the rows as written, as a per-row recompute failure did. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index c2e66ffeb69..571a1556abe 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -406,6 +406,29 @@ 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 summary as stored before the import: two such rows that fall in different batches of a dry run both preview valid, while the import refuses the second. +**A bulk update equals one-by-one updates (批量等于逐条):** a bulk update +(`updateManyData`, the `update` operation of `batchData`, a grid bulk edit) +recomputes the parents' summaries once, when the batch ends, unless a rule +reads one of the summaries that child object rolls up: a validation rule of any +object reading it one hop through a reference, a detail object's +`requiredWhen` / `readonlyWhen` reading it on `parent`, or a rule of the parent +object itself reading its own summary (a cap such as `record.line_count <= 5`, +or a declared bound such as `min` / `max` / `precision` / `unique` on the +summary, a declared unique index naming it, or any stored computed field of the +parent calculated from it, whose value the recompute's write judges whatever it +declares). A rule that reads a +formula or a stored computed field calculated from the summary reads the +summary too, and so does a rule on a summary that a chain of summaries rolls +the first one up into. A stored computed field of any object that reads the +summary one hop (`record.invoice.line_count`) counts as well, since it stores +what it reads at its own write. Then every roll-up of that child object +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. +**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. **Concurrent writes are not guaranteed (并发不保证):** two writes in flight at the same time each read the summary they started from, so a guard like the one above can still admit one row from each. diff --git a/packages/core/src/security/second-object-read-exposure.pin.test.ts b/packages/core/src/security/second-object-read-exposure.pin.test.ts index a71a20b79de..541496d66f5 100644 --- a/packages/core/src/security/second-object-read-exposure.pin.test.ts +++ b/packages/core/src/security/second-object-read-exposure.pin.test.ts @@ -253,6 +253,14 @@ const CALLERS: Record = { kind: 'not-a-served-read', reason: "resolves a seed's references at install, under the system identity; serves nothing to a caller", }, + // [#33795] The batch scope's rule-read test (ruling 6928862195 B). + 'packages/objectql/src/summary-rule-reads.ts': { + kind: 'not-a-served-read', + reason: + "names the object a validation rule's or a computed field's one hop reaches, from the declarations in the " + + 'registry, only to decide whether a roll-up recompute inside a bulk update runs at once or at the end of the ' + + 'batch; it reads no record and serves nothing of the target to any caller', + }, // ADR-0100: the credential-column guard's filter / sort half. 'packages/objectql/src/credential-evaluation-guard.ts': { kind: 'not-a-served-read', diff --git a/packages/metadata-protocol/src/host-engine.ts b/packages/metadata-protocol/src/host-engine.ts index 577c9fd61e6..d83f631a095 100644 --- a/packages/metadata-protocol/src/host-engine.ts +++ b/packages/metadata-protocol/src/host-engine.ts @@ -64,6 +64,15 @@ export interface MetadataHostEngine extends IDataEngine { * see `protocol-stored-expression-fill.ts`. */ captureStoredExpressions?(object: string): StoredExpressionFillCapture; + /** + * [#33795] The engine's roll-up batch scope, typed off the `objectql` slot + * contract for the reason `transaction` is, and optional there as here by + * ruling 6922040858. The bulk update doors (`runUpdateManyLoop`, and the + * update arm of `runBatchDataLoop`) run their per-row loop inside it, so a + * batch recomputes its parents' summaries once. Degrading means today's + * per-row recompute: the same values, more statements. + */ + deferSummaryRecompute?: IObjectQLEngine['deferSummaryRecompute']; // Protocol accesses additional engine members structurally; keep it permissive // for this relocation (behavior unchanged — the concrete engine is injected). [key: string]: any; diff --git a/packages/metadata-protocol/src/protocol-batch-data.ts b/packages/metadata-protocol/src/protocol-batch-data.ts index 7edb6a8e66e..d5ef4f2469f 100644 --- a/packages/metadata-protocol/src/protocol-batch-data.ts +++ b/packages/metadata-protocol/src/protocol-batch-data.ts @@ -323,10 +323,81 @@ function landedDespiteStaleSummary(e: unknown, atomic: boolean, object: string): return stale.written; } +/** + * [#33795] A per-row bulk UPDATE loop, run as one roll-up batch: inside the + * engine's `deferSummaryRecompute` (optional on the engine contract by + * ruling 6922040858), every row's `summary` recompute is recorded and runs + * once when the loop has settled — one grouped aggregate per summary field + * and one write per parent, where the loop alone paid a recompute per row. + * Each row's hooks, validation, audit and realtime run where they ran. + * + * Probed, never assumed: an engine without the member runs the loop as it + * always has, recomputing after each row — the same values, more statements. + * + * How the batch ends, by arm — the per-row `.catch` above no longer meets a + * stale-roll-up refusal inside a scope, because the recompute is not run + * there; the scope throws it once, at the end, its `written` the loop's + * outcome: + * + * - NON-ATOMIC: the rows are stored; only the named summaries are stale. The + * outcome is answered as it stands, with the stale column logged at `error` + * once, as `landedDespiteStaleSummary` logs a row's. + * - ATOMIC: this runs inside the batch's transaction (the loop is + * `runAtomicBatch`'s `runLoop`), so the recompute precedes the commit. A + * refusal fails the last row that landed with the refusal's own row error — + * the row a per-row recompute would have failed last — so + * `runAtomicBatch`'s `failed > 0` rolls the batch back and answers the same + * rolled-back envelope a per-row failure answers. A loop that already + * failed a row rolls back as it is. + * + * Every other error is rethrown unchanged; the scope has already recomputed + * the parents of the rows that landed before it. + */ +async function inSummaryBatch( + engine: BatchDataHost['engine'], + object: string, + atomic: boolean, + operation: string, + runLoop: () => Promise, +): Promise { + if (typeof engine?.deferSummaryRecompute !== 'function') return await runLoop(); + try { + return await engine.deferSummaryRecompute(runLoop); + } catch (e: unknown) { + const stale = staleSummaryRefusalOrThrow(e); + const outcome = stale.written as BatchDataLoopOutcome; + if (!atomic) { + for (const line of staleSummaryAnswerLines(stale, object)) console.error(`[Protocol] ${line}`); + return outcome; + } + if (outcome.failed > 0) return outcome; + const results = outcome.results.slice(); + let last = results.length - 1; + while (last >= 0 && !results[last]!.success) last--; + if (last < 0) return outcome; + const landed = results[last]!; + results[last] = { id: landed.id, success: false, index: landed.index, errors: [toRowApiError(stale, rowOperationFailureFallback(operation))] }; + return { results, succeeded: outcome.succeeded - 1, failed: outcome.failed + 1 }; + } +} + /** The body of `ObjectStackProtocolImplementation#runBatchDataLoop`; the method's docblock there is its contract. */ export async function runBatchDataLoop( this: Pick, - args: { + args: BatchDataLoopArgs, +): Promise { + // [#33795] The UPDATE arm is one roll-up batch, as `runUpdateManyLoop` is: + // the parents' summaries recompute once, when the loop has settled, on + // every way out of it (`inSummaryBatch`). The other operations keep their + // per-row recompute, which the ruling did not move. + if (args.operation === 'update') { + return await inSummaryBatch(this.engine, args.object, args.atomic, args.operation, () => runBatchDataRows.call(this, args)); + } + return await runBatchDataRows.call(this, args); +} + +/** The arguments of {@link runBatchDataLoop}, typed once for it and the loop it runs. */ +interface BatchDataLoopArgs { object: string; operation: BatchUpdateRequest['operation']; records: BatchUpdateRequest['records']; @@ -334,7 +405,13 @@ export async function runBatchDataLoop( batchSchema: any; context: any; atomic: boolean; -}): Promise { +} + +/** The per-row loop of {@link runBatchDataLoop}, every operation's arm. */ +async function runBatchDataRows( + this: Pick, + args: BatchDataLoopArgs, +): Promise { const { object, operation, records, options, batchSchema, context, atomic } = args; const results: BatchDataRowResult[] = []; let succeeded = 0; @@ -838,65 +915,69 @@ export async function runUpdateManyLoop( atomic: boolean; }): Promise { const { object, records, options, context, atomic } = args; - const results: BatchDataRowResult[] = []; - let succeeded = 0; - let failed = 0; // [#7823] Ingress strip over each row's `data` payload — the bulk // update face is the same generic-data-path surface as the by-id // PATCH body, one row at a time. Resolved once; the loop reuses it. const updateManySchema = this.engine.registry?.getObject(object); - for (const [index, record] of records.entries()) { - try { - // [#3455] Two gaps the pre-#3455 loop had, both fixed per row: - // 1. `context` was never threaded — bulk updates ran the engine - // context-less, so RLS/FLS and `readonlyWhen` evaluated without - // the caller's principal. Thread it like single-write updateData. - // 2. `onFieldsDropped` was never wired — the same static `readonly` - // (#2948) / `readonlyWhen` (#3042) strips that single-write now - // surfaces (#3431) happened silently here. Collect per row. - // - // [#5100] Same guard as `runBatchDataLoop`'s update branch - // (#4793), same classification: an id-less row is a CALLER - // error — VALIDATION_FAILED/400 — not a data-state one. The - // REST entrance already rejects it (`UpdateManyRecordSchema` - // requires `id`, #3939), but that invariant lives two packages - // away; unguarded, an in-process caller's malformed row - // reached the probe and the write as `{ id: undefined }`, - // whose reading is up to each driver's undefined-where-key - // handling — at best a 404 with `undefined` interpolated into - // the message, at worst a where-clause with no id at all. - if (!record.id) throw rowRequiredIdError('update'); - const dropped: DroppedFieldsEvent[] = []; - const opts: any = { where: { id: record.id }, onFieldsDropped: (e: DroppedFieldsEvent) => { dropped.push(e); } }; - if (context !== undefined) opts.context = context; - const updated = byIdUpdateRecord(await this.engine.update(object, record.data || {}, opts).catch((e: unknown) => landedDespiteStaleSummary(e, atomic, object))); - // [#5088] Third gap, the same shape: no existence answer. A row - // naming no record came back `INTERNAL_ERROR` from #4775's - // condition abort — blaming the hook for a caller's stale id. It - // answers what the single-record PATCH answers now, asked where - // that door asks it: AFTER the engine has judged the write (its - // refusals, then its not-found gate ahead of every hook), so a - // refused row reads the same whether or not its id names a - // record — see `assertRecordExists`. - if (updated == null) await this.assertRecordExists(object, record.id); - omitInternalFieldsFromWriteResponse(updateManySchema, updated); // [#7823] - results.push({ id: record.id, success: true, data: updated, index, ...(dropped.length > 0 ? { droppedFields: dropped } : {}) }); - succeeded++; - } catch (err: any) { - results.push({ id: record.id, success: false, index, errors: [toRowApiError(err, rowOperationFailureFallback('update'))] }); - failed++; - if (atomic) { - // Abort on the first failure; the caller rolls back. - break; - } - if (!options?.continueOnError) { - break; + // [#33795] One roll-up batch: the parents' summaries recompute once, when + // the loop has settled, on every way out of it (`inSummaryBatch`). + return await inSummaryBatch(this.engine, object, atomic, 'update', async () => { + const results: BatchDataRowResult[] = []; + let succeeded = 0; + let failed = 0; + for (const [index, record] of records.entries()) { + try { + // [#3455] Two gaps the pre-#3455 loop had, both fixed per row: + // 1. `context` was never threaded — bulk updates ran the engine + // context-less, so RLS/FLS and `readonlyWhen` evaluated without + // the caller's principal. Thread it like single-write updateData. + // 2. `onFieldsDropped` was never wired — the same static `readonly` + // (#2948) / `readonlyWhen` (#3042) strips that single-write now + // surfaces (#3431) happened silently here. Collect per row. + // + // [#5100] Same guard as `runBatchDataLoop`'s update branch + // (#4793), same classification: an id-less row is a CALLER + // error — VALIDATION_FAILED/400 — not a data-state one. The + // REST entrance already rejects it (`UpdateManyRecordSchema` + // requires `id`, #3939), but that invariant lives two packages + // away; unguarded, an in-process caller's malformed row + // reached the probe and the write as `{ id: undefined }`, + // whose reading is up to each driver's undefined-where-key + // handling — at best a 404 with `undefined` interpolated into + // the message, at worst a where-clause with no id at all. + if (!record.id) throw rowRequiredIdError('update'); + const dropped: DroppedFieldsEvent[] = []; + const opts: any = { where: { id: record.id }, onFieldsDropped: (e: DroppedFieldsEvent) => { dropped.push(e); } }; + if (context !== undefined) opts.context = context; + const updated = byIdUpdateRecord(await this.engine.update(object, record.data || {}, opts).catch((e: unknown) => landedDespiteStaleSummary(e, atomic, object))); + // [#5088] Third gap, the same shape: no existence answer. A row + // naming no record came back `INTERNAL_ERROR` from #4775's + // condition abort — blaming the hook for a caller's stale id. It + // answers what the single-record PATCH answers now, asked where + // that door asks it: AFTER the engine has judged the write (its + // refusals, then its not-found gate ahead of every hook), so a + // refused row reads the same whether or not its id names a + // record — see `assertRecordExists`. + if (updated == null) await this.assertRecordExists(object, record.id); + omitInternalFieldsFromWriteResponse(updateManySchema, updated); // [#7823] + results.push({ id: record.id, success: true, data: updated, index, ...(dropped.length > 0 ? { droppedFields: dropped } : {}) }); + succeeded++; + } catch (err: any) { + results.push({ id: record.id, success: false, index, errors: [toRowApiError(err, rowOperationFailureFallback('update'))] }); + failed++; + if (atomic) { + // Abort on the first failure; the caller rolls back. + break; + } + if (!options?.continueOnError) { + break; + } } } - } - return { results, succeeded, failed }; + return { results, succeeded, failed }; + }); } /** The body of `ObjectStackProtocolImplementation#buildUpdateManyResponse`; the method's docblock there is its contract. */ diff --git a/packages/metadata-protocol/src/protocol.many-data-atomic.test.ts b/packages/metadata-protocol/src/protocol.many-data-atomic.test.ts index 55a83103bff..35a595403c7 100644 --- a/packages/metadata-protocol/src/protocol.many-data-atomic.test.ts +++ b/packages/metadata-protocol/src/protocol.many-data-atomic.test.ts @@ -21,6 +21,9 @@ // test reads the store back afterwards. import { describe, it, expect, vi } from 'vitest'; +// The protocol module reaches `@objectstack/lint` by a dynamic import; its first +// load is paid here, at collection, not inside a case's clocked window. +import '@objectstack/lint'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch, assertEngineFindOnePredicate } from '@objectstack/metadata-core'; import { ObjectStackProtocolImplementation } from './protocol.js'; @@ -371,3 +374,147 @@ describe('many-data non-atomic — unchanged (#4620 regression net)', () => { expect(t.rows.get('a')).toEqual({ id: 'a', title: 'a-new' }); }); }); + +/** + * [#33795] The engine's optional roll-up batch scope (`deferSummaryRecompute`, + * ruling 6922040858), as the bulk update doors use it. The fake scope below is + * the contract's shape: run the callback, then "recompute" once — or throw the + * engine's stale-roll-up refusal (`ERR_SUMMARY_RECOMPUTE`) whose `written` is + * the callback's result. + */ +function armBatchScope(t: ReturnType, opts: { failRecompute?: boolean } = {}) { + const recompute = vi.fn((_commitsSoFar: number) => {}); + t.engine.deferSummaryRecompute = vi.fn(async (callback: () => Promise) => { + const result = await callback(); + recompute(t.commits.length); + if (opts.failRecompute) { + throw Object.assign(new Error('Roll-up summary recompute failed after retries for 1 parent record(s)'), { + code: 'ERR_SUMMARY_RECOMPUTE', + written: result, + failures: [{ childObject: 'invoice', parentObject: 'account', parentId: 'acc-1', field: 'invoice_total' }], + }); + } + return result; + }); + /** Every `engine.update` ran inside the scope: after it was entered, before its one recompute. */ + const everyUpdateInScope = () => { + const entered = (t.engine.deferSummaryRecompute as any).mock.invocationCallOrder[0]; + const recomputed = recompute.mock.invocationCallOrder[0]; + return t.update.mock.invocationCallOrder.every((at: number) => at > entered && at < recomputed); + }; + return { recompute, everyUpdateInScope }; +} + +describe('[#33795] the bulk update doors run as one roll-up batch', () => { + it('updateManyData runs every row inside the scope, and the scope recomputes once', async () => { + const t = makeStoreEngine(); + const s = armBatchScope(t); + const p = new ObjectStackProtocolImplementation(t.engine); + const res: any = await p.updateManyData({ + object: 'invoice', + records: [{ id: 'a', data: { title: 'a-new' } }, { id: 'b', data: { title: 'b-new' } }, { id: 'c', data: { title: 'c-new' } }], + } as any); + expect(res).toMatchObject({ success: true, succeeded: 3, failed: 0 }); + expect(t.engine.deferSummaryRecompute).toHaveBeenCalledTimes(1); + expect(s.recompute).toHaveBeenCalledTimes(1); + expect(t.update).toHaveBeenCalledTimes(3); + expect(s.everyUpdateInScope()).toBe(true); + }); + + it('a non-atomic batch stopped by a failed row still ends the scope over the rows that landed', async () => { + const t = makeStoreEngine(); + const s = armBatchScope(t); + const p = new ObjectStackProtocolImplementation(t.engine); + const res: any = await p.updateManyData({ + object: 'invoice', + records: [{ id: 'a', data: { title: 'a-new' } }, { id: 'b', data: { title: POISON } }, { id: 'c', data: { title: 'c-new' } }], + } as any); + expect(t.rows.get('a')).toEqual({ id: 'a', title: 'a-new' }); + expect(res).toMatchObject({ success: false, succeeded: 1, failed: 2 }); + expect(res.results[2].errors?.[0]?.code).toBe('NOT_ATTEMPTED'); + expect(s.recompute).toHaveBeenCalledTimes(1); + expect(s.everyUpdateInScope()).toBe(true); + }); + + it('non-atomic: a failed end-of-batch recompute keeps the rows written and is logged once at error', async () => { + const t = makeStoreEngine(); + armBatchScope(t, { failRecompute: true }); + const p = new ObjectStackProtocolImplementation(t.engine); + const errors = vi.spyOn(console, 'error').mockImplementation(() => {}); + try { + const res: any = await p.updateManyData({ + object: 'invoice', + records: [{ id: 'a', data: { title: 'a-new' } }, { id: 'b', data: { title: 'b-new' } }], + } as any); + expect(res).toMatchObject({ success: true, succeeded: 2, failed: 0 }); + expect(t.rows.get('b')).toEqual({ id: 'b', title: 'b-new' }); + const lines = errors.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('account.invoice_total')); + expect(lines).toHaveLength(1); + } finally { + errors.mockRestore(); + } + }); + + it('atomic: the recompute runs inside the transaction, before the commit', async () => { + const t = makeStoreEngine(); + const s = armBatchScope(t); + const p = new ObjectStackProtocolImplementation(t.engine); + const res: any = await p.updateManyData({ + object: 'invoice', + records: [{ id: 'a', data: { title: 'a-new' } }, { id: 'b', data: { title: 'b-new' } }], + options: { atomic: true }, + } as any); + expect(res).toMatchObject({ success: true, succeeded: 2 }); + expect(s.recompute).toHaveBeenCalledWith(0); // no commit yet when it ran + expect(t.commits).toHaveLength(1); + }); + + it('atomic: a failed end-of-batch recompute rolls the batch back with the rolled-back envelope a failed row answers', async () => { + const t = makeStoreEngine(); + armBatchScope(t, { failRecompute: true }); + const p = new ObjectStackProtocolImplementation(t.engine); + const res: any = await p.updateManyData({ + object: 'invoice', + records: [{ id: 'a', data: { title: 'a-new' } }, { id: 'b', data: { title: 'b-new' } }, { id: 'c', data: { title: 'c-new' } }], + options: { atomic: true }, + } as any); + // Nothing landed. + expect(t.rows.get('a')).toEqual({ id: 'a', title: 'a-old' }); + expect(t.rows.get('c')).toEqual({ id: 'c', title: 'c-old' }); + expect(t.rollbacks).toHaveLength(1); + expect(t.commits).toHaveLength(0); + // The envelope a per-row recompute failure answered: the last row + // carries the refusal's row error, the earlier rows ROLLED_BACK. + expect(res).toMatchObject({ success: false, succeeded: 0, failed: 3, total: 3 }); + expect(res.results.map((r: any) => r.errors?.[0]?.code)).toEqual(['ROLLED_BACK', 'ROLLED_BACK', 'ERR_SUMMARY_RECOMPUTE']); + expect(res.results[2].errors?.[0]?.message).toBe('The update of this record failed. The reason is in the server log.'); + expect(res.results[0].errors?.[0]?.message).toContain('record 2 failed'); + }); + + it('an engine without the member keeps the per-row loop unchanged', async () => { + const t = makeStoreEngine(); + expect(t.engine.deferSummaryRecompute).toBeUndefined(); + const p = new ObjectStackProtocolImplementation(t.engine); + const res: any = await p.updateManyData({ + object: 'invoice', + records: [{ id: 'a', data: { title: 'a-new' } }, { id: 'b', data: { title: 'b-new' } }], + } as any); + expect(res).toMatchObject({ success: true, succeeded: 2, failed: 0 }); + }); + + it('batchData: the update arm runs inside the scope; the delete arm does not enter it', async () => { + const t = makeStoreEngine(); + const s = armBatchScope(t); + const p = new ObjectStackProtocolImplementation(t.engine); + const updated: any = await p.batchData({ + object: 'invoice', + request: { operation: 'update', records: [{ id: 'a', data: { title: 'a-new' } }, { id: 'b', data: { title: 'b-new' } }] }, + } as any); + expect(updated).toMatchObject({ success: true, succeeded: 2 }); + expect(t.engine.deferSummaryRecompute).toHaveBeenCalledTimes(1); + expect(s.everyUpdateInScope()).toBe(true); + await p.batchData({ object: 'invoice', request: { operation: 'delete', records: [{ id: 'c' }] } } as any); + expect(t.engine.deferSummaryRecompute).toHaveBeenCalledTimes(1); + expect(t.rows.has('c')).toBe(false); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 67c695f4298..82a30c838f1 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -5719,6 +5719,14 @@ export class ObjectStackProtocolImplementation implements * read, since the fork's own note says why), so a fallback insert could * only bury a real update failure under the duplicate-key error of * inserting a row the caller was just shown to read. + * + * [#33795] The `update` operation runs as ONE roll-up batch, inside the + * engine's optional `deferSummaryRecompute` when the engine has it (ruling + * 6922040858): the parents' `summary` fields recompute once, when the + * loop has settled, instead of after each row. A summary field a rule + * reads still recomputes after each row (ruling 6928862195), so a rule + * answers as one-by-one updates do; a hook reads the value from before + * the batch. The other operations keep their per-row recompute. */ private runBatchDataLoop(args: { object: string; @@ -5972,6 +5980,18 @@ export class ObjectStackProtocolImplementation implements * `continueOnError` — whose own contract text already scopes it to * `atomic=false`, and which has nothing to continue toward when every write * so far is about to be undone. + * + * [#33795] The loop is ONE roll-up batch, inside the engine's optional + * `deferSummaryRecompute` when the engine has it (ruling 6922040858): the + * parents' `summary` fields recompute once, when the loop has settled, on + * every way out of it — finished, stopped on a failed row, or thrown — over + * the rows that landed. A summary field a rule reads still recomputes + * after each row (ruling 6928862195), so a rule answers as one-by-one + * updates do; a hook reads the value from before the batch. Atomic: the + * recompute runs inside the transaction, + * before the commit, and its failure rolls the batch back with the same + * envelope a failed row answers. Non-atomic: its failure is logged and the + * rows stay written. An engine without the member recomputes per row. */ private runUpdateManyLoop(args: { object: string; diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 40557f7cfa5..a6fbb7129cd 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -43,8 +43,9 @@ import type { QueryAST, ServiceObject } from '@objectstack/spec/data'; import { isStoredMetadataBodyObject } from '@objectstack/spec/kernel'; import type { ExecutionContext } from '@objectstack/spec/kernel'; import { withTransientRetry } from '@objectstack/core'; -import type { SummaryRecomputeFailure } from './summary-errors.js'; +import { SummaryRecomputeError, type SummaryRecomputeFailure } from './summary-errors.js'; import { aggregateSummaryValue, aggregateSummaryValues, summaryEmptySetValue } from './summary-aggregate.js'; +import { ruleReadKey, summaryFieldsReadByRules } from './summary-rule-reads.js'; import type { SummaryDescriptor } from './summary-aggregate.js'; import { ENGINE_WIRE_ONLY_SLOTS, WIRE_ONLY_CANONICAL_SHAPES } from './engine-top-level.js'; import { ObjectQLStatics as ObjectQL } from './engine.js'; @@ -73,6 +74,93 @@ import type { ObjectQL as ObjectQLClass } from './engine.js'; */ export const SUMMARY_RECOMPUTE_WRITE: unique symbol = Symbol.for('objectstack.objectql.summaryRecomputeWrite'); +/** + * [#33795] One open roll-up deferral scope + * ({@link SummariesAndExpansionFacet.deferSummaryRecompute}): the recomputes + * the writes inside it recorded instead of running, and whether it has ended. + * + * Ambient (`AsyncLocalStorage`, `ObjectQL.summaryBatchStore`), for the reason + * the transaction store is: a row's write reaches `recomputeSummaries` + * through hooks, `ctx.api` writes and the engine's own nested calls, none of + * which a caller could thread a marker through. + */ +export interface SummaryBatchScope { + /** + * The transaction the scope was opened in (the ambient one, or none). Only a + * write under this same transaction is recorded: the recompute at the end + * runs here, so a write under any other transaction (one a hook or a nested + * batch opened and may already have committed) recomputes at once, inside + * its own transaction, as outside any scope. + */ + transaction: unknown; + /** + * Set once the outermost callback has settled. Work the callback started + * and did not await still sees this scope ambiently; a write it makes after + * this point recomputes at once, as outside any scope, because the one + * recompute has already run. + */ + closed: boolean; + /** + * The recorded recomputes, merged per child object and caller + * ({@link summaryBatchKey}): each entry is one recompute when the scope ends. + * A row is recorded as the foreign keys the recompute reads off it, a copy + * taken when it was recorded, so a later strip of the row a caller is + * answered with (`omitInternalFieldsFromWriteResponse`) cannot move it. + */ + entries: Map[]; previous: Record[] }>; +} + +/** + * [#33795] Which recorded recomputes of a scope run as one: the same child + * object under the same caller. The recompute elevates the caller's context + * (`isSystem`), so what still tells two callers apart is the tenant it is + * scoped to and the user the parent's hooks are told triggered it. Identity + * of the context object would not do: the security middleware hands every + * operation its own copy of the caller's context. The transaction needs no + * place in the key: a scope records only writes under the transaction it was + * opened in ({@link SummaryBatchScope.transaction}), so every entry's recorded + * context carries that one. + */ +function summaryBatchKey(childObject: string, execCtx: ExecutionContext | undefined): string { + const ctx = execCtx as { tenantId?: unknown; userId?: unknown } | undefined; + return JSON.stringify([childObject, ctx?.tenantId ?? null, ctx?.userId ?? null]); +} + +/** + * [#33795] The transaction a write runs in, read the way `buildDriverOptions` + * reads it: the context's own handle unless its unit has closed, else the + * ambient one (ADR-0034), else none. + */ +function writeTransactionOf(host: Pick, execCtx: ExecutionContext | undefined): unknown { + const explicit = execCtx?.transaction; + return explicit !== undefined && !host.isClosedUnitHandle(explicit) ? explicit : host.txStore.getStore()?.transaction; +} + +/** + * [#33795] The summary fields a rule reads, per built summary index: rebuilt + * when the index is (a registry change), so it is invalidated with metadata + * changes exactly as the index is (`ensureSummaryIndexes`). + */ +const ruleReadsByIndex = new WeakMap>(); + +/** + * [#33795, ruling 6928862195 B] Does a rule read any of `descriptors`' + * summary fields (on another row, or on the summary's own row, through a + * formula or stored computed field, and up a chain of summaries to the + * rule)? Then this recompute runs at once inside a batch scope, so a rule's + * answer during a bulk update is the one-by-one answer + * (`summary-rule-reads.ts`). + */ +function rollUpReadByARule(host: Pick, descriptors: readonly SummaryDescriptor[]): boolean { + 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))); +} + /** * The `ObjectQL` members the bodies of {@link SummariesAndExpansionFacet} read — every one of * them, and no other. Each is typed AS the class member (an indexed access on @@ -91,12 +179,15 @@ export interface SummariesAndExpansionHost { getOwnedSummaryDescriptors: ObjectQLClass['getOwnedSummaryDescriptors']; getSummaryDescriptors: ObjectQLClass['getSummaryDescriptors']; invalidateSummaryIndex: ObjectQLClass['invalidateSummaryIndex']; + isClosedUnitHandle: ObjectQLClass['isClosedUnitHandle']; readonly logger: ObjectQLClass['logger']; serveReferenceNames: ObjectQLClass['serveReferenceNames']; + readonly summaryBatchStore: ObjectQLClass['summaryBatchStore']; summaryIndex: ObjectQLClass['summaryIndex']; summaryIndexByParent: ObjectQLClass['summaryIndexByParent']; summaryIndexRevision: ObjectQLClass['summaryIndexRevision']; readonly summaryRetryOptions: ObjectQLClass['summaryRetryOptions']; + readonly txStore: ObjectQLClass['txStore']; update: ObjectQLClass['update']; } @@ -476,9 +567,37 @@ export class SummariesAndExpansionFacet { * Insert, update, delete and a re-parent of a child all reach the master * through this one write, so they all stamp the same way. */ - static async recomputeSummaries(this: Pick, childObject: string, records: any, previous: any, execCtx?: ExecutionContext): Promise { + static async recomputeSummaries(this: Pick, childObject: string, records: any, previous: any, execCtx?: ExecutionContext): Promise { const descriptors = this.getSummaryDescriptors(childObject); if (descriptors.length === 0) return []; + + // [#33795] Inside an open deferral scope the recompute is RECORDED, not + // run: the scope runs it once, over every row recorded, when its callback + // settles (`deferSummaryRecompute`). Nothing else of the write moves — + // its hooks, validation, audit and realtime ran where they run. No + // failure can be reported here, so none is: the scope reports them. + // Only a write under the scope's own transaction is recorded; one under + // another (a hook's `ctx.api.transaction`, a nested atomic batch) may + // commit before the scope ends, so it recomputes now, inside it. A + // roll-up a rule reads is not recorded either (ruling 6928862195 B): it + // recomputes after each row, so the next row's rule, and the parent's + // own rule judging the recompute's write, read it as one-by-one updates + // would. + const scope = this.summaryBatchStore.getStore(); + if (scope && !scope.closed && writeTransactionOf(this, execCtx) === scope.transaction && !rollUpReadByARule(this, descriptors)) { + const fkFields = [...new Set(descriptors.map((d) => d.fkField))]; + const keysOf = (r: unknown): Record => { + const keys: Record = {}; + if (r && typeof r === 'object') for (const f of fkFields) keys[f] = (r as Record)[f]; + return keys; + }; + const key = summaryBatchKey(childObject, execCtx); + let entry = scope.entries.get(key); + if (!entry) { entry = { childObject, execCtx, records: [], previous: [] }; scope.entries.set(key, entry); } + for (const r of Array.isArray(records) ? records : records ? [records] : []) entry.records.push(keysOf(r)); + for (const p of Array.isArray(previous) ? previous : previous ? [previous] : []) entry.previous.push(keysOf(p)); + return []; + } // The elevation described above. Built once per call, spread from the // caller's context so transaction / tenant / timezone ride along. const systemCtx = { ...(execCtx ?? {}), isSystem: true } as ExecutionContext; @@ -618,6 +737,92 @@ export class SummariesAndExpansionFacet { return failures; } + /** + * [#33795] The body of `ObjectQL#deferSummaryRecompute`: run `callback` as + * ONE batch for roll-up summaries. Every `summary` recompute a write inside + * it would run is recorded instead, and runs once when the callback + * settles: per child object and caller, one grouped aggregate per summary + * field per id chunk and one write per parent (a roll-up cycle keeps its + * per-parent order), instead of one recompute per row. Optional on + * `IObjectQLEngine` by ruling 6922040858; + * the bulk update doors probe for it. + * + * Entered and left by the engine, as `ObjectQL#transaction` is: there is no + * begin and end pair to leave unbalanced. A nested call JOINS the open + * scope, and the outermost call runs the recompute. + * + * Only the roll-up recompute moves. Each write's hooks, validation, audit + * and realtime run where they run outside a scope. A summary field a rule + * reads is never deferred (ruling 6928862195 B, `summary-rule-reads.ts`): + * its recompute runs after each row, inside the scope, so the next row's + * rule, and a rule of the parent judging the recompute's own write, reads + * what one-by-one writes would have it read, for every summary function. A hook or flow step that reads a parent's summary during the + * batch reads the value from before the batch, as it does during a + * multi-row insert. + * + * Every way out recomputes, over every write recorded: + * + * - the callback resolves and every parent recomputes: its result; + * - the callback resolves and a parent cannot be recomputed (after the + * transient retries): `SummaryRecomputeError` (`ERR_SUMMARY_RECOMPUTE`), + * `written` the callback's result — the writes are stored, the named + * summaries are stale, as when a single write's recompute fails; + * - the callback throws: the recompute still runs, for the writes that + * landed before the throw, and the callback's error is rethrown; a + * recompute failure there is logged, as each one is. + * + * Called inside a `transaction`, the recompute runs inside it, before + * the commit, and a caller that lets the refusal escape rolls the batch back. + * Only writes under the transaction the scope was opened in are deferred. + * A write under another transaction opened within the scope (a hook's + * `ctx.api.transaction`, an atomic batch reached from inside a non-atomic + * one) recomputes at once, inside that transaction, as outside any scope: + * that transaction may commit before the scope ends, and its recompute + * belongs before its commit. + * A write recorded after the callback settled (work it started and did not + * await) recomputes at once. + */ + static async deferSummaryRecompute(this: Pick, callback: () => Promise): Promise { + // A nested call joins the open scope: the outermost one runs the recompute. + const open = this.summaryBatchStore.getStore(); + if (open && !open.closed) return await callback(); + + const scope: SummaryBatchScope = { closed: false, transaction: writeTransactionOf(this, undefined), entries: new Map() }; + // The recorded recomputes, run once the callback has settled — outside + // the scope, so each parent write recomputes ITS parents at once, in + // dependency order, as a multi-row write's recompute always has. Inside + // the caller's transaction when there is one: this runs before the + // caller's commit. + const recompute = async (): Promise => { + scope.closed = true; + const failures: SummaryRecomputeFailure[] = []; + for (const { childObject, execCtx, records, previous } of scope.entries.values()) { + failures.push(...await SummariesAndExpansionFacet.recomputeSummaries.call(this, childObject, records, previous, execCtx)); + } + return failures; + }; + + let result: T; + try { + result = await this.summaryBatchStore.run(scope, callback); + } catch (err) { + // Every way out recomputes: rows written before the throw keep their + // writes, so their parents are recomputed; each failure is already + // logged where it happened. The callback's own error is the answer. + try { + await recompute(); + } catch (recomputeErr) { + this.logger.warn('Roll-up summary recompute at the end of a failed batch failed', { error: (recomputeErr as any)?.message }); + } + throw err; + } + const failures = await recompute(); + // The callback's writes are stored; only roll-ups are stale. The same + // refusal a single write throws, its `written` the callback's result. + if (failures.length > 0) throw new SummaryRecomputeError(failures, result); + return result; + } + /** * Post-process expand: resolve lookup/master_detail fields by batch-loading related records. * diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 8d789a8785f..19c1dbc53e2 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -339,7 +339,7 @@ import { SecretsAndRoutingFacet } from './engine-secrets-and-routing.js'; // [#29986 codemod] Migration flags, value-shape deviations, creation attestations, destroy: the methods of the same names below hand the bodies what they read (`MigrationStateHost`). import { MigrationStateFacet } from './engine-migration-state.js'; // [#29986 codemod] Summary indexes, related-record expansion, file and reference hydration: the methods of the same names below hand the bodies what they read (`SummariesAndExpansionHost`). -import { SummariesAndExpansionFacet } from './engine-summaries-and-expansion.js'; +import { SummariesAndExpansionFacet, type SummaryBatchScope } from './engine-summaries-and-expansion.js'; // [#29986 codemod] Query lowering, search, find and findOne: the methods of the same names below hand the bodies what they read (`FindHost`). import { FindFacet } from './engine-find.js'; // [#29986 codemod] Write preparation and insert: the methods of the same names below hand the bodies what they read (`InsertHost`). @@ -447,6 +447,9 @@ export class ObjectQL implements IObjectQLEngine { */ private readonly cascadeDeleteSets = new AsyncLocalStorage(); + /** [#33795] The open roll-up batch scope (`SummaryBatchScope` says why it is ambient). */ + private readonly summaryBatchStore = new AsyncLocalStorage(); + /** * [#23221] The child delete {@link walkReferencingRelations} is issuing right * now, so that `delete()` can tell the cascade's own child delete from every @@ -4130,6 +4133,11 @@ export class ObjectQL implements IObjectQLEngine { return summaryRefreshesSettled(this); } + /** [#33795] `IObjectQLEngine.deferSummaryRecompute`: the body and its docblock are in `engine-summaries-and-expansion.ts`. */ + deferSummaryRecompute(callback: () => Promise): Promise { + return SummariesAndExpansionFacet.deferSummaryRecompute.call(summariesAndExpansionHost.of(this), callback) as Promise; + } + private initializeSummaryFields(object: string, record: any): any { // [#29986 codemod] The body moved to `engine-summaries-and-expansion.ts`, its docblock with it (see `SummariesAndExpansionHost`). return SummariesAndExpansionFacet.initializeSummaryFields.call(summariesAndExpansionHost.of(this), object, record); @@ -6141,6 +6149,7 @@ export class ObjectQL implements IObjectQLEngine { invalidateSummaryIndex: (...a) => engine.invalidateSummaryIndex(...a), get logger() { return engine.logger; }, serveReferenceNames: (...a) => engine.serveReferenceNames(...a), + get summaryBatchStore() { return engine.summaryBatchStore; }, get summaryIndex() { return engine.summaryIndex; }, set summaryIndex(v) { engine.summaryIndex = v; }, get summaryIndexByParent() { return engine.summaryIndexByParent; }, @@ -6148,6 +6157,8 @@ export class ObjectQL implements IObjectQLEngine { get summaryIndexRevision() { return engine.summaryIndexRevision; }, set summaryIndexRevision(v) { engine.summaryIndexRevision = v; }, get summaryRetryOptions() { return engine.summaryRetryOptions; }, + get txStore() { return engine.txStore; }, + isClosedUnitHandle: (...a) => engine.isClosedUnitHandle(...a), update: (...a) => engine.update(...a), })); transactionsSectionHost.install((engine) => ({ diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 5a9fe8bb3f3..c19c8b41f78 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -368,6 +368,16 @@ const READERS: Record = { disposition: 'caller-predicate', why: VALIDATION_RULE, }, + // [#33795] A batch scope keeps a roll-up a rule reads out of the deferral; + // the test names the object a rule's one hop reaches, from the declaration. + 'summary-rule-reads.ts#summaryFieldsReadByRules :: referenceTargetOf()': { + disposition: 'caller-predicate', + why: "names the object a validation rule's own one-hop relation path reaches, to judge whether it reads a summary field; it reads no row", + }, + 'summary-rule-reads.ts#keysReadFrom :: referenceTargetOf()': { + disposition: 'caller-predicate', + why: "names the object a computed field's own one-hop expression reaches, to judge whether a rule reads a summary through it; it reads no row", + }, 'engine-summaries-and-expansion.ts#buildSummaryIndex :: referenceCarrierOf()': { disposition: 'author-declared', why: diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 7ebb6a61f4b..f12787bed00 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -790,3 +790,473 @@ describe('[#33795] grouped roll-up recompute', () => { expect(storeFor('inv').get(b.id)).toMatchObject({ line_total: 2, line_count: 1 }); }); }); + +describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + let log: ReturnType['log']; + let driver: any; + /** Every write to an `inv` parent, in order: the recompute's own writes are the only ones these tests make. */ + let parentWrites: Array>; + + beforeEach(async () => { + engine = new ObjectQL(); + const d = makeDriver(); + storeFor = d.storeFor; + log = d.log; + driver = d.driver; + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registry.registerObject({ + name: 'region', + fields: { + name: { type: 'text' }, + grand_total: { type: 'summary', summaryOperations: { object: 'inv', field: 'line_total', function: 'sum' } }, + }, + } as any); + engine.registry.registerObject({ + name: 'inv', + fields: { + name: { type: 'text' }, + region: { type: 'lookup', reference: 'region' }, + line_total: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'sum' } }, + line_count: { type: 'summary', summaryOperations: { object: 'inv_line', function: 'count' } }, + }, + } as any); + engine.registry.registerObject({ + name: 'inv_line', + fields: { + amount: { type: 'number' }, + inv: { type: 'master_detail', reference: 'inv' }, + }, + } as any); + parentWrites = []; + engine.registerHook('beforeUpdate', async (ctx: any) => { parentWrites.push({ ...ctx.input.data }); }, { object: 'inv' }); + }); + + /** Three parents, two lines each: a=5, b=7, c=9. */ + async function seed() { + const [a, b, c] = await engine.insert('inv', [{ name: 'A' }, { name: 'B' }, { name: 'C' }]) as any[]; + const lines = await engine.insert('inv_line', [ + { inv: a.id, amount: 1 }, { inv: b.id, amount: 2 }, { inv: c.id, amount: 3 }, + { inv: a.id, amount: 4 }, { inv: b.id, amount: 5 }, { inv: c.id, amount: 6 }, + ]) as any[]; + parentWrites.length = 0; + return { a, b, c, lines }; + } + + const aggregateReads = (from: number) => log.slice(from).filter((e) => e.op === 'find' && e.object === 'inv_line').length; + + it('a loop of single-row updates recomputes once, when the scope ends', async () => { + const { a, b, c, lines } = await seed(); + const before = log.length; + const answer = await engine.deferSummaryRecompute(async () => { + for (const line of lines) await engine.update('inv_line', { amount: line.amount * 10 }, { where: { id: line.id } }); + // Nothing recomputed yet: every parent still holds its pre-batch value. + expect(parentWrites).toHaveLength(0); + return 'done'; + }); + expect(answer).toBe('done'); + // One write per parent for the whole batch (outside a scope: one per row), + // and one grouped aggregate per summary field (outside: one per row per field). + expect(parentWrites).toHaveLength(3); + expect(aggregateReads(before)).toBe(2); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 50, line_count: 2 }); + expect(storeFor('inv').get(b.id)).toMatchObject({ line_total: 70, line_count: 2 }); + expect(storeFor('inv').get(c.id)).toMatchObject({ line_total: 90, line_count: 2 }); + }); + + it('control: the same loop outside a scope recomputes after every row', async () => { + const { lines } = await seed(); + for (const line of lines) await engine.update('inv_line', { amount: line.amount * 10 }, { where: { id: line.id } }); + expect(parentWrites).toHaveLength(6); + }); + + it('a hook reading the parent summary during the batch reads the value from before the batch', async () => { + const { a, lines } = await seed(); + const seen: unknown[] = []; + engine.registerHook('beforeUpdate', async () => { + const parent = await engine.findOne('inv', { where: { id: a.id } }); + seen.push((parent as any)?.line_total); + }, { object: 'inv_line' }); + const mine = lines.filter((l: any) => l.inv === a.id); + await engine.deferSummaryRecompute(async () => { + for (const line of mine) await engine.update('inv_line', { amount: 100 }, { where: { id: line.id } }); + }); + // Both rows read 5, the pre-batch total; one by one, the second read 104. + expect(seen).toEqual([5, 5]); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 200 }); + }); + + it('a nested call joins the open scope; the outermost one recomputes', async () => { + const { a, lines } = await seed(); + await engine.deferSummaryRecompute(async () => { + await engine.deferSummaryRecompute(async () => { + await engine.update('inv_line', { amount: 0 }, { where: { id: lines[0].id } }); + }); + expect(parentWrites).toHaveLength(0); + await engine.update('inv_line', { amount: 0 }, { where: { id: lines[3].id } }); + }); + expect(parentWrites).toHaveLength(1); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 0, line_count: 2 }); + }); + + it('a summary over a summary recomputes up the chain when the scope ends', async () => { + const [r] = await engine.insert('region', [{ name: 'R' }]) as any[]; + const [a, b] = await engine.insert('inv', [{ name: 'A', region: r.id }, { name: 'B', region: r.id }]) as any[]; + const lines = await engine.insert('inv_line', [{ inv: a.id, amount: 10 }, { inv: b.id, amount: 32 }]) as any[]; + expect(storeFor('region').get(r.id).grand_total).toBe(42); + await engine.deferSummaryRecompute(async () => { + for (const line of lines) await engine.update('inv_line', { amount: 1 }, { where: { id: line.id } }); + expect(storeFor('region').get(r.id).grand_total).toBe(42); + }); + expect(storeFor('region').get(r.id).grand_total).toBe(2); + }); + + it('a callback that throws: the rows that landed are recomputed, and its error is rethrown', async () => { + const { a, b, lines } = await seed(); + const boom = new Error('row 2 refused'); + await expect(engine.deferSummaryRecompute(async () => { + await engine.update('inv_line', { amount: 0 }, { where: { id: lines[0].id } }); + await engine.update('inv_line', { amount: 0 }, { where: { id: lines[1].id } }); + throw boom; + })).rejects.toBe(boom); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 4 }); + expect(storeFor('inv').get(b.id)).toMatchObject({ line_total: 5 }); + }); + + it('a recompute that fails after the callback resolved: ERR_SUMMARY_RECOMPUTE, written = the callback result', async () => { + const { a, b, lines } = await seed(); + const update = driver.update; + driver.update = async (object: string, id: string, data: Record) => { + if (object === 'inv' && id === a.id) throw new Error('parent write refused'); + return update.call(driver, object, id, data); + }; + let caught: any; + try { + await engine.deferSummaryRecompute(async () => { + for (const line of lines.slice(0, 2)) await engine.update('inv_line', { amount: 0 }, { where: { id: line.id } }); + return { rows: 2 }; + }); + } catch (e) { caught = e; } + expect(caught?.code).toBe('ERR_SUMMARY_RECOMPUTE'); + expect(caught.written).toEqual({ rows: 2 }); + expect(caught.failures.map((f: any) => [f.parentId, f.field]).sort()).toEqual([[a.id, 'line_count'], [a.id, 'line_total']]); + // The rows are stored, and the other parent was still recomputed. + expect(storeFor('inv_line').get(lines[0].id).amount).toBe(0); + expect(storeFor('inv').get(b.id)).toMatchObject({ line_total: 5 }); + }); + + it('inside a transaction the recompute runs before the commit', async () => { + const { a, lines } = await seed(); + const events: string[] = []; + engine.registerHook('beforeUpdate', async () => { events.push('parent write'); }, { object: 'inv' }); + driver.commit = async () => { events.push('commit'); }; + await engine.transaction(async (trxCtx: any) => { + await engine.deferSummaryRecompute(async () => { + await engine.update('inv_line', { amount: 0 }, { where: { id: lines[0].id }, context: trxCtx }); + await engine.update('inv_line', { amount: 0 }, { where: { id: lines[3].id }, context: trxCtx }); + }); + }); + expect(events).toEqual(['parent write', 'commit']); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 0 }); + }); + + it('a write the callback started and did not await recomputes at once once the scope has ended', async () => { + const { a, lines } = await seed(); + let release!: () => void; + const gate = new Promise((r) => { release = r; }); + let late!: Promise; + await engine.deferSummaryRecompute(async () => { + late = (async () => { await gate; await engine.update('inv_line', { amount: 0 }, { where: { id: lines[0].id } }); })(); + }); + expect(parentWrites).toHaveLength(0); + release(); + await late; + expect(parentWrites).toHaveLength(1); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 4 }); + }); + + it('the scope is ambient: a hook-issued insert into a second child of the same parent is deferred to the end too', async () => { + // A second child object of `inv`, counted by a summary the recompute of + // `inv_line` does not touch, and a hook on each line that inserts a note. + engine.registry.registerObject({ + name: 'inv', + fields: { + name: { type: 'text' }, + region: { type: 'lookup', reference: 'region' }, + line_total: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'sum' } }, + line_count: { type: 'summary', summaryOperations: { object: 'inv_line', function: 'count' } }, + note_count: { type: 'summary', summaryOperations: { object: 'inv_note', function: 'count' } }, + }, + } as any); + engine.registry.registerObject({ + name: 'inv_note', + fields: { text: { type: 'text' }, inv: { type: 'master_detail', reference: 'inv' } }, + } as any); + const { a, b, c, lines } = await seed(); + engine.registerHook('afterUpdate', async (ctx: any) => { + const row = await engine.findOne('inv_line', { where: { id: ctx.id ?? ctx.input?.id } }); + await engine.insert('inv_note', { text: 'changed', inv: (row as any).inv }); + }, { object: 'inv_line' }); + const before = log.length; + await engine.deferSummaryRecompute(async () => { + for (const line of lines) await engine.update('inv_line', { amount: line.amount * 10 }, { where: { id: line.id } }); + // Six notes are stored, and no parent was recomputed for them yet. + expect(storeFor('inv_note').size).toBe(6); + expect(parentWrites).toHaveLength(0); + expect(storeFor('inv').get(a.id)).not.toHaveProperty('note_count', 2); + }); + // One recompute per child object for the batch, each one write per parent: + // 3 parents x 2 child objects, where a per-row loop pays 6 rows x 2. + expect(parentWrites).toHaveLength(6); + expect(log.slice(before).filter((e) => e.op === 'find' && e.object === 'inv_note').length).toBe(1); + for (const p of [a, b, c]) expect(storeFor('inv').get(p.id)).toMatchObject({ line_count: 2, note_count: 2 }); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 50 }); + }); + + it('a write under a transaction a hook opened and committed inside the batch recomputes in that transaction, not on its dead handle at the end', async () => { + // The sandbox runner's `ctx.api.transaction` is the discrete trio + // (`beginTransaction` / `commitTransaction`): with no transaction to join + // (a non-atomic bulk update) it opens and commits its own, before the + // batch ends. A driver call on a committed handle fails, as on knex. + driver.commit = async (h: any) => { h.done = true; }; + for (const op of ['find', 'findOne', 'create', 'update', 'delete', 'count', 'aggregate', 'bulkCreate', 'updateMany']) { + const real = driver[op]; + if (typeof real !== 'function') continue; + driver[op] = async (...args: any[]) => { + if (args.some((a) => a?.transaction?.done)) throw new Error('Transaction query already complete'); + return real.apply(driver, args); + }; + } + engine.registry.registerObject({ + name: 'inv', + fields: { + name: { type: 'text' }, + region: { type: 'lookup', reference: 'region' }, + line_total: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'sum' } }, + line_count: { type: 'summary', summaryOperations: { object: 'inv_line', function: 'count' } }, + note_count: { type: 'summary', summaryOperations: { object: 'inv_note', function: 'count' } }, + }, + } as any); + engine.registry.registerObject({ + name: 'inv_note', + fields: { text: { type: 'text' }, inv: { type: 'master_detail', reference: 'inv' } }, + } as any); + const { a, b, c, lines } = await seed(); + const api = engine.createContext({ isSystem: true }); + engine.registerHook('afterUpdate', async (ctx: any) => { + const row = await engine.findOne('inv_line', { where: { id: ctx.id ?? ctx.input?.id } }); + const unit = (await api.beginTransaction())!; + expect(unit.owned).toBe(true); + await unit.ctx.object('inv_note').insert({ text: 'changed', inv: (row as any).inv }); + await api.commitTransaction(unit.handle); + }, { object: 'inv_line' }); + await engine.deferSummaryRecompute(async () => { + for (const line of lines) await engine.update('inv_line', { amount: line.amount * 10 }, { where: { id: line.id } }); + }); + for (const p of [a, b, c]) expect(storeFor('inv').get(p.id)).toMatchObject({ line_count: 2, note_count: 2 }); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 50 }); + }); + + describe('[ruling 6928862195 B] a roll-up a rule reads is not deferred', () => { + const lineWith = (extra: Record) => engine.registry.registerObject({ + name: 'inv_line', + fields: { + amount: { type: 'number' }, + inv: { type: 'master_detail', reference: 'inv' }, + ...(extra.fields as object ?? {}), + }, + ...(extra.validations ? { validations: extra.validations } : {}), + } as any); + /** Parent writes made DURING the batch, and after it. */ + async function batchOfSix(): Promise<{ during: number; after: number }> { + const { lines } = await seed(); + let during = 0; + await engine.deferSummaryRecompute(async () => { + for (const line of lines) await engine.update('inv_line', { amount: line.amount * 10 }, { where: { id: line.id } }); + during = parentWrites.length; + }); + return { during, after: parentWrites.length - during }; + } + + it('(i) a validation rule on the child reading the parent summary one hop: each row recomputes at once', async () => { + lineWith({ validations: [{ name: 'cap', type: 'script', severity: 'error', message: 'cap', condition: 'record.inv.line_count > 1000' }] }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(i) a validation rule on ANOTHER object reading the parent summary: judged on the field read, not the object written', async () => { + engine.registry.registerObject({ + name: 'inv_memo', + fields: { inv: { type: 'lookup', reference: 'inv' } }, + validations: [{ name: 'cap', type: 'script', severity: 'error', message: 'cap', condition: 'record.inv.line_total > 100000' }], + } as any); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(ii) a field-level parent. predicate reading the parent summary: each row recomputes at once', async () => { + lineWith({ fields: { note: { type: 'text', readonlyWhen: 'parent.line_total > 100000' } } }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('a parent. predicate reading a field that is no summary (the showcase invoice line, parent.status) keeps the deferral', async () => { + lineWith({ fields: { note: { type: 'text', readonlyWhen: "parent.name == 'paid'", requiredWhen: "parent.name == 'x'" } } }); + expect(await batchOfSix()).toEqual({ during: 0, after: 3 }); + }); + + it('a rule reading another field of the related row keeps the deferral', async () => { + lineWith({ validations: [{ name: 'named', type: 'script', severity: 'error', message: 'named', condition: "record.inv.name == 'never'" }] }); + expect(await batchOfSix()).toEqual({ during: 0, after: 3 }); + }); + + /** `inv` as registered above, with `extra` fields and validations of its own. */ + const invWith = (extra: { fields?: Record; validations?: unknown[] }) => engine.registry.registerObject({ + name: 'inv', + fields: { + name: { type: 'text' }, + region: { type: 'lookup', reference: 'region' }, + line_total: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'sum' } }, + line_count: { type: 'summary', summaryOperations: { object: 'inv_line', function: 'count' } }, + ...(extra.fields ?? {}), + }, + ...(extra.validations ? { validations: extra.validations } : {}), + } as any); + + it('(iii) a validation rule of the parent reading its OWN summary: each row recomputes at once, so the rule judges every step', async () => { + invWith({ validations: [{ name: 'cap', type: 'script', severity: 'error', message: 'cap', condition: 'record.line_count > 1000' }] }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(iii) the same through `previous`, and through a conditional rule at depth', async () => { + invWith({ validations: [{ name: 'grow', type: 'conditional', when: "record.name != ''", then: { name: 'g', type: 'script', severity: 'error', message: 'g', condition: 'previous != null && previous.line_total > 100000' } }] }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(iii) a field-level requiredWhen of the parent reading its own summary', async () => { + invWith({ fields: { memo: { type: 'text', requiredWhen: 'record.line_total > 100000' } } }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(iii) a rule of the parent reading only its own non-summary fields keeps the deferral', async () => { + invWith({ validations: [{ name: 'named', type: 'script', severity: 'error', message: 'named', condition: "record.name == 'never'" }] }); + expect(await batchOfSix()).toEqual({ during: 0, after: 3 }); + }); + + /** `inv` with a formula over its own summary: `headroom = 1000000 - line_total`. */ + const withHeadroom = (extra: { fields?: Record; validations?: unknown[] } = {}) => invWith({ + fields: { headroom: { type: 'formula', returnType: 'number', expression: '1000000 - record.line_total' }, ...(extra.fields ?? {}) }, + ...(extra.validations ? { validations: extra.validations } : {}), + }); + + it('(i) through a formula: a child rule reading the parent formula computed from its summary', async () => { + withHeadroom(); + lineWith({ validations: [{ name: 'room', type: 'script', severity: 'error', message: 'room', condition: 'record.inv.headroom < 0' }] }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(ii) through a formula: a parent. predicate reading the header formula computed from its summary', async () => { + withHeadroom(); + lineWith({ fields: { note: { type: 'text', requiredWhen: 'parent.headroom < 0' } } }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(iii) through a formula: a rule of the parent reading its own formula computed from its summary', async () => { + withHeadroom({ validations: [{ name: 'room', type: 'script', severity: 'error', message: 'room', condition: 'record.headroom != null && record.headroom < 0' }] }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('through a stored computed field: an expression on a stored field of the parent reading its summary', async () => { + invWith({ fields: { doubled: { type: 'number', expression: 'record.line_total * 2' } } }); + lineWith({ validations: [{ name: 'dbl', type: 'script', severity: 'error', message: 'dbl', condition: 'record.inv.doubled > 100000000' }] }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(iii) a declared bound on a stored computed field of the parent calculated from its summary', async () => { + invWith({ fields: { room: { type: 'number', expression: '1000000 - record.line_total', min: -1000000000000 } } }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(iii) a declared bound on the summary itself', async () => { + invWith({ fields: { line_count: { type: 'summary', max: 1000, summaryOperations: { object: 'inv_line', function: 'count' } } } }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(iii) a declared precision on the summary itself', async () => { + invWith({ fields: { line_count: { type: 'summary', precision: 9, summaryOperations: { object: 'inv_line', function: 'count' } } } }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('(iii) an object-level unique index naming the summary', async () => { + engine.registry.registerObject({ + name: 'inv', + fields: { + name: { type: 'text' }, + region: { type: 'lookup', reference: 'region' }, + line_total: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'sum' } }, + line_count: { type: 'summary', summaryOperations: { object: 'inv_line', function: 'count' } }, + }, + indexes: [{ name: 'inv_total_once', fields: ['region', 'line_total'], unique: 'organization' }], + } as any); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('a declared index naming the summary that is not unique keeps the deferral', async () => { + engine.registry.registerObject({ + name: 'inv', + fields: { + name: { type: 'text' }, + region: { type: 'lookup', reference: 'region' }, + line_total: { type: 'summary', summaryOperations: { object: 'inv_line', field: 'amount', function: 'sum' } }, + line_count: { type: 'summary', summaryOperations: { object: 'inv_line', function: 'count' } }, + }, + indexes: [{ name: 'inv_by_total', fields: ['line_total'] }], + } as any); + expect(await batchOfSix()).toEqual({ during: 0, after: 3 }); + }); + + it('(iii) a stored computed field of the parent calculated from its summary, with no bound and no rule: its write judges it all the same', async () => { + invWith({ fields: { doubled: { type: 'number', expression: 'record.line_total * 2' } } }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('a stored computed field of the parent that reads no summary keeps the deferral', async () => { + invWith({ fields: { label: { type: 'text', expression: 'record.name' } } }); + expect(await batchOfSix()).toEqual({ during: 0, after: 3 }); + }); + + it('a stored computed field of the CHILD reading the parent summary one hop: each row recomputes at once', async () => { + lineWith({ fields: { seen: { type: 'number', expression: 'record.inv.line_count' } } }); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + + it('a formula (not stored) of the child reading the parent summary keeps the deferral: it is computed on read', async () => { + lineWith({ fields: { seen: { type: 'formula', returnType: 'number', expression: 'record.inv.line_count' } } }); + expect(await batchOfSix()).toEqual({ during: 0, after: 3 }); + }); + + it('a rule reading a formula that reads no summary keeps the deferral', async () => { + invWith({ fields: { shout: { type: 'formula', returnType: 'text', expression: 'record.name.upperAscii()' } } }); + lineWith({ validations: [{ name: 'shout', type: 'script', severity: 'error', message: 'shout', condition: "record.inv.shout == 'NEVER'" }] }); + expect(await batchOfSix()).toEqual({ during: 0, after: 3 }); + }); + + it('a chain: a rule on the grandparent reading a summary over the parent summary keeps the parent summary per row', async () => { + engine.registry.registerObject({ + name: 'region', + fields: { + name: { type: 'text' }, + grand_total: { type: 'summary', summaryOperations: { object: 'inv', field: 'line_total', function: 'sum' } }, + }, + validations: [{ name: 'cap', type: 'script', severity: 'error', message: 'cap', condition: 'record.grand_total > 1000000' }], + } as any); + expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); + }); + }); + + it('a scope with no roll-up write runs nothing', async () => { + const before = log.length; + await engine.deferSummaryRecompute(async () => { await engine.insert('region', { name: 'R' }); }); + expect(parentWrites).toHaveLength(0); + expect(aggregateReads(before)).toBe(0); + }); +}); diff --git a/packages/objectql/src/summary-rule-reads.ts b/packages/objectql/src/summary-rule-reads.ts new file mode 100644 index 00000000000..c0a2f92a1e6 --- /dev/null +++ b/packages/objectql/src/summary-rule-reads.ts @@ -0,0 +1,288 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33795] Which roll-up `summary` fields a rule reads (ruling 6928862195, + * letter B: 「被规则读到的合计不延后」). + * + * A bulk update runs inside the engine's roll-up batch scope + * (`deferSummaryRecompute`), which records each row's recompute and runs it + * once when the batch ends. A rule that reads the parent's summary would then + * read the value from before the batch on every row, where one-by-one updates + * read each earlier row's recompute: "a supplier has at most one primary + * contact" would admit two primaries set in one grid edit. So a summary field + * a rule reads is NOT deferred: inside the scope its recompute runs after each + * row, as it does outside one, and a rule's answer during a bulk update is the + * answer one-by-one updates give, for every summary function. + * + * "Read by a rule" is three classes, judged on the summary field that is read, + * never on the object written: + * + * - (i) a validation rule of ANY object that reads the field one hop through a + * reference (`record.supplier.primary_contact_count`), by the same judgement + * that decides which hops a rule is hydrated for + * ({@link collectPredicateRelationships}) — the class #25579 covers for a + * multi-row insert; + * - (ii) a field-level `requiredWhen` / `readonlyWhen` of a detail object that + * reads the field on its `parent` (the master-detail header), by field name; + * - (iii) a rule of the summary's OWN object that reads the field on `record` + * or `previous`: a validation rule (a CEL condition, or the field a + * `state_machine` / `format` / `json_schema` rule names) or a field-level + * `requiredWhen` / `readonlyWhen`. The recompute's own write is an update of + * that row, judged by those rules: one by one they judge every intermediate + * value (an atomic move A→B then B→A over a cap refuses the first), so + * deferred they would judge only the last. That write also judges every + * value it stores against its declaration, so the same holds without a + * rule: a declared bound on the summary itself (`min`, `max`, `minLength`, + * `maxLength`, `pattern`, `precision`, `unique`, `required`, or an + * object-level unique index naming it) counts as reading it, and EVERY + * stored computed field of its object counts as read, bound or not, since + * the write computes it and judges it whatever it declares (a bound, an + * option list, a value domain, or a number that is not finite). + * + * A stored computed field (an `expression` on a field that is not a + * `formula`) that reads another row one hop is stored from what it read at its + * own write, so what it reads counts as read too: one by one each row stores a + * value over the recompute of the rows before it. + * + * Then the set is closed over what the fields read are computed from: a + * formula or stored computed field a rule reads reads what its expression + * reads, and a summary over a summary that a rule reads makes the summary it + * aggregates read too, so the chain recomputes row by row up to the rule. + * + * ⛔ A `parent.` predicate that reads a field which is not a summary (the + * showcase invoice line's `parent.status == 'paid'`) names that field and no + * other, so it does not turn the deferral off. Hooks and flow steps are not + * here: the engine cannot know what they read, and they read the pre-batch + * value inside one batch, on create and update alike. + */ + +import { analyzeRelationshipTraversals } from '@objectstack/formula'; +import { referenceTargetOf } from '@objectstack/spec/data'; +import { collectPredicateRelationships } from './validation/rule-validator.js'; +import { resolveMasterDetailRelation } from './master-detail.js'; + +/** The CEL scope root a master-detail header is bound under (`rule-validator.ts`). */ +const PARENT_ROOT = 'parent'; + +/** The field-level predicates that may read `parent` (#4889, #4977). */ +const PARENT_PREDICATE_SLOTS = ['requiredWhen', 'readonlyWhen'] as const; + +/** + * The declared bounds a write judges on the summary's stored value + * (`validateRecord`'s `min_value` / `max_value` / `min_length` / `max_length` + * / `max_precision` and `required` checks, and a field-level unique index). + * `pattern` / `regex` are read by no check today: an over-read, which costs + * only statements. A declared index with `unique` is read beside this list. + */ +const SUMMARY_BOUND_KEYS = ['min', 'max', 'minLength', 'maxLength', 'pattern', 'regex', 'precision', 'unique', 'required'] as const; + +/** The fields an object-level declared index with `unique` names (`'global'`, `'organization'`, or a stored bare `true`). */ +function uniquelyIndexed(indexes: unknown): Set { + const out = new Set(); + if (!Array.isArray(indexes)) return out; + for (const index of indexes) { + if (!index || typeof index !== 'object') continue; + const { unique, fields } = index as { unique?: unknown; fields?: unknown }; + if (unique === undefined || unique === null || unique === false || !Array.isArray(fields)) continue; + for (const field of fields) if (typeof field === 'string') out.add(field); + } + return out; +} + +/** The CEL roots a rule reads its own row under: the row, and the row before the write. */ +const OWN_ROW_ROOTS = ['record', 'previous'] as const; + +/** Every field `source` reads on `root`, as a value or through it. Empty when it does not parse. */ +function fieldsReadOn(source: string, root: string): string[] { + const analysis = analyzeRelationshipTraversals(source, root); + return analysis ? [...analysis.bareFields, ...analysis.traversals.keys()] : []; +} + +/** + * (iii) The fields of its own row a validation rule reads: its CEL condition + * (`script`, `cross_field`, a `conditional`'s `when`, at every depth) on + * `record` or `previous`, and the field a `state_machine` / `format` / + * `json_schema` rule names. + */ +function ownFieldsReadByRule(rule: unknown, out: Set, depth = 0): void { + if (!rule || typeof rule !== 'object' || depth > 8) return; + const r = rule as { type?: unknown; condition?: unknown; when?: unknown; then?: unknown; otherwise?: unknown; field?: unknown }; + for (const slot of [r.condition, r.when]) { + const source = celSource(slot); + if (!source) continue; + for (const root of OWN_ROW_ROOTS) for (const field of fieldsReadOn(source, root)) out.add(field); + } + if (typeof r.field === 'string' && r.field) out.add(r.field); + if (r.type === 'conditional') { + ownFieldsReadByRule(r.then, out, depth + 1); + ownFieldsReadByRule(r.otherwise, out, depth + 1); + } +} + +/** The CEL source of an authored predicate slot, or `undefined` when it is not CEL. */ +function celSource(slot: unknown): string | undefined { + if (typeof slot === 'string') return slot || undefined; + if (!slot || typeof slot !== 'object') return undefined; + const { dialect, source } = slot as { dialect?: unknown; source?: unknown }; + if (dialect !== undefined && dialect !== 'cel') return undefined; + return typeof source === 'string' && source ? source : undefined; +} + +/** The key {@link summaryFieldsReadByRules} answers in: `.`. */ +export function ruleReadKey(object: string, field: string): string { + return `${object}.${field}`; +} + +/** An object definition as this module reads it. */ +type ObjectDef = { name?: unknown; fields?: Record | null | undefined>; validations?: unknown[]; indexes?: unknown } | null | undefined; + +/** The parts of a roll-up descriptor the chain closure reads. */ +export interface ChainLink { + parentObject: string; + summaryField: string; + childObject: string; + sourceField?: string; + filter?: Record; +} + +/** + * The `.` keys a CEL source reads, evaluated against a row of + * `object`: its own fields on `record` (as a value or as the reference a hop + * goes through), and one hop through a reference to the target's field. + */ +function keysReadFrom(source: string, object: string, fields: NonNullable['fields']>, out: Set): void { + const analysis = analyzeRelationshipTraversals(source, 'record'); + if (!analysis) return; + for (const field of analysis.bareFields) out.add(ruleReadKey(object, field)); + for (const [reference, related] of analysis.traversals) { + out.add(ruleReadKey(object, reference)); + const target = referenceTargetOf(fields[reference] as never); + if (!target) continue; + for (const field of related) out.add(ruleReadKey(target, field)); + } +} + +/** + * Every `.` a rule of `objects` reads, closed over what those + * fields are computed from. Direct reads: on another row through a reference, + * one hop (class i), on the master-detail header by a field-level predicate + * (class ii), or on its own row (class iii). Then, to a fixed point: + * + * - a computed field read (a `formula`, or a stored field with an + * `expression`) makes what its expression reads read too, on its own row and + * one hop through a reference: a rule reading `record.project.remaining`, + * where `remaining` is `record.budget - record.spent_total`, reads the + * summary `spent_total`; + * - a summary read that aggregates a field of its child rows (`sourceField`, + * from `links`) makes that field read; a filtered one makes every summary of + * its child object read (the filter may name any of them). So a rule on the + * top of a chain of summaries keeps every link under it recomputing row by + * row, as one by one, where the rule judges each step. + * + * A field that is not a summary may be in the set; the caller asks only about + * summary fields. + */ +export function summaryFieldsReadByRules(objects: Iterable, links: Iterable = []): Set { + const out = new Set(); + /** `.` → the CEL source a computed field is computed from. */ + const computed = new Map['fields']> }>(); + for (const candidate of objects) { + const schema = candidate as ObjectDef; + const fields = schema?.fields; + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) continue; + const name = typeof schema?.name === 'string' && schema.name ? schema.name : undefined; + if (name) { + for (const [field, def] of Object.entries(fields)) { + const source = def && typeof def === 'object' ? celSource(def.expression) : undefined; + if (source) computed.set(ruleReadKey(name, field), { source, object: name, fields }); + } + } + // (iii) A rule reading its own row: validation rules, then field-level predicates. + const own = new Set(); + if (Array.isArray(schema?.validations)) for (const rule of schema.validations) ownFieldsReadByRule(rule, own); + for (const def of Object.values(fields)) { + if (!def || typeof def !== 'object') continue; + for (const slot of PARENT_PREDICATE_SLOTS) { + const source = celSource(def[slot]); + if (!source) continue; + for (const root of OWN_ROW_ROOTS) for (const field of fieldsReadOn(source, root)) own.add(field); + } + } + // (iii) What the recompute's own write judges without a rule. It stores + // the summary and every stored computed field (an `expression` on a field + // that is not a `formula`), computed onto its payload, and judges each + // against its declaration (`validateRecord`, a unique index), so one by + // one every intermediate value is judged. The summary counts when it + // declares a bound or a unique index names it; a stored computed field + // counts always, since its type alone can refuse a value (an option, a + // value domain, a number that is not finite). The closure below adds + // what a stored computed field reads. + const indexed = uniquelyIndexed(schema?.indexes); + for (const [field, def] of Object.entries(fields)) { + if (!def || typeof def !== 'object') continue; + if (def.type === 'summary') { + if (indexed.has(field) || SUMMARY_BOUND_KEYS.some((key) => def[key] !== undefined && def[key] !== null && def[key] !== false)) own.add(field); + } else if (def.type !== 'formula' && celSource(def.expression) !== undefined) { + own.add(field); + } + } + if (name) for (const field of own) out.add(ruleReadKey(name, field)); + // A stored computed field reading another row one hop (`record.inv.line_total`) + // stores what it read at its own write: one by one each row reads the + // recompute of the rows before it, so what it reads counts as read. + if (name) { + for (const def of Object.values(fields)) { + if (!def || typeof def !== 'object' || def.type === 'formula') continue; + const source = celSource(def.expression); + if (!source) continue; + const analysis = analyzeRelationshipTraversals(source, 'record'); + for (const [reference, related] of analysis?.traversals ?? []) { + const target = referenceTargetOf(fields[reference] as never); + if (target) for (const field of related) out.add(ruleReadKey(target, field)); + } + } + } + // (i) A validation rule reading through a reference, one hop. + for (const [reference, related] of collectPredicateRelationships(schema as never)) { + const target = referenceTargetOf(fields[reference] as never); + if (!target) continue; + for (const field of related) out.add(ruleReadKey(target, field)); + } + // (ii) A field-level predicate reading the master-detail header. + let master: string | null | undefined; + for (const def of Object.values(fields)) { + if (!def || typeof def !== 'object') continue; + for (const slot of PARENT_PREDICATE_SLOTS) { + const source = celSource(def[slot]); + if (!source) continue; + const read = fieldsReadOn(source, PARENT_ROOT); + if (read.length === 0) continue; + // No single master-detail relation: `parent` is unbound and the + // predicate faults where it is judged; it reads no header field. + if (master === undefined) master = resolveMasterDetailRelation(schema as never)?.master ?? null; + if (!master) continue; + for (const field of read) out.add(ruleReadKey(master, field)); + } + } + } + // The closure: computed fields, then summary chains, to a fixed point. + const chain = [...links]; + let grew = true; + while (grew) { + grew = false; + const add = new Set(); + for (const key of out) { + const formula = computed.get(key); + if (formula) keysReadFrom(formula.source, formula.object, formula.fields, add); + } + for (const link of chain) { + if (!out.has(ruleReadKey(link.parentObject, link.summaryField))) continue; + if (link.sourceField) add.add(ruleReadKey(link.childObject, link.sourceField)); + if (link.filter && Object.keys(link.filter).length > 0) { + for (const other of chain) if (other.parentObject === link.childObject) add.add(ruleReadKey(other.parentObject, other.summaryField)); + } + } + for (const key of add) if (!out.has(key)) { out.add(key); grew = true; } + } + return out; +} diff --git a/packages/qa/dogfood/package.json b/packages/qa/dogfood/package.json index 9a4a747aeea..47a771ed07e 100644 --- a/packages/qa/dogfood/package.json +++ b/packages/qa/dogfood/package.json @@ -50,6 +50,7 @@ "@objectstack/driver-sql": "workspace:*", "@objectstack/driver-sqlite-wasm": "workspace:*", "@objectstack/driver-turso": "workspace:*", + "@objectstack/metadata-protocol": "workspace:*", "@objectstack/setup": "workspace:*", "@objectstack/trigger-api": "workspace:*", "@types/node": "^26.6.5", diff --git a/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts index d05475bb863..399b34526e4 100644 --- a/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts +++ b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts @@ -29,6 +29,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import { ObjectQL, aggregateSummaryValue } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; +import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol'; import { installDefaultOrganization } from './default-organization.testkit.js'; const PG_URL = process.env.OS_TEST_POSTGRES_URL; @@ -104,7 +105,195 @@ const KIND_OBJECTS = [ }, ]; -const OBJECTS = [...rollupPair(0), ...rollupPair(1), ...rollupPair(2), ...KIND_OBJECTS]; +/** + * [#33795, ruling 6928862195 B] A supplier whose contacts' rules read its + * roll-ups, one child object per summary function so each rule moves alone: + * "at most one primary contact" over a filtered `count`, and a bound on a + * contact's score against the supplier's current `avg`, `min` and `max`. + */ +const RULE_SUPPLIER = 'r33795_rsup'; +const RULE_CHILDREN = { + count: { object: 'r33795_rsup_primary', summary: 'primary_count', op: { function: 'count', filter: { is_primary: true } } }, + avg: { object: 'r33795_rsup_avg', summary: 'score_avg', op: { function: 'avg', field: 'score' } }, + min: { object: 'r33795_rsup_min', summary: 'score_min', op: { function: 'min', field: 'score' } }, + max: { object: 'r33795_rsup_max', summary: 'score_max', op: { function: 'max', field: 'score' } }, +} as const; +const RULE_TEXT = { + count: 'A supplier has at most one primary contact.', + avg: 'A score may not exceed the supplier average by more than 2.', + min: 'A score may not fall more than 1 below the supplier minimum.', + max: 'A score may not rise more than 1 above the supplier maximum.', +} as const; +const RULE_CONDITION = { + count: 'record.is_primary == true && record.supplier.primary_count > 0', + avg: 'record.supplier.score_avg != null && record.score > record.supplier.score_avg + 2.0', + min: 'record.supplier.score_min != null && record.score < record.supplier.score_min - 1.0', + max: 'record.supplier.score_max != null && record.score > record.supplier.score_max + 1.0', +} as const; +const RULE_OBJECTS = [ + { + name: RULE_SUPPLIER, + label: 'Rule supplier', + fields: { + name: { type: 'text', label: 'Name' }, + ...Object.fromEntries(Object.values(RULE_CHILDREN).map(({ object, summary, op }) => [ + summary, { type: 'summary', label: summary, summaryOperations: { object, ...op } }, + ])), + }, + }, + ...(Object.keys(RULE_CHILDREN) as Array).map((fn) => ({ + name: RULE_CHILDREN[fn].object, + label: `Rule contact (${fn})`, + fields: { + name: { type: 'text', label: 'Name' }, + supplier: { type: 'lookup', label: 'Supplier', reference: RULE_SUPPLIER }, + is_primary: { type: 'boolean', label: 'Primary' }, + score: { type: 'number', label: 'Score' }, + }, + validations: [{ name: `rule_${fn}`, type: 'script', severity: 'error', message: RULE_TEXT[fn], condition: RULE_CONDITION[fn] }], + })), +]; + +/** + * [#33795, ruling 6928862195 B, class iii] An invoice whose OWN rule caps its + * own roll-up: at most two lines. The recompute's write is an update of the + * invoice, judged by that rule, so one by one it judges every intermediate + * count. + */ +const CAP_TEXT = 'An invoice holds at most two lines.'; +/** + * The capped invoice and its lines. `rule` caps the count with a validation + * rule; `computed` caps a stored computed field over it (`room = 2 - + * line_count`, recomputed on the recompute's own write) with a rule; `bound` + * declares `min: 0` on that field and has no rule at all; `option` declares + * nothing: a stored select computed from the count names a value its option + * list lacks past the cap, which the write refuses as it would any value. + */ +function capObjects(parent: string, line: string, mode: 'rule' | 'computed' | 'bound' | 'option') { + const viaComputed = mode === 'computed' || mode === 'bound'; + return [ + { + name: parent, + label: `Capped invoice (${mode})`, + fields: { + name: { type: 'text', label: 'Name' }, + line_count: { type: 'summary', label: 'Lines', summaryOperations: { object: line, function: 'count' } }, + ...(viaComputed ? { room: { type: 'number', label: 'Room', expression: '2 - record.line_count', ...(mode === 'bound' ? { min: 0 } : {}) } } : {}), + ...(mode === 'option' ? { + fill: { + type: 'select', label: 'Fill', + options: [{ label: 'Open', value: 'open' }, { label: 'Full', value: 'full' }], + expression: "record.line_count == null || record.line_count < 2 ? 'open' : (record.line_count == 2 ? 'full' : 'over')", + }, + } : {}), + }, + validations: mode === 'bound' || mode === 'option' ? [] : [{ + name: 'cap_lines', type: 'script', severity: 'error', message: CAP_TEXT, + condition: viaComputed ? 'record.room != null && record.room < 0' : 'record.line_count != null && record.line_count > 2', + }], + }, + { + name: line, + label: `Capped invoice line (${mode})`, + fields: { + name: { type: 'text', label: 'Name' }, + invoice: { type: 'lookup', label: 'Invoice', reference: parent }, + }, + }, + ]; +} +const CAP = { parent: 'r33795_cap', line: 'r33795_cap_line' }; +const CCAP = { parent: 'r33795_ccap', line: 'r33795_ccap_line' }; +const BCAP = { parent: 'r33795_bcap', line: 'r33795_bcap_line' }; +const OCAP = { parent: 'r33795_ocap', line: 'r33795_ocap_line' }; + +/** + * [#33795] A stored computed field of the CHILD that reads the parent's + * summary one hop: `rank = owner.flagged_count`, stored at the line's own + * write. One by one the second line stores the first line's recompute. + */ +const SEEN = 'r33795_seen'; +const SEEN_LINE = 'r33795_seen_line'; +const SEEN_OBJECTS = [ + { + name: SEEN, + label: 'Ranked owner', + fields: { + name: { type: 'text', label: 'Name' }, + flagged_count: { type: 'summary', label: 'Flagged', summaryOperations: { object: SEEN_LINE, function: 'count', filter: { flag: true } } }, + }, + }, + { + name: SEEN_LINE, + label: 'Ranked line', + fields: { + name: { type: 'text', label: 'Name' }, + owner: { type: 'lookup', label: 'Owner', reference: SEEN }, + flag: { type: 'boolean', label: 'Flag' }, + rank: { type: 'number', label: 'Rank', expression: 'record.owner.flagged_count' }, + }, + }, +]; + +/** + * [#33795, ruling 6928862195 B, through a computed field] (i) a contact's rule + * reads the supplier's formula `slots = 1 - primary_count` one hop (the hop's + * read computes formulas); (ii) a line's `readonlyWhen` reads the header's + * stored computed field `room = 1 - flagged_count` on `parent` (the header is + * read as stored). Neither rule names the summary. + */ +const FSUP = 'r33795_fsup'; +const FSUP_CONTACT = 'r33795_fsup_contact'; +const FSUP_TEXT = 'No primary slot is left on this supplier.'; +const FHDR = 'r33795_fhdr'; +const FHDR_LINE = 'r33795_fhdr_line'; +const FORMULA_OBJECTS = [ + { + name: FSUP, + label: 'Formula supplier', + fields: { + name: { type: 'text', label: 'Name' }, + primary_count: { type: 'summary', label: 'Primaries', summaryOperations: { object: FSUP_CONTACT, function: 'count', filter: { is_primary: true } } }, + slots: { type: 'formula', label: 'Slots', returnType: 'number', expression: '1 - record.primary_count' }, + }, + }, + { + name: FSUP_CONTACT, + label: 'Formula supplier contact', + fields: { + name: { type: 'text', label: 'Name' }, + supplier: { type: 'lookup', label: 'Supplier', reference: FSUP }, + is_primary: { type: 'boolean', label: 'Primary' }, + }, + validations: [{ name: 'slots_left', type: 'script', severity: 'error', message: FSUP_TEXT, condition: 'record.is_primary == true && record.supplier.slots != null && record.supplier.slots < 1' }], + }, + { + name: FHDR, + label: 'Formula header', + fields: { + name: { type: 'text', label: 'Name' }, + flagged_count: { type: 'summary', label: 'Flagged', summaryOperations: { object: FHDR_LINE, function: 'count', filter: { flag: true } } }, + room: { type: 'number', label: 'Room', expression: '1 - record.flagged_count' }, + }, + }, + { + name: FHDR_LINE, + label: 'Formula header line', + fields: { + name: { type: 'text', label: 'Name' }, + header: { type: 'master_detail', label: 'Header', reference: FHDR, deleteBehavior: 'cascade' }, + flag: { type: 'boolean', label: 'Flag' }, + note: { type: 'text', label: 'Note', readonlyWhen: 'parent.room != null && parent.room < 1' }, + }, + }, +]; + +const OBJECTS = [ + ...rollupPair(0), ...rollupPair(1), ...rollupPair(2), ...KIND_OBJECTS, ...RULE_OBJECTS, + ...capObjects(CAP.parent, CAP.line, 'rule'), ...capObjects(CCAP.parent, CCAP.line, 'computed'), ...capObjects(BCAP.parent, BCAP.line, 'bound'), + ...capObjects(OCAP.parent, OCAP.line, 'option'), + ...FORMULA_OBJECTS, ...SEEN_OBJECTS, +]; const engines: ObjectQL[] = []; afterEach(async () => { @@ -227,6 +416,324 @@ describe.each(CELLS)('roll-up grouped recompute (#33795): $name', ({ url, make } }); }); +/** + * [#33795] The second half: a bulk update through the data door + * (`updateManyData`, and the update arm of `batchData`) runs its per-row loop + * inside the engine's roll-up batch scope (`deferSummaryRecompute`, ruling + * 6922040858), so the parents recompute once, when the loop has settled. + * + * Pins, per cell: the statement counts of a 50-row `updateManyData` over 10 + * parents with 0, 1 and 2 summary fields, with the member and on the same + * engine with the member hidden (the per-row recompute a door degrades to); + * and value parity for every summary kind through the door — non-atomic, + * atomic, the generic batch door, a batch stopped by a failed row, and an + * engine without the member. + */ +/** The engine with `deferSummaryRecompute` hidden for `fn`: what a door sees on an engine that lacks the member. */ +async function withoutBatchScope(engine: ObjectQL, fn: () => Promise): Promise { + (engine as unknown as Record).deferSummaryRecompute = undefined; + try { return await fn(); } finally { delete (engine as unknown as Record).deferSummaryRecompute; } +} + +describe.each(CELLS)('roll-up batch deferral through the bulk update door (#33795): $name', ({ url, make }) => { + const skip = !url; + + it.skipIf(skip)('a bulk update costs one aggregate per summary field and one write per parent', async () => { + const { engine, driver } = await boot(make); + const protocol = new ObjectStackProtocolImplementation(engine as never); + const measured: Record> = { updateMany: {}, updateManyNoScope: {}, updateManyAtomic: {} }; + for (const n of [0, 1, 2] as const) { + const parent = `r33795_roll${n}`; + const child = `${parent}_item`; + const parents = await seedParents(engine, parent, PARENTS); + const created = await engine.insert(child, Array.from({ length: BATCH }, (_, k) => ({ + name: `c${k}`, parent: parents[k % PARENTS], quantity: 1 + (k % 5), + })), SYSTEM) as Array<{ id: string }>; + const records = (q: number) => created.map((row, k) => ({ id: row.id, data: { quantity: q + (k % 7) } })); + for (const [key, run] of [ + ['updateMany', () => protocol.updateManyData({ object: child, records: records(2), context: SYSTEM.context } as never)], + ['updateManyNoScope', () => withoutBatchScope(engine, () => protocol.updateManyData({ object: child, records: records(3), context: SYSTEM.context } as never))], + ['updateManyAtomic', () => protocol.updateManyData({ object: child, records: records(4), options: { atomic: true }, context: SYSTEM.context } as never)], + ] as const) { + let answer: any; + measured[key][n] = await statementsOf(driver, async () => { answer = await run(); }); + expect(answer, `${key} ${n}`).toMatchObject({ success: true, succeeded: BATCH }); + } + } + const delta = (key: string, n: number) => measured[key][n] - measured[key][0]; + // In the scope: one aggregate per field, then one write per parent + // (3 statements: the update and its two reads of the parent row) — what + // a createMany pays. + for (const key of ['updateMany', 'updateManyAtomic']) { + expect(delta(key, 1), `${key} ${JSON.stringify(measured)}`).toBe(1 + PARENTS * 3); + expect(delta(key, 2), `${key} ${JSON.stringify(measured)}`).toBe(2 + PARENTS * 3); + } + // Without the member: today's per-row recompute, one per row. + expect(delta('updateManyNoScope', 1), JSON.stringify(measured)).toBe(BATCH * (1 + 3)); + expect(delta('updateManyNoScope', 2), JSON.stringify(measured)).toBe(BATCH * (2 + 3)); + // The no-summary control costs the same either way. + expect(measured.updateManyNoScope[0], JSON.stringify(measured)).toBe(measured.updateMany[0]); + console.log(`[#33795] door statements ${url === 'sqlite' ? 'sqlite' : 'postgresql'}: ${JSON.stringify(measured)}`); + }); + + it.skipIf(skip)('every summary kind lands the one-parent aggregate through every bulk update door', async () => { + const { engine } = await boot(make); + const protocol = new ObjectStackProtocolImplementation(engine as never); + const parents = await seedParents(engine, KIND_PARENT, 6); + const rows = await engine.insert(KIND_CHILD, Array.from({ length: 40 }, (_, k) => ({ + name: `k${k}`, parent: parents[k % 5], quantity: k % 4 === 0 ? null : (k * 7) % 11 - 3, status: k % 3 === 0 ? 'open' : 'closed', + })), SYSTEM) as Array<{ id: string }>; + + const check = async (stage: string) => { + const children = await engine.find(KIND_CHILD, { where: {}, limit: 1000 }, SYSTEM) as Array>; + for (const id of parents) { + const stored = await engine.findOne(KIND_PARENT, { where: { id } }, SYSTEM) as Record; + for (const [field, op] of Object.entries(KIND_FIELDS)) { + const desc = { + parentObject: KIND_PARENT, summaryField: field, childObject: KIND_CHILD, fkField: 'parent', + fn: op.function, sourceField: 'field' in op ? op.field : undefined, filter: 'filter' in op ? op.filter : undefined, + } as const; + const oneParent = await aggregateSummaryValue(engine as never, desc as never, id, SYSTEM.context); + const at = `${stage}: ${field} of parent ${parents.indexOf(id)}`; + expect(num(stored[field]), at).toEqual(num(oneParent)); + expect(num(stored[field]), `${at} (hand count)`).toEqual(handValue(children, id, op)); + } + } + }; + // Each batch moves values, moves rows between parents (parent 5 gains + // its first children) and in and out of the filters. + const batch = (salt: number, slice: [number, number]) => rows.slice(...slice).map((row, k) => ({ + id: row.id, + data: { quantity: (k * salt) % 9 - 2, status: (k + salt) % 2 ? 'open' : 'closed', ...(k % 4 === salt % 4 ? { parent: parents[(k + salt) % 6] } : {}) }, + })); + + let answer: any = await protocol.updateManyData({ object: KIND_CHILD, records: batch(1, [0, 20]), context: SYSTEM.context } as never); + expect(answer).toMatchObject({ success: true, succeeded: 20 }); + await check('after updateManyData'); + + answer = await protocol.updateManyData({ object: KIND_CHILD, records: batch(2, [10, 30]), options: { atomic: true }, context: SYSTEM.context } as never); + expect(answer).toMatchObject({ success: true, succeeded: 20 }); + await check('after an atomic updateManyData'); + + answer = await protocol.batchData({ object: KIND_CHILD, request: { operation: 'update', records: batch(3, [20, 40]) }, context: SYSTEM.context } as never); + expect(answer).toMatchObject({ success: true, succeeded: 20 }); + await check('after batchData update'); + + // Stopped by a failed row (an id naming no record, no continueOnError): + // the rows before it landed, and their parents are recomputed. + const stopped = batch(5, [0, 12]); + stopped.splice(6, 0, { id: 'no_such_row_33795', data: { quantity: 1, status: 'open' } }); + answer = await protocol.updateManyData({ object: KIND_CHILD, records: stopped, context: SYSTEM.context } as never); + expect(answer).toMatchObject({ success: false, succeeded: 6 }); + await check('after a bulk update stopped by a failed row'); + + // An engine without the member: the per-row recompute, the same values. + answer = await withoutBatchScope(engine, () => protocol.updateManyData({ object: KIND_CHILD, records: batch(7, [5, 35]), context: SYSTEM.context } as never)); + expect(answer).toMatchObject({ success: true, succeeded: 30 }); + await check('after updateManyData on an engine without the member'); + }); +}); + +/** + * [#33795, ruling 6928862195 B] A roll-up a rule reads is not deferred: a + * bulk update through the real door answers what single updates answer, row + * for row, for a filtered `count` and for `avg`, `min` and `max`; atomic and + * `continueOnError`. Each case runs twice on twin data — once as one batch, + * once as one-record calls of the same door — and the answers, the stored + * rows and the supplier's roll-ups must match. A roll-up no rule reads (the + * describe above) keeps its deferred statement counts. + */ +const RULE_CASES: Record>; batch: Array> }> = { + // Two contacts set primary in one edit: one-by-one refuses the second; + // against the pre-batch count (0) both would pass. + count: { seed: [{ is_primary: false }, { is_primary: false }], batch: [{ is_primary: true }, { is_primary: true }] }, + // Scores 3, 3, 3 (avg 3): 0 is admitted and moves the avg to 2, so 4.5 is + // refused (4.5 > 4); against the pre-batch avg it would pass (4.5 > 5 is false). + avg: { seed: [{ score: 3 }, { score: 3 }, { score: 3 }], batch: [{ score: 0 }, { score: 4.5 }] }, + // Scores 1, 5, 5 (min 1): the 1 becomes 5, so the min is 5 and 3 is refused + // (3 < 4); against the pre-batch min it would pass (3 < 0 is false). + min: { seed: [{ score: 1 }, { score: 5 }, { score: 5 }], batch: [{ score: 5 }, { score: 3 }] }, + // Scores 9, 5, 5 (max 9): the 9 becomes 5, so the max is 5 and 7 is refused + // (7 > 6); against the pre-batch max it would pass (7 > 10 is false). + max: { seed: [{ score: 9 }, { score: 5 }, { score: 5 }], batch: [{ score: 5 }, { score: 7 }] }, +}; + +describe.each(CELLS)('a roll-up a rule reads is not deferred (#33795 B): $name', ({ url, make }) => { + const skip = !url; + + async function twin(engine: ObjectQL, fn: keyof typeof RULE_CHILDREN, tag: string) { + const [supplier] = await engine.insert(RULE_SUPPLIER, [{ name: `${fn}-${tag}` }], SYSTEM) as Array<{ id: string }>; + const contacts = await engine.insert(RULE_CHILDREN[fn].object, RULE_CASES[fn].seed.map((row, k) => ({ + name: `${tag}${k}`, supplier: supplier.id, ...row, + })), SYSTEM) as Array<{ id: string }>; + const records = RULE_CASES[fn].batch.map((data, k) => ({ id: contacts[k].id, data })); + const state = async () => ({ + summary: num((await engine.findOne(RULE_SUPPLIER, { where: { id: supplier.id } }, SYSTEM) as any)[RULE_CHILDREN[fn].summary]), + contacts: (await engine.find(RULE_CHILDREN[fn].object, { where: { supplier: supplier.id }, orderBy: [{ field: 'name', order: 'asc' }] }, SYSTEM) as any[]) + .map((c) => ({ is_primary: !!c.is_primary, score: num(c.score) })), + }); + return { records, state }; + } + + /** The per-row answers a caller reads: success and the first error's code and text. */ + const rows = (answer: any) => (answer.results as any[]).map((r) => ({ success: r.success, code: r.errors?.[0]?.code, message: r.errors?.[0]?.message })); + + for (const fn of Object.keys(RULE_CHILDREN) as Array) { + it.skipIf(skip)(`${fn}: continueOnError answers what single updates answer`, async () => { + const { engine } = await boot(make); + const protocol = new ObjectStackProtocolImplementation(engine as never); + const object = RULE_CHILDREN[fn].object; + const one = await twin(engine, fn, 'single'); + const singles: any[] = []; + for (const record of one.records) { + singles.push(...rows(await protocol.updateManyData({ object, records: [record], options: { continueOnError: true }, context: SYSTEM.context } as never))); + } + const batch = await twin(engine, fn, 'batch'); + const answer = await protocol.updateManyData({ object, records: batch.records, options: { continueOnError: true }, context: SYSTEM.context } as never); + // One by one, the first row is admitted and the second refused with the rule's own text. + expect(singles[0]).toMatchObject({ success: true }); + expect(singles[1]).toMatchObject({ success: false, message: expect.stringContaining(RULE_TEXT[fn]) }); + expect(rows(answer)).toEqual(singles); + expect(await batch.state()).toEqual(await one.state()); + }); + + it.skipIf(skip)(`${fn}: an atomic batch refuses the second row with the single update's answer and writes nothing`, async () => { + const { engine } = await boot(make); + const protocol = new ObjectStackProtocolImplementation(engine as never); + const object = RULE_CHILDREN[fn].object; + const one = await twin(engine, fn, 'single'); + const before = await one.state(); + const second = rows(await protocol.updateManyData({ object, records: [one.records[0]], context: SYSTEM.context } as never)).concat( + rows(await protocol.updateManyData({ object, records: [one.records[1]], context: SYSTEM.context } as never)), + )[1]; + expect(second).toMatchObject({ success: false, message: expect.stringContaining(RULE_TEXT[fn]) }); + const batch = await twin(engine, fn, 'batch'); + const answer = await protocol.updateManyData({ object, records: batch.records, options: { atomic: true }, context: SYSTEM.context } as never); + expect(answer).toMatchObject({ success: false }); + const got = rows(answer); + expect(got[0]).toMatchObject({ success: false, code: 'ROLLED_BACK' }); + expect(got[1]).toEqual(second); + expect(await batch.state()).toEqual(before); + }); + } +}); + +/** One bulk update a rule judges, set up on twin data: the door's object, its records, and the state to compare. */ +type ParityCase = (engine: ObjectQL, tag: string) => Promise<{ object: string; records: Array<{ id: string; data: Record }>; state: () => Promise }>; + +/** The capped invoice: A holds one line, B two; the batch moves A's line onto B and one of B's onto A. */ +const capCase = ({ parent, line }: { parent: string; line: string }): ParityCase => async (engine, tag) => { + const [a, b] = await engine.insert(parent, [{ name: `${tag}A` }, { name: `${tag}B` }], SYSTEM) as Array<{ id: string }>; + const [a1, b1] = await engine.insert(line, [ + { name: `${tag}a1`, invoice: a.id }, { name: `${tag}b1`, invoice: b.id }, { name: `${tag}b2`, invoice: b.id }, + ], SYSTEM) as Array<{ id: string }>; + return { + object: line, + records: [{ id: a1.id, data: { invoice: b.id } }, { id: b1.id, data: { invoice: a.id } }], + state: async () => ({ + counts: await Promise.all([a, b].map(async (p) => num((await engine.findOne(parent, { where: { id: p.id } }, SYSTEM) as any).line_count))), + lines: (await engine.find(line, { where: { invoice: { $in: [a.id, b.id] } }, orderBy: [{ field: 'name', order: 'asc' }] }, SYSTEM) as any[]) + .map((l) => ({ name: String(l.name).slice(tag.length), on: l.invoice === a.id ? 'A' : 'B' })), + }), + }; +}; + +/** Two contacts of one supplier set primary: the formula `slots` is 1 before the batch, 0 after the first. */ +const slotsCase: ParityCase = async (engine, tag) => { + const [supplier] = await engine.insert(FSUP, [{ name: `${tag}S` }], SYSTEM) as Array<{ id: string }>; + const contacts = await engine.insert(FSUP_CONTACT, [0, 1].map((k) => ({ name: `${tag}${k}`, supplier: supplier.id, is_primary: false })), SYSTEM) as Array<{ id: string }>; + return { + object: FSUP_CONTACT, + records: contacts.map((c) => ({ id: c.id, data: { is_primary: true } })), + state: async () => ({ + primaries: num((await engine.findOne(FSUP, { where: { id: supplier.id } }, SYSTEM) as any).primary_count), + contacts: (await engine.find(FSUP_CONTACT, { where: { supplier: supplier.id }, orderBy: [{ field: 'name', order: 'asc' }] }, SYSTEM) as any[]).map((c) => !!c.is_primary), + }), + }; +}; + +/** Two lines of one header flagged, each with a note: the header's computed `room` is 1 before the batch and 0 after the first, so one by one the second note is locked and dropped. */ +const roomCase: ParityCase = async (engine, tag) => { + const [header] = await engine.insert(FHDR, [{ name: `${tag}H` }], SYSTEM) as Array<{ id: string }>; + const lines = await engine.insert(FHDR_LINE, [0, 1].map((k) => ({ name: `${tag}${k}`, header: header.id, flag: false })), SYSTEM) as Array<{ id: string }>; + return { + object: FHDR_LINE, + records: lines.map((l) => ({ id: l.id, data: { flag: true, note: 'set' } })), + state: async () => ({ + flagged: num((await engine.findOne(FHDR, { where: { id: header.id } }, SYSTEM) as any).flagged_count), + lines: (await engine.find(FHDR_LINE, { where: { header: header.id }, orderBy: [{ field: 'name', order: 'asc' }] }, SYSTEM) as any[]).map((l) => ({ flag: !!l.flag, note: l.note ?? null })), + }), + }; +}; + +/** Two lines of one owner flagged: each stores `rank` from the owner's count at its own write. */ +const rankCase: ParityCase = async (engine, tag) => { + const [owner] = await engine.insert(SEEN, [{ name: `${tag}O` }], SYSTEM) as Array<{ id: string }>; + const lines = await engine.insert(SEEN_LINE, [0, 1].map((k) => ({ name: `${tag}${k}`, owner: owner.id, flag: false })), SYSTEM) as Array<{ id: string }>; + return { + object: SEEN_LINE, + records: lines.map((l) => ({ id: l.id, data: { flag: true } })), + state: async () => ({ + flagged: num((await engine.findOne(SEEN, { where: { id: owner.id } }, SYSTEM) as any).flagged_count), + ranks: (await engine.find(SEEN_LINE, { where: { owner: owner.id }, orderBy: [{ field: 'name', order: 'asc' }] }, SYSTEM) as any[]).map((l) => num(l.rank)), + }), + }; +}; + +/** + * [#33795, ruling 6928862195 B] The classes a rule reads a roll-up through that + * the supplier describe above does not cover: (iii) a rule of the parent on its + * own roll-up, and a rule reading the roll-up through a computed field: a + * formula one hop (i), a stored computed field on `parent` (ii) and on its own + * row (iii). Each case's pre-batch value admits + * the whole batch where one-by-one refuses a step. The oracle is the same door + * on the same engine with the member hidden: today's per-row recompute, so + * "rules do not change against today" is pinned as stated, the answer and the + * stored rows alike, atomic and `continueOnError`. + */ +const refused = (answer: any): boolean => answer.success === false; +/** `live` says the per-row path shows what a deferral would change; `coeLive` says it also does so under `continueOnError` (else that run is a parity pin only). */ +const PARITY_CASES: Array<{ name: string; make: ParityCase; live: (answer: any, state: any) => boolean; coeLive?: boolean }> = [ + // Invoice A holds one line, B two (the cap). Moving A's line onto B makes + // B hold 3, and B's own rule refuses that recompute; moving one of B's + // lines back leaves B at 2, so deferred the rule would see only B = 2. + { name: '(iii) the parent caps its own count', make: capCase(CAP), live: refused }, + { name: '(iii) the parent caps a stored computed field over its own count', make: capCase(CCAP), live: refused }, + { name: '(i) a contact rule reads the supplier formula over its count, one hop', make: slotsCase, live: refused, coeLive: true }, + { name: '(ii) a line readonlyWhen reads the header computed field over its count on parent', make: roomCase, live: (_answer, state) => state.lines[1].note === null, coeLive: true }, + // The same cap spelled as a declared bound (`min: 0` on the stored `room`), no rule. + { name: '(iii) a declared bound on the parent stored computed field over its count', make: capCase(BCAP), live: refused }, + // No declaration at all: a stored select computed from the count, whose option list lacks the value past the cap. + { name: '(iii) a stored computed field over its count with no bound, refused by its own option list', make: capCase(OCAP), live: refused }, + // Not a rule: a child's stored field computed from the parent's summary. + { name: 'a child stored computed field reads the owner count one hop', make: rankCase, live: (_answer, state) => state.ranks[0] !== state.ranks[1], coeLive: true }, +]; + +describe.each(CELLS)('a roll-up a rule reads through its own row or a formula is not deferred (#33795 B): $name', ({ url, make }) => { + const skip = !url; + const rows = (answer: any) => (answer.results as any[]).map((r) => ({ success: r.success, code: r.errors?.[0]?.code, message: r.errors?.[0]?.message })); + + for (const parity of PARITY_CASES) { + for (const options of [{ atomic: true }, { continueOnError: true }] as const) { + const label = 'atomic' in options ? 'atomic' : 'continueOnError'; + it.skipIf(skip)(`${parity.name}, ${label}: answers what today's per-row recompute answers`, async () => { + const { engine } = await boot(make); + const protocol = new ObjectStackProtocolImplementation(engine as never); + const today = await parity.make(engine, 'today'); + const expected = await withoutBatchScope(engine, () => protocol.updateManyData({ object: today.object, records: today.records, options, context: SYSTEM.context } as never)) as any; + const batch = await parity.make(engine, 'batch'); + const answer = await protocol.updateManyData({ object: batch.object, records: batch.records, options, context: SYSTEM.context } as never) as any; + // The case is live: one by one the batch is refused, a lock drops the second note, or the + // second row stores the first row's recompute. Under continueOnError the cap cases end in + // the same rows either way (the refused recompute is logged), so there they pin parity only. + if ('atomic' in options || parity.coeLive) expect(parity.live(expected, await today.state())).toBe(true); + expect({ success: answer.success, rows: rows(answer) }).toEqual({ success: expected.success, rows: rows(expected) }); + expect(await batch.state()).toEqual(await today.state()); + }); + } + } +}); + /** A stored number as a number: PostgreSQL may answer a numeric aggregate as text. */ function num(v: unknown): number | null { if (v == null) return null; diff --git a/packages/qa/dogfood/vitest.config.ts b/packages/qa/dogfood/vitest.config.ts index f2f31749d70..526ff52b916 100644 --- a/packages/qa/dogfood/vitest.config.ts +++ b/packages/qa/dogfood/vitest.config.ts @@ -249,6 +249,15 @@ export default defineConfig({ find: /^@objectstack\/metadata-core$/, replacement: path.resolve(__dirname, '../../metadata-core/src/index.ts'), }, + // [#33795] `rollup-grouped-recompute-33795.test.ts` drives the bulk + // update doors (`updateManyData`, `batchData`) of + // `ObjectStackProtocolImplementation` over a real engine and SQL + // driver; the doors' roll-up batch wiring is the pin's subject, so + // it resolves to SOURCE, like the entries above. + { + find: /^@objectstack\/metadata-protocol$/, + replacement: path.resolve(__dirname, '../../metadata-protocol/src/index.ts'), + }, // [#13513] `date-bucket-parity-turso.test.ts` drives // `TursoDriver` itself — it asserts the driver's SQL date // bucketing against the in-memory reference, plus the on-disk diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index 173657384bc..c535b75e380 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -290,11 +290,12 @@ export type EngineFilterJudgement = * guarded call into a `possibly undefined` error and push code back toward the * `any` this contract exists to remove. * - * Three members are optional by ruling, not by this default: {@link judgeFilter} + * Four members are optional by ruling, not by this default: {@link judgeFilter} * (#19995 ruling C), {@link getDisabledActions} (#27842 ruling letter B, - * the `getFlowRegistration?` shape) and {@link getCascadeDeleteObjects} - * (#28001, that shape again). Their callers must work with an engine - * that lacks them, so the optional mark states that requirement in the type. + * the `getFlowRegistration?` shape), {@link getCascadeDeleteObjects} + * (#28001, that shape again) and {@link deferSummaryRecompute} (#33795, + * ruling 6922040858). Their callers must work with an engine that lacks + * them, so the optional mark states that requirement in the type. */ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { // ── Schema access ──────────────────────────────────────────────────── @@ -646,4 +647,59 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { baseContext?: any, opts?: EngineTransactionOptions, ): Promise; + + // ── Batch scope (#33795, ruling 6922040858) ────────────────────────── + /** + * Run `callback` as ONE batch for roll-up summaries: the `summary` + * recompute every write inside it would run after itself is recorded + * instead, and runs once, over every recorded row, when the callback + * settles, where a per-row loop pays a recompute per row. (How few + * statements that takes is the implementation's, not this contract's.) + * + * Shape, as the ruling settled it: a callback, entered and left by the + * engine as {@link transaction} is, with no begin and end pair; a nested + * call joins the open scope and the outermost call runs the recompute. + * + * It defers the roll-up recompute ONLY. Each write's hooks, validation, + * audit and realtime run where they run outside a scope. A summary field a + * rule reads is not deferred (ruling 6928862195). A validation rule of any + * object reading it one hop through a reference, a detail object's + * `requiredWhen` / `readonlyWhen` reading it on `parent`, a rule of the + * summary's own object reading it on its own row, a declared bound + * (`min`, `max`, `precision`, `unique`, …) or unique index on the summary, + * or any stored computed field of that object calculated from it (the + * recompute's write judges its value whatever it declares), each counts, + * whether it reads the + * summary directly, through a formula or stored computed field calculated + * from it, or up a chain of summaries; so does a stored computed field of + * any object that reads it one hop, since it stores what it read. Any of + * them makes the recompute of every roll-up of the child object written + * run after each row, so a rule's answer, and a stored value, during the + * batch is what one-by-one writes give. A hook or flow step that reads a + * parent's summary during the batch reads the value from before the + * batch, as it does during a multi-row insert. + * The scope is ambient: it covers every write made while the callback + * runs under the transaction the scope was opened in (or under none, when + * it was opened outside one), including writes a hook issues on another + * object (a hook's own insert, update or delete), whose roll-ups are + * deferred to the end too. A write under another transaction opened + * within the scope (a hook's own `ctx.api.transaction`, an atomic batch + * reached from inside a non-atomic one) recomputes at once, inside that + * transaction, as outside any scope: it may commit before the scope ends. + * A summary over a summary still recomputes in dependency order. + * + * Every way out of the callback recomputes. Resolved: the callback's + * result, or — when a parent cannot be recomputed after retries — the + * engine's stale-roll-up refusal (`ERR_SUMMARY_RECOMPUTE`) whose `written` + * is that result: the writes are stored, only the named summaries are + * stale. Rejected: the recompute runs for the writes that landed, and the + * callback's own error is rethrown. Opened inside a {@link transaction}, + * the scope's recompute runs before the commit, so a caller that lets the + * refusal escape rolls the batch back. + * + * OPTIONAL by ruling: a caller probes + * `typeof engine.deferSummaryRecompute === 'function'`, and without it + * keeps the per-row recompute — the same values, more statements. + */ + deferSummaryRecompute?(callback: () => Promise): Promise; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9f133d31d81..e9810d8a0f9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2443,6 +2443,9 @@ importers: '@objectstack/driver-turso': specifier: workspace:* version: link:../../drivers/driver-turso + '@objectstack/metadata-protocol': + specifier: workspace:* + version: link:../../metadata-protocol '@objectstack/setup': specifier: workspace:* version: link:../../apps/setup