From 51f0f6780e9ffe1a086c862de97a1187e2edc3c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 14:56:13 +0000 Subject: [PATCH 1/4] 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 2/4] 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 3/4] 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 1789606ebfb6e2eab004baf912a1a11ef6cb490f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 17:17:58 +0000 Subject: [PATCH 4/4] test(objectql): pin a record-currency roll-up through the grouped recompute aggregate A createMany of lines across a USD and a EUR invoice now asks one aggregate grouped by the master_detail; the pin checks each subtotal equals the one-line-at-a-time value, no recompute failure is recorded, and the same grouped statement asked without the roll-up channel is still refused. The ROLLUP_AGGREGATE_OPTION docblock names aggregateSummaryValues as its second setter. Co-Authored-By: Claude --- .../src/record-currency-aggregate-door.ts | 7 +++- .../src/record-currency-guards.test.ts | 42 ++++++++++++++++++- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/packages/objectql/src/record-currency-aggregate-door.ts b/packages/objectql/src/record-currency-aggregate-door.ts index a193269eb91..302544e9241 100644 --- a/packages/objectql/src/record-currency-aggregate-door.ts +++ b/packages/objectql/src/record-currency-aggregate-door.ts @@ -59,7 +59,8 @@ * The roll-up's own recompute asks the aggregate through the engine, and this * door would refuse it as ungrouped. It carries the module-private * {@link ROLLUP_AGGREGATE_OPTION}, naming the `master_detail` it totals one - * parent's rows through (`aggregateSummaryValue`, `summary-aggregate.ts`); an + * parent's rows through (`aggregateSummaryValue`, `summary-aggregate.ts`; or + * several parents' rows grouped by that field, `aggregateSummaryValues`); an * amount following its parent through that field is then one currency. No * door a caller reaches can set it. * @@ -93,7 +94,9 @@ import { recordCurrencyFieldOf, recordCurrencyPathOf, type RecordCurrencyPath } * [ADR-0144 D6, amended] The engine's own channel for a roll-up's aggregate: * the `master_detail` field it totals one parent's child rows through. A * module-private symbol on the aggregate's options, so no options object a - * door builds can carry it. Set only by `aggregateSummaryValue`. + * door builds can carry it. Set only by `aggregateSummaryValue` (one parent's + * rows) and `aggregateSummaryValues` (grouped by that same field, one parent + * per group), both in `summary-aggregate.ts`. */ export const ROLLUP_AGGREGATE_OPTION: unique symbol = Symbol('objectstack.objectql.rollupAggregateVia'); diff --git a/packages/objectql/src/record-currency-guards.test.ts b/packages/objectql/src/record-currency-guards.test.ts index 171c38cee73..6446b8e2642 100644 --- a/packages/objectql/src/record-currency-guards.test.ts +++ b/packages/objectql/src/record-currency-guards.test.ts @@ -143,7 +143,7 @@ async function bootEngine() { const d = makeDriver(); engine.registerDriver(d.driver, true); await engine.init(); - return { engine, storeFor: d.storeFor }; + return { engine, storeFor: d.storeFor, driver: d.driver }; } describe('a record-mode amount is stored with its currency code (ERR_CURRENCY_CODE_REQUIRED)', () => { @@ -554,6 +554,46 @@ describe('a summary rolled up through the master_detail its children follow regi } }); + it('[#33795] a batch of lines across two parents totals each in one grouped aggregate, as one line at a time does', async () => { + const LINES = [ + { title: 'u1', invoice: 'inv_usd', amount: 100 }, + { title: 'e1', invoice: 'inv_eur', amount: 70 }, + { title: 'u2', invoice: 'inv_usd', amount: 50 }, + { title: 'e2', invoice: 'inv_eur', amount: 30 }, + ]; + // One line at a time: each recompute asks the one-parent aggregate. + const single = await bootFollowing(); + for (const line of LINES) await single.engine.insert('pp_line', line); + // One batch: the recompute asks ONE aggregate grouped by the master_detail + // over both parents. The door admits it on the roll-up's own channel only: + // had it refused, the insert would answer ERR_SUMMARY_RECOMPUTE and both + // subtotals would stay stale. + const batch = await bootFollowing(); + const lineReads: unknown[] = []; + const find = batch.driver.find; + batch.driver.find = async (object: string, ast: any) => { + if (object === 'pp_line') lineReads.push(ast?.where); + return find.call(batch.driver, object, ast); + }; + await batch.engine.insert('pp_line', LINES); + const grouped = lineReads.filter((where) => JSON.stringify(where).includes('$in')); + expect(grouped).toHaveLength(1); + expect(JSON.stringify(grouped[0])).toContain('"invoice":{"$in":["inv_usd","inv_eur"]}'); + for (const id of ['inv_usd', 'inv_eur']) { + expect(batch.storeFor('pp_invoice').get(id).subtotal, id).toBe(single.storeFor('pp_invoice').get(id).subtotal); + } + expect(batch.storeFor('pp_invoice').get('inv_usd').subtotal).toBe(150); + expect(batch.storeFor('pp_invoice').get('inv_eur').subtotal).toBe(100); + // The same grouped statement asked by a caller, without the channel, is + // still refused: the grouping does not make it one currency, the channel does. + const err = await refusalOf(batch.engine.aggregate('pp_line', aggregateQuery({ + where: { invoice: { $in: ['inv_usd', 'inv_eur'] } }, + groupBy: ['invoice'], + aggregations: [{ function: 'sum', field: 'amount', alias: 'value' }], + }))); + expect(envelopeOf(err)).toEqual(INVALID_FIELD); + }); + const PROJECT = { name: 'pp_project', fields: { title: { type: 'text' } } }; const lineWith = (extra: Record) => ({ ...PP_LINE, fields: { ...PP_LINE.fields, ...extra } });