From 51f0f6780e9ffe1a086c862de97a1187e2edc3c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:56:13 +0000 Subject: [PATCH 01/25] perf(objectql): recompute roll-up summaries with one grouped aggregate per descriptor and one write per parent Claude-Session: https://claude.ai/code/session_01FEkQ5pHNFS9mn8hS13iGyL Co-authored-by: Claude --- .../src/engine-summaries-and-expansion.ts | 142 +++++++++++++++--- packages/objectql/src/summary-aggregate.ts | 64 ++++++++ 2 files changed, 183 insertions(+), 23 deletions(-) diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index dcfaef8d0bb..40557f7cfa5 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -44,7 +44,7 @@ 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 { aggregateSummaryValue, summaryEmptySetValue } from './summary-aggregate.js'; +import { aggregateSummaryValue, aggregateSummaryValues, summaryEmptySetValue } from './summary-aggregate.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'; @@ -485,39 +485,135 @@ export class SummariesAndExpansionFacet { const recs = Array.isArray(records) ? records : records ? [records] : []; const prevs = Array.isArray(previous) ? previous : previous ? [previous] : []; const failures: SummaryRecomputeFailure[] = []; + const recordFailure = (desc: SummaryDescriptor, parentId: string, err: unknown): void => { + // Retries exhausted (or a non-transient failure). Record it so the + // caller can surface it — one parent's failure must not abort the + // remaining parents' recompute. + this.logger.warn('Roll-up summary recompute failed', { + childObject, parentObject: desc.parentObject, parentId, field: desc.summaryField, + error: (err as any)?.message, + }); + failures.push({ childObject, parentObject: desc.parentObject, parentId, field: desc.summaryField, error: err }); + }; + + // [#33795] Each parent the write touched is written ONCE, carrying all of + // its summary fields — not once per field. And a batch costs one + // aggregate per descriptor — not one per parent: every descriptor's value + // for every touched parent is computed first (one grouped aggregate per + // descriptor), then the parents are written. The values are the ones the + // per-parent loop computed: the same aggregate function over the same + // child rows, the same empty-set fallback. A summary over a summary still + // recomputes in dependency order — each parent write is an engine + // `update`, whose own recompute visits that parent's parents. + type ParentWrite = { parentObject: string; parentId: string; descs: SummaryDescriptor[] }; + const writes = new Map(); + const idsByDesc = new Map(); for (const desc of descriptors) { const ids = new Set(); for (const r of recs) { const v = r?.[desc.fkField]; if (v != null && v !== '') ids.add(String(v)); } for (const p of prevs) { const v = p?.[desc.fkField]; if (v != null && v !== '') ids.add(String(v)); } + if (ids.size === 0) continue; + idsByDesc.set(desc, [...ids]); for (const parentId of ids) { - try { - // Retry a transient failure (a turso `fetch failed` on the parent - // aggregate/update) with backoff — a network blip here used to leave - // the parent summary silently stale (framework#3147). - await withTransientRetry(async () => { + // An object name is snake_case, so its first `|` ends it. + const key = `${desc.parentObject}|${parentId}`; + let write = writes.get(key); + if (!write) { write = { parentObject: desc.parentObject, parentId, descs: [] }; writes.set(key, write); } + write.descs.push(desc); + } + } + if (writes.size === 0) return failures; + + // Computing every value before the first write is sound only while no + // write can move a row an aggregate read. The aggregates read + // `childObject` rows; a parent write moves its own object's rows and, + // through its own recompute, its ancestors' along the summary graph. So + // a graph that leads from a parent back to `childObject` — a roll-up + // over its own object, or a cycle across objects — keeps the per-parent + // order, each parent's aggregates read just before its write, as the + // per-parent loop read them: there, an earlier parent's write could move + // a later parent's child rows. + const reachesChild = (): boolean => { + const seen = new Set(); + const queue = [...new Set([...writes.values()].map((w) => w.parentObject))]; + while (queue.length > 0) { + const object = queue.shift()!; + if (object === childObject) return true; + if (seen.has(object)) continue; + seen.add(object); + for (const up of this.getSummaryDescriptors(object)) queue.push(up.parentObject); + } + return false; + }; + + // Retry a transient failure (a turso `fetch failed` on the parent + // aggregate/update) with backoff — a network blip here used to leave + // the parent summary silently stale (framework#3147). + const writeParent = (parentObject: string, parentId: string, fields: Record) => withTransientRetry(async () => { + await this.update( + parentObject, + { id: parentId, ...fields }, + { context: systemCtx, [SUMMARY_RECOMPUTE_WRITE]: true } as any, + ); + }, this.summaryRetryOptions); + + if (reachesChild()) { + for (const { parentObject, parentId, descs } of writes.values()) { + const fields: Record = {}; + const computed: SummaryDescriptor[] = []; + for (const desc of descs) { + try { // The aggregate — parent-FK match ANDed with the optional // per-summary filter, empty-set fallback included — is - // `aggregateSummaryValue` (#6063). Behaviour unchanged; it simply - // lives where the insert-time seed and the one-off NULL backfill - // can read the identical computation instead of copying it. - const value = await aggregateSummaryValue(this.facade, desc, parentId, systemCtx); - await this.update( - desc.parentObject, - { id: parentId, [desc.summaryField]: value }, - { context: systemCtx, [SUMMARY_RECOMPUTE_WRITE]: true } as any, + // `aggregateSummaryValue` (#6063), where the insert-time seed and + // the one-off NULL backfill read the identical computation. + fields[desc.summaryField] = await withTransientRetry( + () => aggregateSummaryValue(this.facade, desc, parentId, systemCtx), this.summaryRetryOptions, ); - }, this.summaryRetryOptions); + computed.push(desc); + } catch (err) { + recordFailure(desc, parentId, err); + } + } + if (computed.length === 0) continue; + try { + await writeParent(parentObject, parentId, fields); } catch (err) { - // Retries exhausted (or a non-transient failure). Record it so the - // caller can surface it — one parent's failure must not abort the - // remaining parents' recompute. - this.logger.warn('Roll-up summary recompute failed', { - childObject, parentObject: desc.parentObject, parentId, field: desc.summaryField, - error: (err as any)?.message, - }); - failures.push({ childObject, parentObject: desc.parentObject, parentId, field: desc.summaryField, error: err }); + for (const desc of computed) recordFailure(desc, parentId, err); } } + return failures; + } + + const values = new Map>(); + for (const [desc, parentIds] of idsByDesc) { + try { + values.set(desc, await withTransientRetry(async () => { + // One parent — a single-row write — asks today's one-parent + // aggregate, statement for statement. Several ask one grouped + // aggregate per chunk of ids. Both read the computation + // `summary-aggregate.ts` owns (#6063). + if (parentIds.length === 1) { + return new Map([[parentIds[0], await aggregateSummaryValue(this.facade, desc, parentIds[0], systemCtx)]]); + } + return await aggregateSummaryValues(this.facade, desc, parentIds, systemCtx); + }, this.summaryRetryOptions)); + } catch (err) { + for (const parentId of parentIds) recordFailure(desc, parentId, err); + } + } + for (const { parentObject, parentId, descs } of writes.values()) { + const fields: Record = {}; + const computed = descs.filter((desc) => values.has(desc)); + if (computed.length === 0) continue; + for (const desc of computed) fields[desc.summaryField] = values.get(desc)!.get(parentId); + try { + await writeParent(parentObject, parentId, fields); + } catch (err) { + // The one write carried every field below, so each is as stale as + // the write left it: one failure per field, as before. + for (const desc of computed) recordFailure(desc, parentId, err); + } } return failures; } diff --git a/packages/objectql/src/summary-aggregate.ts b/packages/objectql/src/summary-aggregate.ts index cea30120c02..d6b3b5c1e71 100644 --- a/packages/objectql/src/summary-aggregate.ts +++ b/packages/objectql/src/summary-aggregate.ts @@ -138,6 +138,70 @@ export async function aggregateSummaryValue( return value == null ? summaryEmptySetValue(desc.fn) : value; } +/** + * The most parent ids one grouped roll-up aggregate names in its `$in`. A + * batch touching more parents asks one grouped aggregate per chunk, so the + * bound-parameter count of a statement stays far below every dialect's limit + * (SQLite 32766, PostgreSQL 65535) whatever the batch size. + */ +export const SUMMARY_GROUPED_AGGREGATE_CHUNK = 500; + +/** + * Compute ONE roll-up descriptor's value for EVERY parent id a batch touched, + * in one grouped aggregate per {@link SUMMARY_GROUPED_AGGREGATE_CHUNK} ids + * (`where fk in (…) group by fk`), instead of one aggregate per parent. + * + * The value each parent gets is the value {@link aggregateSummaryValue} gives + * it alone: the same function over the same rows — the parent-FK match ANDed + * with the descriptor's optional predicate — and the same empty-set fallback + * for a parent no row matched, which a grouped aggregate answers by leaving + * its group out. Keys of the answer are the ids as handed in. + * + * [ADR-0144 D6, amended] Every group is one parent's rows, through `fkField`, + * so the roll-up channel rides this aggregate as it rides the one-parent one: + * grouped by the master_detail, a child amount that follows its parent's + * currency is one currency per group. It rides only when every id is one + * concrete id, for the reason {@link aggregateSummaryValue} gives. + */ +export async function aggregateSummaryValues( + engine: SummaryAggregateEngine, + desc: SummaryDescriptor, + parentIds: readonly string[], + execCtx?: unknown, +): Promise> { + const found = new Map(); + // The aggregate's alias must not be the group key's name, or the two + // columns of one answer row would collide. + const alias = desc.fkField === 'value' ? 'summary_value' : 'value'; + for (let start = 0; start < parentIds.length; start += SUMMARY_GROUPED_AGGREGATE_CHUNK) { + const chunk = parentIds.slice(start, start + SUMMARY_GROUPED_AGGREGATE_CHUNK); + const concrete = chunk.every((id: unknown) => (typeof id === 'string' && id !== '') || (typeof id === 'number' && Number.isFinite(id))); + const fkMatch = { [desc.fkField]: { $in: chunk } }; + const where = desc.filter ? { $and: [fkMatch, desc.filter] } : fkMatch; + const rows = await engine.aggregate(desc.childObject, { + where, + groupBy: [desc.fkField], + aggregations: [{ + function: desc.fn, + ...(desc.fn === 'count' ? {} : { field: desc.sourceField }), + alias, + }], + context: execCtx, + }, concrete ? { [ROLLUP_AGGREGATE_OPTION]: desc.fkField } : undefined); + for (const row of rows ?? []) { + const key = row?.[desc.fkField]; + if (key == null || key === '') continue; + found.set(String(key), row?.[alias]); + } + } + const values = new Map(); + for (const id of parentIds) { + const value = found.get(String(id)); + values.set(id, value == null ? summaryEmptySetValue(desc.fn) : value); + } + return values; +} + /** * [#26950] The matched rows a predicate delete hands the recompute, less every * foreign key that names a row the same delete removed. From 6659391dd6475d488b6681e4ec52b4f1583e4fae Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:00:26 +0000 Subject: [PATCH 02/25] test(dogfood): pin roll-up recompute statement counts and value parity on SQLite and PostgreSQL Claude-Session: https://claude.ai/code/session_01FEkQ5pHNFS9mn8hS13iGyL Co-authored-by: Claude --- .../rollup-grouped-recompute-33795.test.ts | 246 ++++++++++++++++++ 1 file changed, 246 insertions(+) create mode 100644 packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts diff --git a/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts new file mode 100644 index 00000000000..d05475bb863 --- /dev/null +++ b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts @@ -0,0 +1,246 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * #33795 — a batch write recomputes its parents' roll-up `summary` fields with + * ONE grouped aggregate per summary field and ONE write per parent, and the + * values are the ones the per-parent recompute wrote. + * + * The real engine over a real `SqlDriver`, so a statement here is a statement + * the database ran (knex's `query` event), never a driver call standing in for + * one. Two cells: embedded SQLite always, and PostgreSQL when + * `OS_TEST_POSTGRES_URL` names a server (a named skip otherwise). + * + * Two pins per cell: + * + * 1. Statement counts for a 50-row `createMany` over 10 parents and for a + * 50-row engine `update` loop over 10 parents (the per-row writes the + * bulk data door issues), each with 0, 1 and 2 summary fields on the + * parent. Before #33795 each summary field cost 4 statements per parent + * the batch named (an aggregate, two parent reads, one parent write), + * once per field; after it, a batch costs one aggregate per field plus + * one write per parent carrying every field. + * 2. Value parity across every summary kind — count, sum, min, max, avg, and + * a filtered count and sum — after inserts, a re-parent, an update loop, + * a predicate update and a predicate delete: every parent's stored value + * equals the one-parent aggregate `aggregateSummaryValue` (the computation + * the per-parent recompute ran, unchanged) and a hand count of the rows. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectQL, aggregateSummaryValue } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const PG_URL = process.env.OS_TEST_POSTGRES_URL; + +const CELLS = [ + { + name: 'sqlite (better-sqlite3 :memory:)', + url: 'sqlite', + make: () => new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + }, + { + name: 'postgresql (OS_TEST_POSTGRES_URL)', + url: PG_URL, + make: () => new SqlDriver({ client: 'pg', connection: PG_URL as string }), + }, +] as const; + +const SYSTEM = { context: { userId: 'u_33795', isSystem: true } }; + +/** A parent with `n` summary fields over its master-detail child, the bench's `rollupPair` shape. */ +function rollupPair(n: 0 | 1 | 2) { + const parent = `r33795_roll${n}`; + const child = `${parent}_item`; + const summaries: Record = {}; + if (n >= 1) summaries.total_quantity = { type: 'summary', label: 'Total quantity', summaryOperations: { object: child, field: 'quantity', function: 'sum' } }; + if (n >= 2) summaries.item_count = { type: 'summary', label: 'Item count', summaryOperations: { object: child, function: 'count' } }; + return [ + { name: parent, label: `Roll-up parent (${n})`, fields: { name: { type: 'text', label: 'Name' }, ...summaries } }, + { + name: child, + label: `Roll-up item (${n})`, + fields: { + name: { type: 'text', label: 'Name' }, + parent: { type: 'master_detail', label: 'Parent', reference: parent, deleteBehavior: 'cascade' }, + quantity: { type: 'number', label: 'Quantity' }, + }, + }, + ]; +} + +/** Every summary kind over one child, filtered ones included. */ +const KIND_PARENT = 'r33795_kinds'; +const KIND_CHILD = 'r33795_kinds_item'; +const KIND_FIELDS = { + n_count: { function: 'count' }, + q_sum: { function: 'sum', field: 'quantity' }, + q_min: { function: 'min', field: 'quantity' }, + q_max: { function: 'max', field: 'quantity' }, + q_avg: { function: 'avg', field: 'quantity' }, + open_count: { function: 'count', filter: { status: 'open' } }, + open_sum: { function: 'sum', field: 'quantity', filter: { status: 'open' } }, +} as const; +const KIND_OBJECTS = [ + { + name: KIND_PARENT, + label: 'Kinds parent', + fields: { + name: { type: 'text', label: 'Name' }, + ...Object.fromEntries(Object.entries(KIND_FIELDS).map(([key, op]) => [ + key, { type: 'summary', label: key, summaryOperations: { object: KIND_CHILD, ...op } }, + ])), + }, + }, + { + name: KIND_CHILD, + label: 'Kinds item', + fields: { + name: { type: 'text', label: 'Name' }, + parent: { type: 'master_detail', label: 'Parent', reference: KIND_PARENT, deleteBehavior: 'cascade' }, + quantity: { type: 'number', label: 'Quantity' }, + status: { type: 'select', label: 'Status', options: [{ label: 'Open', value: 'open' }, { label: 'Closed', value: 'closed' }] }, + }, + }, +]; + +const OBJECTS = [...rollupPair(0), ...rollupPair(1), ...rollupPair(2), ...KIND_OBJECTS]; + +const engines: ObjectQL[] = []; +afterEach(async () => { + while (engines.length) { + try { await engines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot(make: () => SqlDriver): Promise<{ engine: ObjectQL; driver: SqlDriver }> { + const driver = make(); + await driver.connect(); + for (const def of [...OBJECTS].reverse()) await driver.getKnex().schema.dropTableIfExists(def.name); + const engine = new ObjectQL(); + engines.push(engine); + engine.registerDriver(driver as never, true); + await engine.init(); + for (const def of OBJECTS) engine.registry.registerObject(def as never, '@objectstack/dogfood', 'r33795'); + await engine.syncSchemas(); + await installDefaultOrganization(engine as never); + return { engine, driver }; +} + +/** Run `fn` and count the statements the database ran meanwhile. */ +async function statementsOf(driver: SqlDriver, fn: () => Promise): Promise { + let n = 0; + const knex = driver.getKnex(); + const listen = () => { n += 1; }; + knex.on('query', listen); + try { await fn(); } finally { knex.removeListener('query', listen); } + return n; +} + +async function seedParents(engine: ObjectQL, object: string, count: number): Promise { + const rows = await engine.insert(object, Array.from({ length: count }, (_, i) => ({ name: `p${i}` })), SYSTEM) as Array<{ id: string }>; + return rows.map((r) => r.id); +} + +const BATCH = 50; +const PARENTS = 10; + +describe.each(CELLS)('roll-up grouped recompute (#33795): $name', ({ url, make }) => { + const skip = !url; + + it.skipIf(skip)('a batch costs one aggregate per summary field and one write per parent', async () => { + const { engine, driver } = await boot(make); + const measured: Record> = { createMany: {}, updateLoop: {} }; + 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); + let created: Array<{ id: string }> = []; + measured.createMany[n] = await statementsOf(driver, async () => { + 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 }>; + }); + measured.updateLoop[n] = await statementsOf(driver, async () => { + for (const [k, row] of created.entries()) { + await engine.update(child, { quantity: 2 + (k % 7) }, { where: { id: row.id }, ...SYSTEM }); + } + }); + } + // The control: no summary field, no recompute — the base the others add to. + const base = { createMany: measured.createMany[0], updateLoop: measured.updateLoop[0] }; + // createMany: one aggregate per field, then one write per parent + // (3 statements: the update and its two reads of the parent row). + expect(measured.createMany[1] - base.createMany, JSON.stringify(measured)).toBe(1 + PARENTS * 3); + expect(measured.createMany[2] - base.createMany, JSON.stringify(measured)).toBe(2 + PARENTS * 3); + // The per-row update loop names one parent per row: per row, one + // aggregate per field and one write carrying every field. + expect(measured.updateLoop[1] - base.updateLoop, JSON.stringify(measured)).toBe(BATCH * (1 + 3)); + expect(measured.updateLoop[2] - base.updateLoop, JSON.stringify(measured)).toBe(BATCH * (2 + 3)); + console.log(`[#33795] statements ${url === 'sqlite' ? 'sqlite' : 'postgresql'}: ${JSON.stringify(measured)}`); + }); + + it.skipIf(skip)('every summary kind lands the value the one-parent aggregate computes', async () => { + const { engine } = await boot(make); + const parents = await seedParents(engine, KIND_PARENT, 6); + const rows = await engine.insert(KIND_CHILD, Array.from({ length: 40 }, (_, k) => ({ + name: `k${k}`, + // Parent 5 never gets a child: its min/max/avg stay null, count/sum 0. + 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)); + } + } + }; + await check('after createMany'); + + // A re-parent moves rows between parents: both sides recompute. + await engine.update(KIND_CHILD, { parent: parents[1] }, { where: { id: rows[0].id }, ...SYSTEM }); + await check('after a re-parent'); + + // The bulk door's loop: one engine update per row. + for (const [k, row] of rows.slice(0, 20).entries()) { + await engine.update(KIND_CHILD, { quantity: k - 5, status: k % 2 ? 'open' : 'closed' }, { where: { id: row.id }, ...SYSTEM }); + } + await check('after an update loop'); + + // A predicate update and a predicate delete name many parents in one call. + await engine.update(KIND_CHILD, { status: 'open' }, { where: { quantity: { $gt: 2 } }, multi: true, ...SYSTEM } as never); + await check('after a predicate update'); + await engine.delete(KIND_CHILD, { where: { status: 'closed' }, multi: true, ...SYSTEM } as never); + await check('after a predicate delete'); + }); +}); + +/** 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; + const n = Number(v); + return Number.isFinite(n) ? Math.round(n * 1e9) / 1e9 : NaN; +} + +function handValue(children: Array>, parentId: string, op: { function: string; field?: string; filter?: { status: string } }): number | null { + const mine = children.filter((c) => c.parent === parentId && (!op.filter || c.status === op.filter.status)); + if (op.function === 'count') return mine.length; + const values = mine.map((c) => c[op.field as string]).filter((v) => v != null).map(Number); + if (op.function === 'sum') return values.reduce((a, b) => a + b, 0); + if (values.length === 0) return null; + if (op.function === 'min') return Math.min(...values); + if (op.function === 'max') return Math.max(...values); + return num(values.reduce((a, b) => a + b, 0) / values.length); +} From 02e274bd70d55ebdf1bee21f510133aef0c85ab6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 15:19:19 +0000 Subject: [PATCH 03/25] test(objectql): pin one parent write per recompute and teach three doubles the $in a grouped aggregate asks Claude-Session: https://claude.ai/code/session_01FEkQ5pHNFS9mn8hS13iGyL Co-authored-by: Claude --- .changeset/rollup-grouped-recompute-33795.md | 12 ++ .../engine-summary-recompute-context.test.ts | 4 +- .../objectql/src/engine-summary-retry.test.ts | 2 + .../engine-update-prior-read-scope.test.ts | 5 + packages/objectql/src/summary-rollup.test.ts | 137 ++++++++++++++++++ 5 files changed, 159 insertions(+), 1 deletion(-) create mode 100644 .changeset/rollup-grouped-recompute-33795.md diff --git a/.changeset/rollup-grouped-recompute-33795.md b/.changeset/rollup-grouped-recompute-33795.md new file mode 100644 index 00000000000..b972092588d --- /dev/null +++ b/.changeset/rollup-grouped-recompute-33795.md @@ -0,0 +1,12 @@ +--- +'@objectstack/objectql': patch +--- + +Clause-②: no (same values for every summary kind on both dialects; fewer statements; no accepted shape or public export widens; if collapsing a parent's per-field updates fires a parent hook fewer times, the PR body says so, as the card asks; the dev confirms) +Metadata-protocol: none + +Roll-up `summary` recompute after a child write is cheaper. Each parent the write touched is now written once, carrying all of its summary fields, instead of once per summary field. A multi-row write (`insert` with an array, a predicate `update` or `delete`) computes each summary field for all of its parents with one grouped aggregate (`where fk in (…) group by fk`, at most 500 ids per statement) instead of one aggregate per parent. The stored values are unchanged for every summary kind (count, sum, min, max, avg, filtered). + +What a parent's write path observes changes in count only: a parent with two summary fields over the same child now runs its update hooks, validation, audit entry and realtime event once per recompute instead of twice, with both fields in one payload. A single-row write still asks the same one-parent aggregate. A roll-up over its own object, or a cycle of roll-ups that leads back to the child object, keeps the per-parent order. A failed parent write still reports one failure per summary field it carried. + +Measured on SQLite and PostgreSQL 16 through the engine: a 50-row insert over 10 parents with two summary fields went from 81 to 33 statements (one summary field: 41 to 32); a loop of 50 single-row updates with two summary fields went from 550 to 400 statements. diff --git a/packages/objectql/src/engine-summary-recompute-context.test.ts b/packages/objectql/src/engine-summary-recompute-context.test.ts index f1cbe44a47f..52c79106635 100644 --- a/packages/objectql/src/engine-summary-recompute-context.test.ts +++ b/packages/objectql/src/engine-summary-recompute-context.test.ts @@ -79,12 +79,14 @@ function makeDriver() { return s; }; // Flat equality plus `$and` — the two shapes `aggregateSummaryValue` and the - // row-filter middleware below actually produce. + // row-filter middleware below actually produce — and a field's `$in`, the + // shape a recompute naming several parents groups them under (#33795). const matches = (row: any, where: any): boolean => { if (!where || typeof where !== 'object') return true; return Object.entries(where).every(([k, v]) => { if (k === '$and') return (v as any[]).every((sub) => matches(row, sub)); if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + if (v && typeof v === 'object' && Array.isArray((v as any).$in)) return (v as any).$in.includes(row?.[k]); return row?.[k] === v; }); }; diff --git a/packages/objectql/src/engine-summary-retry.test.ts b/packages/objectql/src/engine-summary-retry.test.ts index ec56ff29277..caeb2623a4f 100644 --- a/packages/objectql/src/engine-summary-retry.test.ts +++ b/packages/objectql/src/engine-summary-retry.test.ts @@ -19,6 +19,8 @@ function makeDriver(opts: { onParentUpdate?: (parentId: string, callN: number) = if (!where || typeof where !== 'object') return true; return Object.entries(where).every(([k, v]) => { if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + // A field's `$in`: a recompute naming several parents groups them under it (#33795). + if (v && typeof v === 'object' && Array.isArray((v as any).$in)) return (v as any).$in.includes(row?.[k]); return row?.[k] === v; }); }; diff --git a/packages/objectql/src/engine-update-prior-read-scope.test.ts b/packages/objectql/src/engine-update-prior-read-scope.test.ts index 547d1e7d9d1..075f023699e 100644 --- a/packages/objectql/src/engine-update-prior-read-scope.test.ts +++ b/packages/objectql/src/engine-update-prior-read-scope.test.ts @@ -135,6 +135,11 @@ function makeCountingDriver() { continue; } if (k.startsWith('$')) continue; + // A field's `$in`: a recompute naming several parents groups them under it (#33795). + if (v && typeof v === 'object' && Array.isArray((v as any).$in)) { + if (!(v as any).$in.includes(row[k])) return false; + continue; + } const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; if ((row[k] ?? null) !== (expected ?? null)) return false; } diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index c4f8002abcc..7ebb6a61f4b 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -653,3 +653,140 @@ describe('[#26950] a predicate update or delete hands recomputeSummaries its mat expect(storeFor('node').get(root.id).kids).toBe(0); }); }); + +// [#33795] A write recomputes each touched parent with ONE write carrying all +// of its summary fields, and a batch computes each summary field for all of +// its parents in ONE grouped aggregate. The SQL statement counts and the +// per-dialect value parity are pinned on real drivers +// (`packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts`); these +// pin what only the engine decides: how many parent writes and hook runs a +// recompute makes, the fallback that keeps a self-referencing roll-up in +// per-parent order, and how a failed write is reported. +describe('[#33795] grouped roll-up recompute', () => { + let engine: ObjectQL; + let storeFor: ReturnType['storeFor']; + let log: ReturnType['log']; + let driver: any; + + 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' }, + // A summary over a summary: the regions total their invoices' totals. + 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); + // A roll-up over its own object: a task counts its direct subtasks. + engine.registry.registerObject({ + name: 'task', + fields: { + name: { type: 'text' }, + parent_task: { type: 'lookup', reference: 'task' }, + subtask_count: { type: 'summary', summaryOperations: { object: 'task', function: 'count' } }, + }, + } as any); + }); + + /** The reads of `object`'s rows the recompute's aggregates made: the in-memory aggregate reads through `find`. */ + const aggregateReads = (object: string, from: number) => + log.slice(from).filter((e) => e.op === 'find' && e.object === object).length; + + it('writes each parent once with all its summary fields, and aggregates each field once per batch', async () => { + const [a, b, c] = await engine.insert('inv', [{ name: 'A' }, { name: 'B' }, { name: 'C' }]) as any[]; + const parentWrites: Array> = []; + engine.registerHook('beforeUpdate', async (ctx: any) => { parentWrites.push({ ...ctx.input.data }); }, { object: 'inv' }); + const before = log.length; + 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 }, + ]); + // One hook run per parent (it was one per parent per field), each + // carrying both fields. + expect(parentWrites).toHaveLength(3); + for (const write of parentWrites) expect(Object.keys(write).sort()).toEqual(['id', 'line_count', 'line_total']); + // One aggregate per summary field over all three parents (it was one per + // parent per field: six). + expect(aggregateReads('inv_line', before)).toBe(2); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 5, line_count: 2 }); + expect(storeFor('inv').get(b.id)).toMatchObject({ line_total: 7, line_count: 2 }); + expect(storeFor('inv').get(c.id)).toMatchObject({ line_total: 9, line_count: 2 }); + }); + + it('a single-row write asks the one-parent aggregate and writes the parent once', async () => { + const [a] = await engine.insert('inv', [{ name: 'A' }]) as any[]; + let hookRuns = 0; + engine.registerHook('beforeUpdate', async () => { hookRuns += 1; }, { object: 'inv' }); + const before = log.length; + await engine.insert('inv_line', { inv: a.id, amount: 10 }); + expect(hookRuns).toBe(1); + const reads = log.slice(before).filter((e) => e.op === 'find' && e.object === 'inv_line'); + expect(reads).toHaveLength(2); + // The one-parent aggregate's equality on the id, not a grouped `$in`. + for (const read of reads) expect(JSON.stringify(read.ast?.where)).toContain(`"inv":"${a.id}"`); + expect(storeFor('inv').get(a.id)).toMatchObject({ line_total: 10, line_count: 1 }); + }); + + it('a summary over a summary still recomputes up the chain', 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[]; + await engine.insert('inv_line', [{ inv: a.id, amount: 10 }, { inv: b.id, amount: 32 }, { inv: a.id, amount: 1 }]); + expect(storeFor('region').get(r.id).grand_total).toBe(43); + await engine.update('inv_line', { amount: 0 }, { where: { inv: a.id }, multi: true } as any); + expect(storeFor('region').get(r.id).grand_total).toBe(32); + }); + + it('a roll-up over its own object keeps the per-parent order, and lands the same values', async () => { + const [root] = await engine.insert('task', [{ name: 'root' }]) as any[]; + const [mid] = await engine.insert('task', [{ name: 'mid', parent_task: root.id }]) as any[]; + const before = log.length; + // One batch naming two parents, one of them (mid) a child of the other. + await engine.insert('task', [ + { name: 'leaf 1', parent_task: mid.id }, { name: 'leaf 2', parent_task: mid.id }, { name: 'sibling', parent_task: root.id }, + ]); + expect(storeFor('task').get(mid.id).subtask_count).toBe(2); + expect(storeFor('task').get(root.id).subtask_count).toBe(2); + // Per parent, never grouped: no aggregate in this batch read a `$in`. + const grouped = log.slice(before).filter((e) => e.op === 'find' && e.object === 'task' && JSON.stringify(e.ast?.where).includes('$in')); + expect(grouped).toHaveLength(0); + }); + + it('a failed parent write reports every field it carried; the other parents are still written', async () => { + const [a, b] = await engine.insert('inv', [{ name: 'A' }, { name: 'B' }]) as any[]; + 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.insert('inv_line', [{ inv: a.id, amount: 1 }, { inv: b.id, amount: 2 }]); + } catch (e) { caught = e; } + expect(caught?.code).toBe('ERR_SUMMARY_RECOMPUTE'); + expect(caught.failures.map((f: any) => [f.parentId, f.field]).sort()).toEqual([[a.id, 'line_count'], [a.id, 'line_total']]); + expect(storeFor('inv').get(b.id)).toMatchObject({ line_total: 2, line_count: 1 }); + }); +}); From 7480459d6cd718a925c1ff7bf82f3de716c41f97 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:37:47 +0000 Subject: [PATCH 04/25] wip(objectql): roll-up batch scope deferSummaryRecompute (work in progress, #33795 second half) Work in progress, stopped by the seat mid-build. Not reviewed, not built, not tested. Done: - IObjectQLEngine.deferSummaryRecompute? (optional by ruling 6922040858) and the same optional member on MetadataHostEngine. - ObjectQL.deferSummaryRecompute: callback form, ambient AsyncLocalStorage scope (summaryBatchStore), nested call joins the outer scope; inside it recomputeSummaries records the rows' foreign keys (merged per child object, tenant and user) instead of running; the outermost call runs one recompute per entry after the callback settles, on every way out; a failure after a resolved callback throws SummaryRecomputeError with written = the callback's result. Not done: - protocol-batch-data.ts: runUpdateManyLoop and the update arm of runBatchDataLoop do not probe or use the member yet (non-atomic: log stale lines and keep the outcome; atomic: roll back). - Pins (statement counts, value parity, ablations, the three extra pins), changeset, generated spec artifacts, PR. Claude-Session: https://claude.ai/code/session_01FEkQ5pHNFS9mn8hS13iGyL Co-Authored-By: Claude --- packages/metadata-protocol/src/host-engine.ts | 9 ++ .../src/engine-summaries-and-expansion.ts | 109 +++++++++++++++++- packages/objectql/src/engine.ts | 50 +++++++- .../spec/src/contracts/objectql-engine.ts | 42 ++++++- 4 files changed, 203 insertions(+), 7 deletions(-) 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/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 40557f7cfa5..191a8f4009b 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -43,7 +43,7 @@ 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 type { SummaryDescriptor } from './summary-aggregate.js'; import { ENGINE_WIRE_ONLY_SLOTS, WIRE_ONLY_CANONICAL_SHAPES } from './engine-top-level.js'; @@ -73,6 +73,47 @@ 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 { + /** + * 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. + */ +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]); +} + /** * 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 @@ -93,6 +134,7 @@ export interface SummariesAndExpansionHost { invalidateSummaryIndex: ObjectQLClass['invalidateSummaryIndex']; readonly logger: ObjectQLClass['logger']; serveReferenceNames: ObjectQLClass['serveReferenceNames']; + readonly summaryBatchStore: ObjectQLClass['summaryBatchStore']; summaryIndex: ObjectQLClass['summaryIndex']; summaryIndexByParent: ObjectQLClass['summaryIndexByParent']; summaryIndexRevision: ObjectQLClass['summaryIndexRevision']; @@ -476,9 +518,30 @@ 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. + const scope = this.summaryBatchStore.getStore(); + if (scope && !scope.closed) { + 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 +681,48 @@ export class SummariesAndExpansionFacet { return failures; } + /** The body of `ObjectQL#deferSummaryRecompute`; the method's docblock there is its contract. */ + 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, 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 7557e0a9da8..5936aaa9b46 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,14 @@ export class ObjectQL implements IObjectQLEngine { */ private readonly cascadeDeleteSets = new AsyncLocalStorage(); + /** + * [#33795] The open roll-up deferral scope ({@link deferSummaryRecompute}), + * ambient for {@link txStore}'s reason: a row's write reaches + * `recomputeSummaries` through hooks and nested engine calls no caller can + * thread a marker through. + */ + 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 +4138,45 @@ export class ObjectQL implements IObjectQLEngine { return summaryRefreshesSettled(this); } + /** + * [#33795] 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 — one grouped aggregate per summary + * field and one write per parent for the whole batch, 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 {@link 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. So a rule or hook that + * reads a parent's summary during the batch reads the value from before + * the batch, as it already does during a multi-row insert or a predicate + * update. + * + * 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 {@link transaction}, the recompute runs inside it, before + * the commit, and a caller that lets the refusal escape rolls the batch back. + * A write recorded after the callback settled (work it started and did not + * await) recomputes at once. + */ + deferSummaryRecompute(callback: () => Promise): Promise { + // [#33795] The body is in `engine-summaries-and-expansion.ts` (see `SummariesAndExpansionHost`). + return SummariesAndExpansionFacet.deferSummaryRecompute.call(summariesAndExpansionHost.of(this), callback); + } + 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); @@ -6140,6 +6187,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; }, diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index 173657384bc..85f32bc9f27 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,37 @@ 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 — one grouped aggregate per summary field and one write per + * parent for the batch, where a per-row loop pays a recompute per row. + * + * 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, so a rule or hook + * that reads a parent's summary during the batch reads the value from + * before the batch (as during a multi-row insert or a predicate update). + * 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. Inside a {@link transaction} the + * 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; } From 28d87629a07fa3313d5aff7ea7021803ccb283a8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:44:12 +0000 Subject: [PATCH 05/25] feat(metadata-protocol): run the bulk update doors as one roll-up batch runUpdateManyLoop and the update arm of runBatchDataLoop probe the engine's optional deferSummaryRecompute and run their per-row loop inside it, so the parents' summaries recompute once when the loop settles. Atomic: a recompute failure fails the last landed row and rolls the batch back with today's envelope. Non-atomic: logged, rows stay written. WIP: untested. Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- .../src/protocol-batch-data.ts | 187 +++++++++++++----- packages/metadata-protocol/src/protocol.ts | 17 ++ 2 files changed, 151 insertions(+), 53 deletions(-) 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.ts b/packages/metadata-protocol/src/protocol.ts index 67c695f4298..568bc7c0f3a 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -5719,6 +5719,13 @@ 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. During the batch a parent's + * summary holds its value from before the batch. The other operations + * keep their per-row recompute. */ private runBatchDataLoop(args: { object: string; @@ -5972,6 +5979,16 @@ 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. During the batch a parent's summary holds its 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; From 486a266e17f31d108ebc3c28b683c84e003af6af Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:50:48 +0000 Subject: [PATCH 06/25] test(objectql): pin the roll-up batch scope Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- packages/objectql/src/engine.ts | 2 +- packages/objectql/src/summary-rollup.test.ts | 194 +++++++++++++++++++ 2 files changed, 195 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 5936aaa9b46..9c3a1503047 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -4174,7 +4174,7 @@ export class ObjectQL implements IObjectQLEngine { */ deferSummaryRecompute(callback: () => Promise): Promise { // [#33795] The body is in `engine-summaries-and-expansion.ts` (see `SummariesAndExpansionHost`). - return SummariesAndExpansionFacet.deferSummaryRecompute.call(summariesAndExpansionHost.of(this), callback); + return SummariesAndExpansionFacet.deferSummaryRecompute.call(summariesAndExpansionHost.of(this), callback) as Promise; } private initializeSummaryFields(object: string, record: any): any { diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 7ebb6a61f4b..7882dacb92c 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -790,3 +790,197 @@ 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 (ctx: any) => { + const parent = await engine.findOne('inv', { where: { id: a.id } } as any); + 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 } as any); + await engine.update('inv_line', { amount: 0 }, { where: { id: lines[3].id }, context: trxCtx } as any); + }); + }); + 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('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); + }); +}); From 9c6406ec2ac8aac75a9a55a34a2848828a05181f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:52:10 +0000 Subject: [PATCH 07/25] test(metadata-protocol): pin the bulk update doors' roll-up batch Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- .../src/protocol.many-data-atomic.test.ts | 144 ++++++++++++++++++ 1 file changed, 144 insertions(+) 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..3cd12cb1490 100644 --- a/packages/metadata-protocol/src/protocol.many-data-atomic.test.ts +++ b/packages/metadata-protocol/src/protocol.many-data-atomic.test.ts @@ -371,3 +371,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); + }); +}); From ce3dea6c724f9c4d26359146c2d630f553d4ae76 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:54:21 +0000 Subject: [PATCH 08/25] test(dogfood): pin the bulk update door's roll-up batch statements and values Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- packages/qa/dogfood/package.json | 1 + .../rollup-grouped-recompute-33795.test.ts | 119 ++++++++++++++++++ pnpm-lock.yaml | 3 + 3 files changed, 123 insertions(+) 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..b3656e29e36 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; @@ -227,6 +228,124 @@ 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'); + }); +}); + /** 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/pnpm-lock.yaml b/pnpm-lock.yaml index f2ae7c3f2db..daf92bedf42 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2440,6 +2440,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 From c37b71ea6c741b0bbbe187b7ef75a7aaaaaa485a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 16:57:59 +0000 Subject: [PATCH 09/25] chore(changeset): roll-up batch deferral on the bulk update doors Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 .changeset/rollup-batch-deferral-33795.md diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md new file mode 100644 index 00000000000..930c30f66d8 --- /dev/null +++ b/.changeset/rollup-batch-deferral-33795.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': patch +'@objectstack/objectql': patch +'@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: none + +**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: 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. Inside a transaction the recompute runs before the commit. + +**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: + +- During a bulk update, a parent's summary holds its value from before the batch until the batch ends, as it already did during a predicate update and in the stored row during a multi-row insert. A hook, or a validation rule, on a child row that reads its parent's summary while the batch runs reads that pre-batch value; before this change each row saw the recompute of the rows before it. (A multi-row insert's validation rules see the batch's earlier rows through an in-memory overlay; a bulk update has no such overlay.) +- 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. + +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. From a4adf634c417742762fc625e1a860337e8c3b37d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:02:49 +0000 Subject: [PATCH 10/25] test(objectql): drop an unused hook parameter Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- packages/objectql/src/summary-rollup.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 7882dacb92c..b2810069cd5 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -875,7 +875,7 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { 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 (ctx: any) => { + engine.registerHook('beforeUpdate', async () => { const parent = await engine.findOne('inv', { where: { id: a.id } } as any); seen.push((parent as any)?.line_total); }, { object: 'inv_line' }); From 2f463e92dc706acc3c15209b9abfaccca10b84ae Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:15:33 +0000 Subject: [PATCH 11/25] refactor(objectql): keep the batch-scope docblock in the facet, not the facade engine.ts is a facade under a line ceiling; the method there is a one-line delegation and the contract text lives with the body. Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- .../src/engine-summaries-and-expansion.ts | 36 +++++++++++++++- packages/objectql/src/engine.ts | 43 +------------------ .../spec/src/contracts/objectql-engine.ts | 2 +- 3 files changed, 38 insertions(+), 43 deletions(-) diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 191a8f4009b..6db38e8b232 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -681,7 +681,41 @@ export class SummariesAndExpansionFacet { return failures; } - /** The body of `ObjectQL#deferSummaryRecompute`; the method's docblock there is its contract. */ + /** + * [#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 — one grouped aggregate per summary + * field and one write per parent for the whole batch, 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. So a rule or hook that + * reads a parent's summary during the batch reads the value from before + * the batch, as it already does during a predicate update. (A multi-row + * insert's validation rules see the batch's earlier rows through an + * in-memory overlay, `summary-batch-accumulation.ts`; a scope has none.) + * + * 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. + * 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(); diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 9c3a1503047..4a883fd6486 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -447,12 +447,7 @@ export class ObjectQL implements IObjectQLEngine { */ private readonly cascadeDeleteSets = new AsyncLocalStorage(); - /** - * [#33795] The open roll-up deferral scope ({@link deferSummaryRecompute}), - * ambient for {@link txStore}'s reason: a row's write reaches - * `recomputeSummaries` through hooks and nested engine calls no caller can - * thread a marker through. - */ + /** [#33795] The open roll-up batch scope (`SummaryBatchScope` says why it is ambient). */ private readonly summaryBatchStore = new AsyncLocalStorage(); /** @@ -4138,42 +4133,8 @@ export class ObjectQL implements IObjectQLEngine { return summaryRefreshesSettled(this); } - /** - * [#33795] 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 — one grouped aggregate per summary - * field and one write per parent for the whole batch, 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 {@link 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. So a rule or hook that - * reads a parent's summary during the batch reads the value from before - * the batch, as it already does during a multi-row insert or a predicate - * update. - * - * 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 {@link transaction}, the recompute runs inside it, before - * the commit, and a caller that lets the refusal escape rolls the batch back. - * A write recorded after the callback settled (work it started and did not - * await) recomputes at once. - */ + /** [#33795] `IObjectQLEngine.deferSummaryRecompute`: the body and its docblock are in `engine-summaries-and-expansion.ts`. */ deferSummaryRecompute(callback: () => Promise): Promise { - // [#33795] The body is in `engine-summaries-and-expansion.ts` (see `SummariesAndExpansionHost`). return SummariesAndExpansionFacet.deferSummaryRecompute.call(summariesAndExpansionHost.of(this), callback) as Promise; } diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index 85f32bc9f27..49cd3f326e6 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -663,7 +663,7 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * It defers the roll-up recompute ONLY. Each write's hooks, validation, * audit and realtime run where they run outside a scope, so a rule or hook * that reads a parent's summary during the batch reads the value from - * before the batch (as during a multi-row insert or a predicate update). + * before the batch, as during a predicate update. * A summary over a summary still recomputes in dependency order. * * Every way out of the callback recomputes. Resolved: the callback's From 6b149c22661ebf14508f6a35c808686ae394b261 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:24:50 +0000 Subject: [PATCH 12/25] test(objectql): type the batch-scope pins' query options Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- packages/objectql/src/summary-rollup.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index b2810069cd5..513c1603e0c 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -876,7 +876,7 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { const { a, lines } = await seed(); const seen: unknown[] = []; engine.registerHook('beforeUpdate', async () => { - const parent = await engine.findOne('inv', { where: { id: a.id } } as any); + 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); @@ -954,8 +954,8 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { 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 } as any); - await engine.update('inv_line', { amount: 0 }, { where: { id: lines[3].id }, context: trxCtx } as any); + 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']); From e68802ff8ee75c8af220fceb16ca20c1aa381b95 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:32:49 +0000 Subject: [PATCH 13/25] test: resolve the door pins' protocol to source; pay the lint load at collection Claude-Session: https://claude.ai/code/session_01FEkQ5oe2Rer5VB78pdZqkr Co-Authored-By: Claude --- .../src/protocol.many-data-atomic.test.ts | 3 +++ packages/qa/dogfood/vitest.config.ts | 9 +++++++++ 2 files changed, 12 insertions(+) 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 3cd12cb1490..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'; 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 From df080eb673c70614dcfa3537e3b42281323c5275 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 19:56:11 +0000 Subject: [PATCH 14/25] docs(objectql): say the batch scope is ambient; pin a hook-issued insert into a second child The deferral scope covers every write made while the callback runs, including writes a hook issues on another object. The spec docblock and the changeset now say so, and an engine pin has a child-row hook insert into a second child object of the same parent: no parent is recomputed during the batch, and each child object recomputes once at the end. The batch-key docblock names which context wins when two writes share a user and tenant but not a transaction handle. Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 2 + .../src/engine-summaries-and-expansion.ts | 5 ++- packages/objectql/src/summary-rollup.test.ts | 38 +++++++++++++++++++ .../spec/src/contracts/objectql-engine.ts | 3 ++ 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md index 930c30f66d8..b82428cd4e3 100644 --- a/.changeset/rollup-batch-deferral-33795.md +++ b/.changeset/rollup-batch-deferral-33795.md @@ -18,4 +18,6 @@ Two things a caller can see: - During a bulk update, a parent's summary holds its value from before the batch until the batch ends, as it already did during a predicate update and in the stored row during a multi-row insert. A hook, or a validation rule, on a child row that reads its parent's summary while the batch runs reads that pre-batch value; before this change each row saw the recompute of the rows before it. (A multi-row insert's validation rules see the batch's earlier rows through an in-memory overlay; a bulk update has no such overlay.) - 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. +The scope is ambient, not tied to the object being updated: a write a hook issues while the batch runs, 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/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 6db38e8b232..1b97d5f59eb 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -107,7 +107,10 @@ export interface SummaryBatchScope { * (`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. + * operation its own copy of the caller's context. Two writes under the same + * user and tenant but a different transaction handle share one entry, and the + * first recorded row's context (and its transaction handle) is the one the + * recompute runs under. */ function summaryBatchKey(childObject: string, execCtx: ExecutionContext | undefined): string { const ctx = execCtx as { tenantId?: unknown; userId?: unknown } | undefined; diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 513c1603e0c..ad843707958 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -977,6 +977,44 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { 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 scope with no roll-up write runs nothing', async () => { const before = log.length; await engine.deferSummaryRecompute(async () => { await engine.insert('region', { name: 'R' }); }); diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index 49cd3f326e6..1ed8d1f9181 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -664,6 +664,9 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * audit and realtime run where they run outside a scope, so a rule or hook * that reads a parent's summary during the batch reads the value from * before the batch, as during a predicate update. + * The scope is ambient: it covers every write made while the callback + * runs, 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 summary over a summary still recomputes in dependency order. * * Every way out of the callback recomputes. Resolved: the callback's From 90871dea08f62a33b3ddc7f55d2daaebd108f7f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 19:56:12 +0000 Subject: [PATCH 15/25] docs(objectql): a joined scope inside its own transaction recomputes after that commit Contract review 6925110082 S3 and N1. The spec, facet and changeset said the recompute runs before the commit inside a transaction, and that a nested call joins the open scope. Together that was false for a call that joins from inside a transaction opened within the scope: its transaction commits first and its rows recompute when the outer scope ends. Say so. The spec docblock no longer states the statement cost as contract; the facet states it per child object, caller and id chunk. Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 2 +- .../objectql/src/engine-summaries-and-expansion.ts | 14 +++++++++++--- packages/spec/src/contracts/objectql-engine.ts | 13 ++++++++----- 3 files changed, 20 insertions(+), 9 deletions(-) diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md index b82428cd4e3..604e91ce1c9 100644 --- a/.changeset/rollup-batch-deferral-33795.md +++ b/.changeset/rollup-batch-deferral-33795.md @@ -9,7 +9,7 @@ feat(objectql): a bulk update recomputes its parents' roll-up summaries once, at Clause-②: yes (widening) Metadata-protocol: none -**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: 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. Inside a transaction the recompute runs before the commit. +**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: 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. When the call that opens the scope runs inside a transaction, the recompute runs before the commit; a call that joins an open scope from inside a transaction opened within it (no caller does this today) commits first and recomputes when the outer 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. diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 1b97d5f59eb..1b0100775ae 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -687,9 +687,11 @@ export class SummariesAndExpansionFacet { /** * [#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 — one grouped aggregate per summary - * field and one write per parent for the whole batch, instead of one - * recompute per row. Optional on `IObjectQLEngine` by ruling 6922040858; + * 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 @@ -716,6 +718,12 @@ export class SummariesAndExpansionFacet { * * Called inside a `transaction`, the recompute runs inside it, before * the commit, and a caller that lets the refusal escape rolls the batch back. + * That holds for the call that OPENS the scope. A call that joins an open + * scope from inside a transaction opened within that scope (an atomic batch + * reached from inside a non-atomic one) records into the outer scope: its + * transaction commits first, its rows recompute when the outer scope ends, + * and a failure then no longer rolls its batch back. No caller does this + * today. * A write recorded after the callback settled (work it started and did not * await) recomputes at once. */ diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index 1ed8d1f9181..a220c0247b2 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -653,8 +653,8 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * 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 — one grouped aggregate per summary field and one write per - * parent for the batch, where a per-row loop pays a recompute per row. + * 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 @@ -674,9 +674,12 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * 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. Inside a {@link transaction} the - * recompute runs before the commit, so a caller that lets the refusal - * escape rolls the batch back. + * callback's own error is rethrown. When the call that opens the scope + * runs inside a {@link transaction}, the recompute runs before the + * commit, so a caller that lets the refusal escape rolls the batch back. + * A call that joins an open scope from inside a transaction opened within + * that scope does not get this: its transaction commits first and its + * rows recompute when the outer scope ends. * * OPTIONAL by ruling: a caller probes * `typeof engine.deferSummaryRecompute === 'function'`, and without it From 14d8188e741a61c1b72452de086c8b73922d1e67 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 19:56:12 +0000 Subject: [PATCH 16/25] chore(changeset): declare the roll-up batch change semantic Contract review 6925110082 S1. A child-side rule or hook reads a different parent value during a bulk update, and the parent's authored hooks and validation run once per batch, not once per row: when an authored hook runs and what it reads move, as in 33760-async-hook-on-commit. objectql goes to minor; the Skills-docs line names the data skill's roll-up section as a follow-up owed after the maintainer's answer. Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md index 604e91ce1c9..6c4c54fd682 100644 --- a/.changeset/rollup-batch-deferral-33795.md +++ b/.changeset/rollup-batch-deferral-33795.md @@ -1,19 +1,20 @@ --- '@objectstack/spec': patch -'@objectstack/objectql': 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: none +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, or what a child-side rule or hook reads meanwhile; it moves after the maintainer answers that open question (option B would change what it says), as a governed skills-only change. **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: 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. When the call that opens the scope runs inside a transaction, the recompute runs before the commit; a call that joins an open scope from inside a transaction opened within it (no caller does this today) commits first and recomputes when the outer 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: +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`): - During a bulk update, a parent's summary holds its value from before the batch until the batch ends, as it already did during a predicate update and in the stored row during a multi-row insert. A hook, or a validation rule, on a child row that reads its parent's summary while the batch runs reads that pre-batch value; before this change each row saw the recompute of the rows before it. (A multi-row insert's validation rules see the batch's earlier rows through an in-memory overlay; a bulk update has no such overlay.) - 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. From 13e48a208c87fbf6779bc77a11bfc7edf2129f78 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 20:07:28 +0000 Subject: [PATCH 17/25] fix(objectql): defer only writes under the batch scope's own transaction L1 6927725912 M1. A sandboxed hook's ctx.api.transaction (the discrete begin/commit trio) opens its own transaction inside a non-atomic bulk update and commits it before the batch ends. Its writes were recorded, and the end-of-batch recompute then ran on the committed handle: the trio does not register in openedUnits, so buildDriverOptions kept it, and the recompute failed with ERR_SUMMARY_RECOMPUTE. The scope now records the transaction it was opened in, and only a write under that same transaction is deferred. A write under any other transaction recomputes at once, inside it, as outside any scope. This also removes the joined-scope exception from the docs: a nested atomic batch inside a non-atomic one recomputes before its own commit again. Pinned red-first with a driver that refuses a committed handle. Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 4 +- .../src/engine-summaries-and-expansion.ts | 51 ++++++++++++++----- packages/objectql/src/engine.ts | 2 + packages/objectql/src/summary-rollup.test.ts | 44 ++++++++++++++++ .../spec/src/contracts/objectql-engine.ts | 18 ++++--- 5 files changed, 95 insertions(+), 24 deletions(-) diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md index 6c4c54fd682..c9dfd5b0ac4 100644 --- a/.changeset/rollup-batch-deferral-33795.md +++ b/.changeset/rollup-batch-deferral-33795.md @@ -10,7 +10,7 @@ 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, or what a child-side rule or hook reads meanwhile; it moves after the maintainer answers that open question (option B would change what it says), as a governed skills-only change. -**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: 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. When the call that opens the scope runs inside a transaction, the recompute runs before the commit; a call that joins an open scope from inside a transaction opened within it (no caller does this today) commits first and recomputes when the outer scope ends. +**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. @@ -19,6 +19,6 @@ Two things a caller can see, which is why this declares `Metadata-protocol: sema - During a bulk update, a parent's summary holds its value from before the batch until the batch ends, as it already did during a predicate update and in the stored row during a multi-row insert. A hook, or a validation rule, on a child row that reads its parent's summary while the batch runs reads that pre-batch value; before this change each row saw the recompute of the rows before it. (A multi-row insert's validation rules see the batch's earlier rows through an in-memory overlay; a bulk update has no such overlay.) - 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. -The scope is ambient, not tied to the object being updated: a write a hook issues while the batch runs, 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. +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/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 1b0100775ae..56462ff84be 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -84,6 +84,14 @@ export const SUMMARY_RECOMPUTE_WRITE: unique symbol = Symbol.for('objectstack.ob * 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 @@ -107,16 +115,26 @@ export interface SummaryBatchScope { * (`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. Two writes under the same - * user and tenant but a different transaction handle share one entry, and the - * first recorded row's context (and its transaction handle) is the one the - * recompute runs under. + * 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; +} + /** * 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 @@ -135,6 +153,7 @@ 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']; @@ -142,6 +161,7 @@ export interface SummariesAndExpansionHost { summaryIndexByParent: ObjectQLClass['summaryIndexByParent']; summaryIndexRevision: ObjectQLClass['summaryIndexRevision']; readonly summaryRetryOptions: ObjectQLClass['summaryRetryOptions']; + readonly txStore: ObjectQLClass['txStore']; update: ObjectQLClass['update']; } @@ -521,7 +541,7 @@ 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 []; @@ -530,8 +550,11 @@ export class SummariesAndExpansionFacet { // 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. const scope = this.summaryBatchStore.getStore(); - if (scope && !scope.closed) { + if (scope && !scope.closed && writeTransactionOf(this, execCtx) === scope.transaction) { const fkFields = [...new Set(descriptors.map((d) => d.fkField))]; const keysOf = (r: unknown): Record => { const keys: Record = {}; @@ -718,21 +741,21 @@ export class SummariesAndExpansionFacet { * * Called inside a `transaction`, the recompute runs inside it, before * the commit, and a caller that lets the refusal escape rolls the batch back. - * That holds for the call that OPENS the scope. A call that joins an open - * scope from inside a transaction opened within that scope (an atomic batch - * reached from inside a non-atomic one) records into the outer scope: its - * transaction commits first, its rows recompute when the outer scope ends, - * and a failure then no longer rolls its batch back. No caller does this - * today. + * 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 { + 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, entries: new Map() }; + 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 diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 4a883fd6486..72b974e39b8 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -6156,6 +6156,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/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index ad843707958..162687b4a08 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -1015,6 +1015,50 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { 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 }); + }); + 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' }); }); diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index a220c0247b2..f736bfbe467 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -665,8 +665,13 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * that reads a parent's summary during the batch reads the value from * before the batch, as during a predicate update. * The scope is ambient: it covers every write made while the callback - * runs, 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. + * 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 @@ -674,12 +679,9 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * 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. When the call that opens the scope - * runs inside a {@link transaction}, the recompute runs before the - * commit, so a caller that lets the refusal escape rolls the batch back. - * A call that joins an open scope from inside a transaction opened within - * that scope does not get this: its transaction commits first and its - * rows recompute when the outer scope ends. + * 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 From a35af28b6307166272d3dbdee224901c088b2314 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 20:55:34 +0000 Subject: [PATCH 18/25] feat(objectql): a roll-up a rule reads is not deferred in a batch scope Ruling 6928862195 (B). Inside deferSummaryRecompute, a recompute is recorded only when no rule reads any of the child object's roll-ups. "Read by a rule" is judged on the summary field read: a validation rule of any object reading it one hop through a reference (the hops collectPredicateRelationships hydrates), or a detail object's requiredWhen / readonlyWhen reading it on parent, by field name. The set is built from the registry and kept per summary index, so it is rebuilt whenever the index is. A parent. predicate reading a field that is not a summary (the showcase invoice line's parent.status) keeps the deferral. Hooks and flow steps stay outside the test and read the pre-batch value, as during a multi-row insert. The spec, facet and door docblocks, the changeset and fields.mdx now say so, and no longer say a rule reads the pre-batch value "as it already does for createMany". Door pins (count, avg, min, max; atomic and continueOnError; SQLite and PostgreSQL) were red first without the test (16 failed) and equal one-by-one with it. Engine pins cover both classes, a rule on another object, and the non-summary parent. predicate. Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 4 +- content/docs/data-modeling/fields.mdx | 11 ++ packages/metadata-protocol/src/protocol.ts | 13 +- .../src/engine-summaries-and-expansion.ts | 47 ++++-- packages/objectql/src/summary-rollup.test.ts | 51 +++++++ packages/objectql/src/summary-rule-reads.ts | 98 +++++++++++++ .../rollup-grouped-recompute-33795.test.ts | 135 +++++++++++++++++- .../spec/src/contracts/objectql-engine.ts | 11 +- 8 files changed, 350 insertions(+), 20 deletions(-) create mode 100644 packages/objectql/src/summary-rule-reads.ts diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md index c9dfd5b0ac4..fd118852525 100644 --- a/.changeset/rollup-batch-deferral-33795.md +++ b/.changeset/rollup-batch-deferral-33795.md @@ -8,7 +8,7 @@ feat(objectql): a bulk update recomputes its parents' roll-up summaries once, at 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, or what a child-side rule or hook reads meanwhile; it moves after the maintainer answers that open question (option B would change what it says), as a governed skills-only change. +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. @@ -16,7 +16,7 @@ Skills-docs: follow-up owed — `skills/objectstack-data/rules/relationships.md` 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`): -- During a bulk update, a parent's summary holds its value from before the batch until the batch ends, as it already did during a predicate update and in the stored row during a multi-row insert. A hook, or a validation rule, on a child row that reads its parent's summary while the batch runs reads that pre-batch value; before this change each row saw the recompute of the rows before it. (A multi-row insert's validation rules see the batch's earlier rows through an in-memory overlay; a bulk update has no such overlay.) +- 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, or a detail object's `requiredWhen` / `readonlyWhen` that reads it on `parent`, makes that roll-up 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). A `parent.` predicate that reads a field that is not a summary (`parent.status == 'paid'`) does not turn the deferral off. - 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. 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. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index c2e66ffeb69..f3d7676ed90 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -406,6 +406,17 @@ 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, except a summary +that a rule reads: a validation rule of any object reading it one hop through a +reference, or a detail object's `requiredWhen` / `readonlyWhen` reading it on +`parent`. That summary recomputes after each row, so each row's rules 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 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/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index 568bc7c0f3a..82a30c838f1 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -5723,9 +5723,10 @@ export class ObjectStackProtocolImplementation implements * [#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. During the batch a parent's - * summary holds its value from before the batch. The other operations - * keep their per-row recompute. + * 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; @@ -5984,8 +5985,10 @@ export class ObjectStackProtocolImplementation implements * `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. During the batch a parent's summary holds its value - * from before the batch. Atomic: the recompute runs inside the transaction, + * 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. diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 56462ff84be..98c42470c9b 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -45,6 +45,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import { withTransientRetry } from '@objectstack/core'; 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'; @@ -135,6 +136,29 @@ function writeTransactionOf(host: Pick>(); + +/** + * [#33795, ruling 6928862195 B] Does a rule read any of `descriptors`' + * summary fields? 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()); + 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 @@ -541,7 +565,7 @@ 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 []; @@ -552,9 +576,12 @@ export class SummariesAndExpansionFacet { // 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. + // 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 reads it as + // one-by-one updates would. const scope = this.summaryBatchStore.getStore(); - if (scope && !scope.closed && writeTransactionOf(this, execCtx) === scope.transaction) { + 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 = {}; @@ -722,11 +749,13 @@ export class SummariesAndExpansionFacet { * 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. So a rule or hook that - * reads a parent's summary during the batch reads the value from before - * the batch, as it already does during a predicate update. (A multi-row - * insert's validation rules see the batch's earlier rows through an - * in-memory overlay, `summary-batch-accumulation.ts`; a scope has none.) + * 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 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: * @@ -750,7 +779,7 @@ export class SummariesAndExpansionFacet { * 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 { + 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(); diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 162687b4a08..a66f1fe6b93 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -1059,6 +1059,57 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { 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 }); + }); + }); + 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' }); }); diff --git a/packages/objectql/src/summary-rule-reads.ts b/packages/objectql/src/summary-rule-reads.ts new file mode 100644 index 00000000000..eb17666a401 --- /dev/null +++ b/packages/objectql/src/summary-rule-reads.ts @@ -0,0 +1,98 @@ +// 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 two 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. + * + * ⛔ 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 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}`; +} + +/** + * Every `.` a rule of `objects` reads on ANOTHER row: through a + * reference, one hop (class i), or on the master-detail header by a + * field-level predicate (class ii). A field that is not a summary may be in + * the set; the caller asks only about summary fields. + */ +export function summaryFieldsReadByRules(objects: Iterable): Set { + const out = new Set(); + for (const candidate of objects) { + const schema = candidate as { fields?: Record | null | undefined>; validations?: unknown[] } | null | undefined; + const fields = schema?.fields; + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) continue; + // (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 analysis = analyzeRelationshipTraversals(source, PARENT_ROOT); + if (!analysis) continue; + const read = [...analysis.bareFields, ...analysis.traversals.keys()]; + 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)); + } + } + } + return out; +} 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 b3656e29e36..75292925a0a 100644 --- a/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts +++ b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts @@ -105,7 +105,56 @@ 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] }], + })), +]; + +const OBJECTS = [...rollupPair(0), ...rollupPair(1), ...rollupPair(2), ...KIND_OBJECTS, ...RULE_OBJECTS]; const engines: ObjectQL[] = []; afterEach(async () => { @@ -346,6 +395,90 @@ describe.each(CELLS)('roll-up batch deferral through the bulk update door (#3379 }); }); +/** + * [#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); + }); + } +}); + /** 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/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index f736bfbe467..aee7f43b7a8 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -661,9 +661,14 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * 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, so a rule or hook - * that reads a parent's summary during the batch reads the value from - * before the batch, as during a predicate update. + * 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, or a detail object's + * `requiredWhen` / `readonlyWhen` reading it on `parent`, makes its + * recompute run after each row, so a rule's answer during the batch is + * the answer 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 From 0868390fa3af91c919591ffa539c411b5d8627fa Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 21:15:21 +0000 Subject: [PATCH 19/25] test(objectql): give the rule-read test's referenceTargetOf its READERS row The federated injected-column census scans every seam use in the engine source; summaryFieldsReadByRules names the object a validation rule's one hop reaches from the declaration and reads no row (caller-predicate). Co-Authored-By: Claude --- .../objectql/src/federated-injected-column-readers.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index f5c9639bf9c..357e4277d40 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -357,6 +357,12 @@ 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", + }, 'engine-summaries-and-expansion.ts#buildSummaryIndex :: referenceCarrierOf()': { disposition: 'author-declared', why: From 056c5d5fcf3b0d38ad2769b3b7ccdefdaae55c9c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:03:50 +0000 Subject: [PATCH 20/25] fix(objectql): a parent's own rule, a computed field and a summary chain count as reading a roll-up L1 6930506752 M1 and contract review 6930582939 M1, both inside ruling 6928862195 (B). The batch scope's rule-read test missed three ways a rule reads a roll-up, so the roll-up stayed deferred and the rule judged only the end of the batch where one-by-one updates judge every step: - (iii) a rule of the summary's own object reading it on record or previous (validation rules, the field a state_machine / format / json_schema rule names, and field-level requiredWhen / readonlyWhen): the recompute's own write is an update of that row, judged by them; - a formula or stored computed field calculated from the summary, read by a rule of any class: the read set is closed over what a computed field's expression reads, on its row and one hop through a reference; - a summary over a summary: a summary a rule reads makes the field it aggregates read, and a filtered one every summary of its child object. Door pins through updateManyData compare each case with today's per-row path (the member hidden), atomic and continueOnError: the parent capping its own count, the parent capping a stored computed field over it, a contact rule reading the supplier formula one hop, and a line readonlyWhen reading a header computed field on parent. fields.mdx now says every roll-up of that child object recomputes after each row. Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 4 +- content/docs/data-modeling/fields.mdx | 18 +- .../src/engine-summaries-and-expansion.ts | 17 +- packages/objectql/src/summary-rollup.test.ts | 80 ++++++++ packages/objectql/src/summary-rule-reads.ts | 145 ++++++++++++- .../rollup-grouped-recompute-33795.test.ts | 191 +++++++++++++++++- .../spec/src/contracts/objectql-engine.ts | 11 +- 7 files changed, 435 insertions(+), 31 deletions(-) diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md index fd118852525..5b2469ba2c9 100644 --- a/.changeset/rollup-batch-deferral-33795.md +++ b/.changeset/rollup-batch-deferral-33795.md @@ -16,8 +16,8 @@ Skills-docs: follow-up owed — `skills/objectstack-data/rules/relationships.md` 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, or a detail object's `requiredWhen` / `readonlyWhen` that reads it on `parent`, makes that roll-up 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). A `parent.` predicate that reads a field that is not a summary (`parent.status == 'paid'`) does not turn the deferral off. -- 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. +- 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), 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. +- 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. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index f3d7676ed90..c0c235911e0 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -408,12 +408,18 @@ 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, except a summary -that a rule reads: a validation rule of any object reading it one hop through a -reference, or a detail object's `requiredWhen` / `readonlyWhen` reading it on -`parent`. That summary recomputes after each row, so each row's rules 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 does not count. +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`). +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. 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. diff --git a/packages/objectql/src/engine-summaries-and-expansion.ts b/packages/objectql/src/engine-summaries-and-expansion.ts index 98c42470c9b..a6fbb7129cd 100644 --- a/packages/objectql/src/engine-summaries-and-expansion.ts +++ b/packages/objectql/src/engine-summaries-and-expansion.ts @@ -145,15 +145,17 @@ const ruleReadsByIndex = new WeakMap>(); /** * [#33795, ruling 6928862195 B] Does a rule read any of `descriptors`' - * summary fields? 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 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()); + 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))); @@ -578,8 +580,9 @@ export class SummariesAndExpansionFacet { // 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 reads it as - // one-by-one updates would. + // 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))]; @@ -752,8 +755,8 @@ export class SummariesAndExpansionFacet { * 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 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 + * 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. * diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index a66f1fe6b93..235c3b2911c 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -1108,6 +1108,86 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { 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('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 () => { diff --git a/packages/objectql/src/summary-rule-reads.ts b/packages/objectql/src/summary-rule-reads.ts index eb17666a401..acd64d1fe95 100644 --- a/packages/objectql/src/summary-rule-reads.ts +++ b/packages/objectql/src/summary-rule-reads.ts @@ -14,7 +14,7 @@ * 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 two classes, judged on the summary field that is read, + * "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 @@ -23,7 +23,19 @@ * ({@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. + * 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. + * + * 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 @@ -43,6 +55,36 @@ const PARENT_ROOT = 'parent'; /** The field-level predicates that may read `parent` (#4889, #4977). */ const PARENT_PREDICATE_SLOTS = ['requiredWhen', 'readonlyWhen'] as const; +/** 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; @@ -57,18 +99,82 @@ 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[] } | 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; +} + /** - * Every `.` a rule of `objects` reads on ANOTHER row: through a - * reference, one hop (class i), or on the master-detail header by a - * field-level predicate (class ii). A field that is not a summary may be in - * the set; the caller asks only about summary fields. + * 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. */ -export function summaryFieldsReadByRules(objects: Iterable): Set { +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 { fields?: Record | null | undefined>; validations?: unknown[] } | null | undefined; + 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); + } + } + if (name) for (const field of own) out.add(ruleReadKey(name, 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); @@ -82,9 +188,7 @@ export function summaryFieldsReadByRules(objects: Iterable): Set): 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/test/rollup-grouped-recompute-33795.test.ts b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts index 75292925a0a..1a83ef100e0 100644 --- a/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts +++ b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts @@ -154,7 +154,103 @@ const RULE_OBJECTS = [ })), ]; -const OBJECTS = [...rollupPair(0), ...rollupPair(1), ...rollupPair(2), ...KIND_OBJECTS, ...RULE_OBJECTS]; +/** + * [#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; `viaComputed` caps a stored computed field + * over the count (`room = 2 - line_count`, recomputed on the recompute's own + * write) instead of the count itself. + */ +function capObjects(parent: string, line: string, viaComputed: boolean) { + return [ + { + name: parent, + label: viaComputed ? 'Capped invoice (computed)' : 'Capped invoice', + 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' } } : {}), + }, + validations: [{ + 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: viaComputed ? 'Capped invoice line (computed)' : 'Capped invoice line', + 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' }; + +/** + * [#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, false), ...capObjects(CCAP.parent, CCAP.line, true), ...FORMULA_OBJECTS, +]; const engines: ObjectQL[] = []; afterEach(async () => { @@ -479,6 +575,99 @@ describe.each(CELLS)('a roll-up a rule reads is not deferred (#33795 B): $name', } }); +/** 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 })), + }), + }; +}; + +/** + * [#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; +const PARITY_CASES: Array<{ name: string; make: ParityCase; live: (answer: any, state: any) => 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 }, + { 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 }, +]; + +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, or (a lock) drops the second note. + if ('atomic' in options) 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/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index aee7f43b7a8..2a8ff7f0d04 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -663,10 +663,13 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * 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, or a detail object's - * `requiredWhen` / `readonlyWhen` reading it on `parent`, makes its - * recompute run after each row, so a rule's answer during the batch is - * the answer one-by-one writes give. A hook or flow step that reads a + * object reading it one hop through a reference, a detail object's + * `requiredWhen` / `readonlyWhen` reading it on `parent`, or a rule of the + * summary's own object reading it on its own row (directly, through a + * formula or stored computed field calculated from it, or up a chain of + * summaries), makes the recompute of every roll-up of the child object + * written run after each row, so a rule's answer during the batch is the + * answer 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 From 24ad0728c26fdb5ed3b91343a39e3e305bc475d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:04:34 +0000 Subject: [PATCH 21/25] test(core): classify the batch scope's rule-read test in the second-object exposure pin summary-rule-reads.ts calls the reference-target arbiter to name the object a rule's or a computed field's one hop reaches, from declarations only; it reads no record and serves nothing of the target. Co-Authored-By: Claude --- .../src/security/second-object-read-exposure.pin.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) 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 42e0280147d..6327fd48a7a 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 @@ -242,6 +242,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', From 7c80b9dbfda448894d46c6aeb275e9c0bfb90c0f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 22:23:51 +0000 Subject: [PATCH 22/25] test(objectql): give the computed-field hop's referenceTargetOf its READERS row keysReadFrom names the object a computed field's one-hop expression reaches, from the declaration, and reads no row (caller-predicate). Co-Authored-By: Claude --- .../objectql/src/federated-injected-column-readers.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/objectql/src/federated-injected-column-readers.test.ts b/packages/objectql/src/federated-injected-column-readers.test.ts index 4e1d0567137..c19c8b41f78 100644 --- a/packages/objectql/src/federated-injected-column-readers.test.ts +++ b/packages/objectql/src/federated-injected-column-readers.test.ts @@ -374,6 +374,10 @@ const READERS: Record = { 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: From 8191a5d5b0678fdd84874c5bda06bede3d2f73b6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 23:15:54 +0000 Subject: [PATCH 23/25] fix(objectql): a declared bound on a stored value and a stored one-hop read count as reading a roll-up Contract review 6932181981 M2 and S4, inside ruling 6928862195 (B). - M2: the recompute's own write of the parent computes its stored computed fields and judges their declared bounds (validateRecord, a unique index). A bound (min, max, minLength, maxLength, pattern, unique, required) on the summary itself or on a stored computed field of its object now counts as a read, and the closure follows the field to the summary it is calculated from. - S4: a stored computed field (an expression on a field that is not a formula) reading another row one hop stores what it read at its own write, so its one-hop reads seed the set too. A formula does not: it is computed when read. Door pins against today's per-row path: the cap spelled as min 0 on the parent's stored room, and a line's stored rank = owner.flagged_count. fields.mdx, the spec docblock and the changeset say so; the docblock's list now reads for all three classes (N4). Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 2 +- content/docs/data-modeling/fields.mdx | 12 ++- packages/objectql/src/summary-rollup.test.ts | 25 ++++++ packages/objectql/src/summary-rule-reads.ts | 42 +++++++++- .../rollup-grouped-recompute-33795.test.ts | 81 +++++++++++++++---- .../spec/src/contracts/objectql-engine.ts | 18 +++-- 6 files changed, 153 insertions(+), 27 deletions(-) diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md index 5b2469ba2c9..c6e20f3cae7 100644 --- a/.changeset/rollup-batch-deferral-33795.md +++ b/.changeset/rollup-batch-deferral-33795.md @@ -16,7 +16,7 @@ Skills-docs: follow-up owed — `skills/objectstack-data/rules/relationships.md` 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), 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 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), and a declared bound (`min`, `max`, `unique`, …) on the summary or on a stored computed field of its object calculated from it, 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. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index c0c235911e0..130a19c0c02 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -412,10 +412,14 @@ 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`). -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. Then every roll-up of that child object +object itself reading its own summary (a cap such as `record.line_count <= 5`, +or a declared bound such as `min` / `max` / `unique` on the summary or on a +stored computed field of the parent calculated from it). 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 diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 235c3b2911c..2f440960b8c 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -1171,6 +1171,31 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { 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('a stored computed field of the parent with no bound and no rule reading it keeps the deferral', async () => { + invWith({ fields: { doubled: { type: 'number', expression: 'record.line_total * 2' } } }); + 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'" }] }); diff --git a/packages/objectql/src/summary-rule-reads.ts b/packages/objectql/src/summary-rule-reads.ts index acd64d1fe95..e24e8320bcb 100644 --- a/packages/objectql/src/summary-rule-reads.ts +++ b/packages/objectql/src/summary-rule-reads.ts @@ -30,7 +30,15 @@ * `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. + * deferred they would judge only the last. A declared bound (`min`, `max`, + * `minLength`, `maxLength`, `pattern`, `unique`, `required`) on a value that + * write stores, the summary itself or a stored computed field, is judged the + * same way and counts as a rule reading that value. + * + * 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 @@ -55,6 +63,13 @@ 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 a stored value (`validateRecord`'s + * `min_value` / `max_value` / `min_length` / `max_length` / pattern and + * `required` checks, and a unique index). + */ +const WRITE_BOUND_KEYS = ['min', 'max', 'minLength', 'maxLength', 'pattern', 'regex', 'unique', 'required'] as const; + /** 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; @@ -174,7 +189,32 @@ export function summaryFieldsReadByRules(objects: Iterable, links: Iter for (const root of OWN_ROW_ROOTS) for (const field of fieldsReadOn(source, root)) own.add(field); } } + // (iii) A declared bound on a field the recompute's own write stores: the + // summary itself, or a stored computed field (an `expression` on a field + // that is not a `formula`). The write computes it onto the payload and + // judges it (`validateRecord`, a unique index), so one by one every + // intermediate value is judged; the closure below adds what it reads. + for (const [field, def] of Object.entries(fields)) { + if (!def || typeof def !== 'object') continue; + const stored = def.type === 'summary' || (def.type !== 'formula' && celSource(def.expression) !== undefined); + if (stored && WRITE_BOUND_KEYS.some((key) => def[key] !== undefined && def[key] !== null && def[key] !== false)) 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); 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 1a83ef100e0..f485119d183 100644 --- a/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts +++ b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts @@ -162,28 +162,30 @@ const RULE_OBJECTS = [ */ const CAP_TEXT = 'An invoice holds at most two lines.'; /** - * The capped invoice and its lines; `viaComputed` caps a stored computed field - * over the count (`room = 2 - line_count`, recomputed on the recompute's own - * write) instead of the count itself. + * 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. */ -function capObjects(parent: string, line: string, viaComputed: boolean) { +function capObjects(parent: string, line: string, mode: 'rule' | 'computed' | 'bound') { + const viaComputed = mode !== 'rule'; return [ { name: parent, - label: viaComputed ? 'Capped invoice (computed)' : 'Capped invoice', + 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' } } : {}), + ...(viaComputed ? { room: { type: 'number', label: 'Room', expression: '2 - record.line_count', ...(mode === 'bound' ? { min: 0 } : {}) } } : {}), }, - validations: [{ + validations: mode === 'bound' ? [] : [{ 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: viaComputed ? 'Capped invoice line (computed)' : 'Capped invoice line', + label: `Capped invoice line (${mode})`, fields: { name: { type: 'text', label: 'Name' }, invoice: { type: 'lookup', label: 'Invoice', reference: parent }, @@ -193,6 +195,35 @@ function capObjects(parent: string, line: string, viaComputed: boolean) { } 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' }; + +/** + * [#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 @@ -249,7 +280,8 @@ const FORMULA_OBJECTS = [ const OBJECTS = [ ...rollupPair(0), ...rollupPair(1), ...rollupPair(2), ...KIND_OBJECTS, ...RULE_OBJECTS, - ...capObjects(CAP.parent, CAP.line, false), ...capObjects(CCAP.parent, CCAP.line, true), ...FORMULA_OBJECTS, + ...capObjects(CAP.parent, CAP.line, 'rule'), ...capObjects(CCAP.parent, CCAP.line, 'computed'), ...capObjects(BCAP.parent, BCAP.line, 'bound'), + ...FORMULA_OBJECTS, ...SEEN_OBJECTS, ]; const engines: ObjectQL[] = []; @@ -623,6 +655,20 @@ const roomCase: ParityCase = async (engine, tag) => { }; }; +/** 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 @@ -635,14 +681,19 @@ const roomCase: ParityCase = async (engine, tag) => { * stored rows alike, atomic and `continueOnError`. */ const refused = (answer: any): boolean => answer.success === false; -const PARITY_CASES: Array<{ name: string; make: ParityCase; live: (answer: any, state: any) => boolean }> = [ +/** `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 }, - { 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 }, + { 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 }, + // 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 }) => { @@ -659,8 +710,10 @@ describe.each(CELLS)('a roll-up a rule reads through its own row or a formula is 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, or (a lock) drops the second note. - if ('atomic' in options) expect(parity.live(expected, await today.state())).toBe(true); + // 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()); }); diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index 2a8ff7f0d04..8ef0ecba4b1 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -662,14 +662,18 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * * 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 + * 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`, or a rule of the - * summary's own object reading it on its own row (directly, through a - * formula or stored computed field calculated from it, or up a chain of - * summaries), makes the recompute of every roll-up of the child object - * written run after each row, so a rule's answer during the batch is the - * answer one-by-one writes give. A hook or flow step that reads a + * `requiredWhen` / `readonlyWhen` reading it on `parent`, a rule of the + * summary's own object reading it on its own row, or a declared bound + * (`min`, `max`, `unique`, …) on the summary or on a stored computed field + * of that object calculated from it, 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 From 7a34cfc903c496ca98e1bdc0372197b262a18ebd Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:08:06 +0000 Subject: [PATCH 24/25] test(objectql): pins for a summary precision, a unique index naming it, and an unbounded stored computed field Co-Authored-By: Claude --- packages/objectql/src/summary-rollup.test.ts | 40 +++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/packages/objectql/src/summary-rollup.test.ts b/packages/objectql/src/summary-rollup.test.ts index 2f440960b8c..f12787bed00 100644 --- a/packages/objectql/src/summary-rollup.test.ts +++ b/packages/objectql/src/summary-rollup.test.ts @@ -1181,8 +1181,46 @@ describe('[#33795] deferSummaryRecompute: one roll-up batch', () => { expect(await batchOfSix()).toEqual({ during: 6, after: 0 }); }); - it('a stored computed field of the parent with no bound and no rule reading it keeps the deferral', async () => { + 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 }); }); From 584fd7dface2abb758ffcaf2291191ea12f94a56 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 00:10:21 +0000 Subject: [PATCH 25/25] fix(objectql): every stored computed field over a roll-up, and a summary's precision or unique index, count as reading it The recompute's own write judges every value it stores against its declaration, so a stored computed field calculated from the summary is judged at each intermediate value one by one, bound or not (an option list, a value domain, a number that is not finite). The summary itself counts when it declares a bound, now including `precision`, or when a declared unique index names it. Co-Authored-By: Claude --- .changeset/rollup-batch-deferral-33795.md | 2 +- content/docs/data-modeling/fields.mdx | 6 +- packages/objectql/src/summary-rule-reads.ts | 59 ++++++++++++++----- .../rollup-grouped-recompute-33795.test.ts | 21 +++++-- .../spec/src/contracts/objectql-engine.ts | 8 ++- 5 files changed, 70 insertions(+), 26 deletions(-) diff --git a/.changeset/rollup-batch-deferral-33795.md b/.changeset/rollup-batch-deferral-33795.md index c6e20f3cae7..33fc2f95257 100644 --- a/.changeset/rollup-batch-deferral-33795.md +++ b/.changeset/rollup-batch-deferral-33795.md @@ -16,7 +16,7 @@ Skills-docs: follow-up owed — `skills/objectstack-data/rules/relationships.md` 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), and a declared bound (`min`, `max`, `unique`, …) on the summary or on a stored computed field of its object calculated from it, 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. +- 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. diff --git a/content/docs/data-modeling/fields.mdx b/content/docs/data-modeling/fields.mdx index 130a19c0c02..571a1556abe 100644 --- a/content/docs/data-modeling/fields.mdx +++ b/content/docs/data-modeling/fields.mdx @@ -413,8 +413,10 @@ 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` / `unique` on the summary or on a -stored computed field of the parent calculated from it). A rule that reads a +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 diff --git a/packages/objectql/src/summary-rule-reads.ts b/packages/objectql/src/summary-rule-reads.ts index e24e8320bcb..c0a2f92a1e6 100644 --- a/packages/objectql/src/summary-rule-reads.ts +++ b/packages/objectql/src/summary-rule-reads.ts @@ -30,10 +30,14 @@ * `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. A declared bound (`min`, `max`, - * `minLength`, `maxLength`, `pattern`, `unique`, `required`) on a value that - * write stores, the summary itself or a stored computed field, is judged the - * same way and counts as a rule reading that value. + * 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 @@ -64,11 +68,26 @@ const PARENT_ROOT = 'parent'; const PARENT_PREDICATE_SLOTS = ['requiredWhen', 'readonlyWhen'] as const; /** - * The declared bounds a write judges on a stored value (`validateRecord`'s - * `min_value` / `max_value` / `min_length` / `max_length` / pattern and - * `required` checks, and a unique index). + * 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 WRITE_BOUND_KEYS = ['min', 'max', 'minLength', 'maxLength', 'pattern', 'regex', 'unique', 'required'] as const; +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; @@ -115,7 +134,7 @@ export function ruleReadKey(object: string, field: string): string { } /** An object definition as this module reads it. */ -type ObjectDef = { name?: unknown; fields?: Record | null | undefined>; validations?: unknown[] } | null | undefined; +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 { @@ -189,15 +208,23 @@ export function summaryFieldsReadByRules(objects: Iterable, links: Iter for (const root of OWN_ROW_ROOTS) for (const field of fieldsReadOn(source, root)) own.add(field); } } - // (iii) A declared bound on a field the recompute's own write stores: the - // summary itself, or a stored computed field (an `expression` on a field - // that is not a `formula`). The write computes it onto the payload and - // judges it (`validateRecord`, a unique index), so one by one every - // intermediate value is judged; the closure below adds what it reads. + // (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; - const stored = def.type === 'summary' || (def.type !== 'formula' && celSource(def.expression) !== undefined); - if (stored && WRITE_BOUND_KEYS.some((key) => def[key] !== undefined && def[key] !== null && def[key] !== false)) own.add(field); + 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`) 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 f485119d183..399b34526e4 100644 --- a/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts +++ b/packages/qa/dogfood/test/rollup-grouped-recompute-33795.test.ts @@ -165,10 +165,12 @@ 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. + * 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') { - const viaComputed = mode !== 'rule'; +function capObjects(parent: string, line: string, mode: 'rule' | 'computed' | 'bound' | 'option') { + const viaComputed = mode === 'computed' || mode === 'bound'; return [ { name: parent, @@ -177,8 +179,15 @@ function capObjects(parent: string, line: string, mode: 'rule' | 'computed' | 'b 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' ? [] : [{ + 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', }], @@ -196,6 +205,7 @@ function capObjects(parent: string, line: string, mode: 'rule' | 'computed' | 'b 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 @@ -281,6 +291,7 @@ const FORMULA_OBJECTS = [ 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, ]; @@ -692,6 +703,8 @@ const PARITY_CASES: Array<{ name: string; make: ParityCase; live: (answer: any, { 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 }, ]; diff --git a/packages/spec/src/contracts/objectql-engine.ts b/packages/spec/src/contracts/objectql-engine.ts index 8ef0ecba4b1..c535b75e380 100644 --- a/packages/spec/src/contracts/objectql-engine.ts +++ b/packages/spec/src/contracts/objectql-engine.ts @@ -665,9 +665,11 @@ export interface IObjectQLEngine extends IDataEngine, QueryEvaluationGate { * 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, or a declared bound - * (`min`, `max`, `unique`, …) on the summary or on a stored computed field - * of that object calculated from it, each counts, whether it reads 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