Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/rollup-grouped-recompute-33795.md
Original file line number Diff line number Diff line change
@@ -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.
142 changes: 119 additions & 23 deletions packages/objectql/src/engine-summaries-and-expansion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<string, ParentWrite>();
const idsByDesc = new Map<SummaryDescriptor, string[]>();
for (const desc of descriptors) {
const ids = new Set<string>();
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<string>();
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<string, unknown>) => 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<string, unknown> = {};
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<SummaryDescriptor, Map<string, unknown>>();
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<string, unknown> = {};
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;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
};
Expand Down
2 changes: 2 additions & 0 deletions packages/objectql/src/engine-summary-retry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
});
};
Expand Down
5 changes: 5 additions & 0 deletions packages/objectql/src/engine-update-prior-read-scope.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
7 changes: 5 additions & 2 deletions packages/objectql/src/record-currency-aggregate-door.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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');

Expand Down
42 changes: 41 additions & 1 deletion packages/objectql/src/record-currency-guards.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)', () => {
Expand Down Expand Up @@ -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<string, unknown>) => ({ ...PP_LINE, fields: { ...PP_LINE.fields, ...extra } });

Expand Down
64 changes: 64 additions & 0 deletions packages/objectql/src/summary-aggregate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Map<string, unknown>> {
const found = new Map<string, unknown>();
// 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<string, unknown>();
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.
Expand Down
Loading
Loading