From a9a891e654cc88b1c7c5a56781bb9226ea7f9720 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 01:58:30 +0000 Subject: [PATCH 1/6] test(objectql): pin a roll-up an upgrade adds reading its computed value on pre-upgrade rows Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- ...-upgrade-added-summary-materialise.test.ts | 292 ++++++++++++++++++ 1 file changed, 292 insertions(+) create mode 100644 packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts diff --git a/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts b/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts new file mode 100644 index 00000000000..0536c844809 --- /dev/null +++ b/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts @@ -0,0 +1,292 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34096] A roll-up `summary` field that a package install or upgrade adds + * reads, on the parent rows stored before it, what a new row with the same + * children reads, with no child write. + * + * The upgrade here is the shape the install door drives: the running engine + * already holds version 1 of a package (registered at boot, which seals the + * set of roll-ups the stored rows were computed for), rows are written, and + * version 2 is registered with `objectExtensions` that add a `sum`, a `count` + * and a `max` roll-up to an object that already has parent and child rows. + * Then the door asks the engine for its schema sync (`ObjectQL.syncSchemas`), + * as `MarketplaceInstallLocal` does after its hot register. + * + * Before the fix the new columns stayed `null` on every pre-upgrade parent + * until one of its children was written, while a parent created after the + * upgrade read `0` for the same empty child set. + */ + +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { ObjectQL } from './engine.js'; + +function makeDriver() { + const stores = new Map>(); + const storeFor = (o: string) => { + let s = stores.get(o); + if (!s) { s = new Map(); stores.set(o, s); } + return s; + }; + const checkOp = (value: any, cond: any): boolean => { + if (cond === null || typeof cond !== 'object' || Array.isArray(cond) || cond instanceof Date) return value === cond; + return Object.entries(cond).every(([op, target]: [string, any]) => { + switch (op) { + case '$eq': return value === target; + case '$ne': return value !== target; + case '$gt': return value > target; + case '$gte': return value >= target; + case '$lt': return value < target; + case '$lte': return value <= target; + case '$in': return Array.isArray(target) && target.includes(value); + case '$nin': return Array.isArray(target) && !target.includes(value); + default: return true; + } + }); + }; + const matches = (row: any, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + return Object.entries(where).every(([k, v]: [string, any]) => { + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); + if (k === '$or') return (v as any[]).some((w) => matches(row, w)); + if (k === '$not') return !matches(row, v); + return checkOp(row?.[k], v); + }); + }; + let n = 0; + /** Every driver write, by verb and object, so a case can say what moved. */ + const writes: Array<{ verb: string; object: string; id?: string; data?: Record }> = []; + /** Every driver read, by object, so a case can say a sync read nothing. */ + const reads: string[] = []; + /** Ids whose next `update` throws, to drive a failed backfill row. */ + const failUpdateOf = new Set(); + const driver: any = { + name: 'memory', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + async syncSchema() {}, + async find(object: string, ast: any) { + reads.push(object); + let rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); + // Keyset order (`id` ascending) so the backfill's walk pages as on a real driver. + rows = rows.sort((a, b) => String(a.id).localeCompare(String(b.id))); + const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + return page.map((r) => ({ ...r })); + }, + async findOne(object: string, ast: any) { + reads.push(object); + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r }; + return null; + }, + async create(object: string, data: Record) { + n += 1; + const id = (data.id as string) ?? `r_${String(n).padStart(4, '0')}`; + const row = { ...data, id }; + writes.push({ verb: 'create', object, id, data }); + storeFor(object).set(id, row); + return { ...row }; + }, + async update(object: string, id: string, data: Record) { + if (failUpdateOf.has(id)) throw new Error(`fake driver: update of ${id} refused`); + writes.push({ verb: 'update', object, id, data }); + const s = storeFor(object); + const row = { ...s.get(id), ...data, id }; + s.set(id, row); + return { ...row }; + }, + async updateMany() { return 0; }, + async delete(object: string, id: string) { writes.push({ verb: 'delete', object, id }); return storeFor(object).delete(id); }, + async deleteMany() { return 0; }, + async count() { return 0; }, + async bulkCreate(object: string, rows: Record[]) { return Promise.all(rows.map((r) => this.create(object, r))); }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + }; + return { driver, storeFor, writes, reads, failUpdateOf }; +} + +const APP = 'com.qa.o2c'; +const CONTRACT = 'qx_contract'; +const INVOICE = 'qx_invoice'; +const INVOICED = 'invoiced_amount'; +const INVOICE_COUNT = 'invoice_count'; +const LAST_INVOICE = 'largest_invoice'; + +const contract = { name: CONTRACT, label: 'Contract', fields: { title: { name: 'title', type: 'text', label: 'Title' } } }; +const invoice = { + name: INVOICE, label: 'Invoice', + fields: { + amount: { name: 'amount', type: 'number', label: 'Amount' }, + contract: { name: 'contract', type: 'lookup', label: 'Contract', reference: CONTRACT }, + }, +}; +const ROLLUPS = { + [INVOICED]: { name: INVOICED, type: 'summary', label: 'Invoiced', summaryOperations: { object: INVOICE, field: 'amount', function: 'sum' } }, + [INVOICE_COUNT]: { name: INVOICE_COUNT, type: 'summary', label: 'Invoices', summaryOperations: { object: INVOICE, function: 'count' } }, + [LAST_INVOICE]: { name: LAST_INVOICE, type: 'summary', label: 'Largest invoice', summaryOperations: { object: INVOICE, field: 'amount', function: 'max' } }, +}; + +/** Version 1: the objects, no roll-up. */ +const v1 = { id: APP, name: 'o2c', version: '6.2.0', objects: [contract, invoice] }; +/** Version 2: the same objects, and the roll-ups added by extension. */ +const v2 = { ...v1, version: '6.3.0', objectExtensions: [{ extend: CONTRACT, fields: ROLLUPS }] }; +/** Version 3: nothing new about roll-ups. */ +const v3 = { ...v2, version: '6.4.0' }; + +/** + * The end of the boot: every package of this boot is registered, and the + * roll-ups present now are the ones the stored rows were computed for. The + * plugin calls this at `kernel:bootstrapped`. Read optionally so that, on a + * build without it, this file reads red on the defect itself rather than on a + * missing method. + */ +function bootCompleted(engine: ObjectQL): void { + (engine as unknown as { sealSummariesMaterialisedAtBoot?: () => unknown }).sealSummariesMaterialisedAtBoot?.call(engine); +} + +describe('#34096 — a roll-up an upgrade adds is materialised on the rows stored before it', () => { + let engine: ObjectQL; + let d: ReturnType; + let logger: Record<'debug' | 'info' | 'warn' | 'error', ReturnType> & Record; + const SYS = { context: { isSystem: true } } as const; + + beforeEach(async () => { + logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), trace: vi.fn(), fatal: vi.fn() }; + logger.child = () => logger; + engine = new ObjectQL({ logger }); + d = makeDriver(); + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registerApp(v1); + bootCompleted(engine); + }); + + const read = async (id: string) => engine.findOne(CONTRACT, { where: { id }, ...SYS }); + + /** Two contracts with invoices and one without, all stored under version 1. */ + async function storeUnderV1() { + const acme = await engine.insert(CONTRACT, { title: 'acme' }, SYS); + const beta = await engine.insert(CONTRACT, { title: 'beta' }, SYS); + const idle = await engine.insert(CONTRACT, { title: 'idle' }, SYS); + await engine.insert(INVOICE, { contract: acme.id, amount: 36000 }, SYS); + await engine.insert(INVOICE, { contract: acme.id, amount: 4000 }, SYS); + await engine.insert(INVOICE, { contract: beta.id, amount: 700 }, SYS); + return { acme, beta, idle }; + } + + async function upgrade(body: Record) { + engine.registerApp(body); + await engine.syncSchemas(); + } + + it('every pre-upgrade parent reads its computed value after the upgrade, with no child write', async () => { + const { acme, beta, idle } = await storeUnderV1(); + const before = d.writes.length; + + await upgrade(v2); + + expect(d.writes.slice(before).filter((w) => w.object === INVOICE)).toEqual([]); + expect(await read(acme.id)).toMatchObject({ [INVOICED]: 40000, [INVOICE_COUNT]: 2, [LAST_INVOICE]: 36000 }); + expect(await read(beta.id)).toMatchObject({ [INVOICED]: 700, [INVOICE_COUNT]: 1, [LAST_INVOICE]: 700 }); + // A parent with no children: `count`/`sum` read 0 (their empty-set value), + // `max` reads null (undefined on an empty set) — what a new row reads. + const idleRow = await read(idle.id); + expect(idleRow?.[INVOICED]).toBe(0); + expect(idleRow?.[INVOICE_COUNT]).toBe(0); + expect(idleRow?.[LAST_INVOICE] ?? null).toBeNull(); + }); + + it('a pre-upgrade parent reads exactly what a new parent with the same children reads', async () => { + const { acme, idle } = await storeUnderV1(); + await upgrade(v2); + + const fresh = await engine.insert(CONTRACT, { title: 'fresh' }, SYS); + const freshIdle = await engine.insert(CONTRACT, { title: 'fresh idle' }, SYS); + await engine.insert(INVOICE, { contract: fresh.id, amount: 36000 }, SYS); + await engine.insert(INVOICE, { contract: fresh.id, amount: 4000 }, SYS); + + const pick = (row: any) => ({ + [INVOICED]: row?.[INVOICED], [INVOICE_COUNT]: row?.[INVOICE_COUNT], [LAST_INVOICE]: row?.[LAST_INVOICE] ?? null, + }); + expect(pick(await read(acme.id))).toEqual(pick(await read(fresh.id))); + expect(pick(await read(idle.id))).toEqual(pick(await read(freshIdle.id))); + }); + + it('a second upgrade that adds no roll-up reads and writes nothing for roll-ups', async () => { + await storeUnderV1(); + await upgrade(v2); + const writesBefore = d.writes.length; + const readsBefore = d.reads.length; + + await upgrade(v3); + + expect(d.writes.slice(writesBefore)).toEqual([]); + expect(d.reads.slice(readsBefore)).toEqual([]); + }); + + it('a roll-up present when the boot completed is not walked by a later sync', async () => { + // A boot that already carries version 2 (a restart of an upgraded + // deployment, or the install-local rehydrate at `kernel:ready`). + const booted = new ObjectQL({ logger }); + const d2 = makeDriver(); + booted.registerDriver(d2.driver, true); + await booted.init(); + booted.registerApp(v2); + await booted.syncSchemas(); + bootCompleted(booted); + const readsBefore = d2.reads.length; + + await booted.syncSchemas(); + + expect(d2.reads.slice(readsBefore)).toEqual([]); + expect(d2.writes).toEqual([]); + }); + + it('writes the parent as the system, in no organization, and fires no hook of the child object', async () => { + const { acme } = await storeUnderV1(); + const childHooks = vi.fn(); + for (const event of ['beforeInsert', 'afterInsert', 'beforeUpdate', 'afterUpdate']) { + engine.registerHook(event, childHooks, { object: INVOICE }); + } + const observed: Array<{ object: string; operation: string; isSystem: boolean; tenantId: unknown }> = []; + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + observed.push({ + object: opCtx.object, operation: opCtx.operation, + isSystem: opCtx.context?.isSystem === true, tenantId: opCtx.context?.tenantId, + }); + return next(); + }); + + await upgrade(v2); + + expect(childHooks).not.toHaveBeenCalled(); + expect((await read(acme.id))?.[INVOICED]).toBe(40000); + const parentUpdates = observed.filter((o) => o.object === CONTRACT && o.operation === 'update'); + expect(parentUpdates.length).toBeGreaterThan(0); + for (const op of parentUpdates) expect(op).toMatchObject({ isSystem: true, tenantId: undefined }); + expect(observed.filter((o) => o.object === INVOICE && o.operation !== 'find' && o.operation !== 'aggregate')).toEqual([]); + }); + + it('an interrupted backfill is retried by the next sync, and the re-run fills only what is still null', async () => { + const { acme, beta } = await storeUnderV1(); + d.failUpdateOf.add(acme.id); + + await upgrade(v2); + + expect((await read(beta.id))?.[INVOICED]).toBe(700); + expect((await read(acme.id))?.[INVOICED] ?? null).toBeNull(); + const said = logger.error.mock.calls.map((c) => String(c[0])).filter((m) => m.startsWith('[summary-materialise]')); + expect(said).toHaveLength(1); + expect(said[0]).toContain(`${CONTRACT}.${INVOICED}`); + expect(said[0]).toContain('os migrate summary-nulls --apply'); + + d.failUpdateOf.clear(); + const writesBefore = d.writes.length; + await engine.syncSchemas(); + + expect((await read(acme.id))).toMatchObject({ [INVOICED]: 40000, [INVOICE_COUNT]: 2, [LAST_INVOICE]: 36000 }); + // Only the row the first run could not write is written again. + const rewritten = new Set(d.writes.slice(writesBefore).filter((w) => w.object === CONTRACT).map((w) => w.id)); + expect([...rewritten]).toEqual([acme.id]); + }); +}); From 83cb265f90cb9c3cd3c17c39e73e7a685fd7905b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 02:08:55 +0000 Subject: [PATCH 2/6] fix(objectql): compute on stored rows the roll-ups a package install or upgrade adds Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../objectql/src/engine-compatibility-api.ts | 10 +- packages/objectql/src/engine.ts | 25 +++ packages/objectql/src/index.ts | 3 + packages/objectql/src/plugin.ts | 6 + .../src/summary-install-materialise.ts | 195 ++++++++++++++++++ 5 files changed, 238 insertions(+), 1 deletion(-) create mode 100644 packages/objectql/src/summary-install-materialise.ts diff --git a/packages/objectql/src/engine-compatibility-api.ts b/packages/objectql/src/engine-compatibility-api.ts index aa18c24836e..9844dc3ce51 100644 --- a/packages/objectql/src/engine-compatibility-api.ts +++ b/packages/objectql/src/engine-compatibility-api.ts @@ -71,6 +71,8 @@ export interface CompatibilityApiHost { readonly logger: ObjectQL['logger']; getDriverForObject: ObjectQL['getDriverForObject']; removeActionsByPackage: ObjectQL['removeActionsByPackage']; + /** [#34096] The roll-ups an install added, computed on the stored rows. */ + materialiseAddedSummaries: ObjectQL['materialiseAddedSummaries']; } /** The body of `ObjectQL#registerObject`; the method's docblock there is its contract. */ @@ -120,7 +122,7 @@ export async function introspectDatasource( /** The body of `ObjectQL#syncSchemas`; the method's docblock there is its contract. */ export async function syncSchemas( - this: Pick, + this: Pick, ): Promise { // The storage layer's objects: a disabled package's extensions folded in, // so the DDL keeps their columns (`SchemaRegistry.getStorageObject`). @@ -187,6 +189,12 @@ export async function syncSchemas( } } } + // [#34096] Every runtime caller of this sync is an install door, after its + // hot register: a roll-up the install added now has its column on every + // stored row, NULL. Compute it there, as the child-write recompute would + // (`summary-install-materialise.ts`); a roll-up the boot already served is + // not walked, and a sync before the boot completes walks nothing. + await this.materialiseAddedSummaries(); } /** The body of `ObjectQL#syncObjectSchema`; the method's docblock there is its contract. */ diff --git a/packages/objectql/src/engine.ts b/packages/objectql/src/engine.ts index 7bbfc0ea205..d8e234867f5 100644 --- a/packages/objectql/src/engine.ts +++ b/packages/objectql/src/engine.ts @@ -145,6 +145,7 @@ import { type SummaryDescriptor, } from './summary-aggregate.js'; import { refreshSummariesExtendedBy, summaryRefreshesSettled, type SummaryEnableRefreshReport } from './summary-enable-refresh.js'; +import { materialiseSummariesAddedSinceBoot, sealSummariesMaterialisedAtBoot, type SummaryMaterialiseOutcome } from './summary-install-materialise.js'; import { DriverConnectError, DatasourceUnavailableError, @@ -4093,6 +4094,29 @@ export class ObjectQL implements IObjectQLEngine { return refreshSummariesExtendedBy(this, this.logger, packageId); } + /** + * [#34096] Record the roll-up `summary` fields served at the end of the + * boot as the ones the stored rows were computed for. `ObjectQLPlugin` calls + * it at `kernel:bootstrapped`; until then {@link materialiseAddedSummaries} + * walks nothing. Returns how many roll-ups are recorded. + */ + sealSummariesMaterialisedAtBoot(): number { + return sealSummariesMaterialisedAtBoot(this); + } + + /** + * [#34096] Compute, on every stored row still `NULL` there, the roll-up + * `summary` fields served now that the boot did not record — the ones a + * package install or upgrade added — through the child-write recompute's own + * aggregate and system-context `update`, then record them. {@link syncSchemas} + * runs it, so every install door's sync does. Never throws: an incomplete + * walk is logged at `error`, left unrecorded, and walked again by the next + * call (`summary-install-materialise.ts`). + */ + materialiseAddedSummaries(): Promise { + return materialiseSummariesAddedSinceBoot(this, this.logger); + } + /** [#30377] Resolves once the summary recomputes the enables so far started ({@link refreshSummariesEnabledBy}) have settled, so a door can answer after them. */ summaryRefreshSettled(): Promise { return summaryRefreshesSettled(this); @@ -5544,6 +5568,7 @@ export class ObjectQL implements IObjectQLEngine { const readLogger = () => this.logger; const host: ThisParameterType = { getDriverForObject: (...a) => this.getDriverForObject(...a), + materialiseAddedSummaries: () => this.materialiseAddedSummaries(), get _registry() { return readRegistry(); }, get logger() { return readLogger(); }, }; diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index fe7d449c9f2..b4532c43d4a 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -633,6 +633,9 @@ export type { SummaryBackfillLogger, SummaryBackfillOptions, } from './summary-backfill.js'; +// [#34096] What `ObjectQL.materialiseAddedSummaries` (run by every install +// door's `syncSchemas`) did with the roll-ups an install or upgrade added. +export type { SummaryMaterialiseOutcome } from './summary-install-materialise.js'; // [#29961] The backfill behind `os migrate stored-expressions`: stored computed // fields over rows no write has computed since the field was declared, and the // boot advisory naming it. Same split as the roll-up backfill above. diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index d5973e882ed..d5b497bc0c7 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -1381,6 +1381,12 @@ export class ObjectQLPlugin implements Plugin { // hooks: there the doors never refuse. const registry = this.ql?.registry; if (registry) sealBareNameHoldersAtColdBoot(registry, BARE_NAME_COLD_BOOT_MODE, ctx.logger); + // [#34096] The same moment, for roll-ups: every package of this boot + // is registered and schema sync has run, so the roll-ups served now are + // the ones the stored rows were computed for. From here on an install + // door's `syncSchemas` computes, on the stored rows, the roll-ups an + // install or upgrade adds (`summary-install-materialise.ts`). + this.ql?.sealSummariesMaterialisedAtBoot(); // [ADR-0150 D8 row R4] With the holders sealed, bind every activation // ledger row that names no package to the one package that holds its // item, and report the rows two packages hold (never guessed). Writes diff --git a/packages/objectql/src/summary-install-materialise.ts b/packages/objectql/src/summary-install-materialise.ts new file mode 100644 index 00000000000..ad74e833638 --- /dev/null +++ b/packages/objectql/src/summary-install-materialise.ts @@ -0,0 +1,195 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#34096] Materialise, at an install door's schema sync, the roll-up + * `summary` fields a package install or upgrade added to objects whose rows + * already exist. + * + * ## The hole + * + * A summary column is written by three paths (`summary-aggregate.ts`): the + * insert-time seed (new rows only), the child-write recompute (a parent named + * by a child write), and `os migrate summary-nulls` (an operator run). A + * summary that an upgrade adds — HotCRM's o2c module adding `invoiced_amount` + * to `crm_contract` through `objectExtensions` — reaches none of them for the + * rows already stored: the schema sync adds the column, every existing parent + * holds `NULL` there, and it stays `NULL` until one of its children is + * written. A contract created after the upgrade reads `0` for the same empty + * child set, so one logical state read two ways depending on when the row was + * made. + * + * ## Materialise on the upgrade, not compute on read + * + * A value computed on read is not the stored column: every filter, sort, + * GROUP BY and formula over it still reads `NULL` (the reason + * `summary-backfill.ts` gives for recomputing rather than reading), and a read + * path that aggregates per row pays the aggregate on every list read for ever. + * The install door is the one moment that both knows a summary is new and has + * just created its column, so the values are written there, through + * {@link backfillSummaryNulls}: the same aggregate the engine's own recompute + * uses, the same system context (`{ isSystem: true }`, no tenant — every + * organization's rows), the same `update` verb on the parent, so a parent + * write fires what the child-write recompute's parent write fires and no + * child row is written. Keyset pages of 500, bounded per object. + * + * ## Which summaries are new + * + * The engine records, when the boot completes (the plugin calls + * {@link sealSummariesMaterialisedAtBoot} at `kernel:bootstrapped`, after the + * install-local rehydrate at `kernel:ready`), the roll-ups it serves then: + * those are the ones the stored rows were computed for. Every later + * {@link materialiseSummariesAddedSinceBoot} — run by `ObjectQL.syncSchemas`, + * the sync an install door asks for after its hot register — walks only the + * roll-ups the engine serves now and has not recorded, then records them. So + * a second upgrade that adds no roll-up reads and writes nothing, and a sync + * before the boot completes (the rehydrate's) walks nothing. + * + * The walk names every new roll-up in `recomputeUndefinedOnEmpty` (#15064): + * the door is the caller that KNOWS these columns were never computed, so a + * new `min`/`max`/`avg` is recomputed on every `NULL` parent too. After it, + * an empty child set reads what a new row reads: `0` for `count`/`sum` (their + * empty-set value), `null` for `min`/`max`/`avg` (undefined on the empty set). + * + * ## A failed or interrupted walk + * + * The walk writes only rows still holding `NULL`, so it is idempotent. A row + * that fails, an object that cannot be read, or a walk cut short by the + * per-object bound leaves the walk incomplete: its roll-ups are NOT recorded, + * so the next install door's sync walks them again and fills only what is + * still `NULL`, and the incompleteness is logged at `error` with the operator + * command that finishes it (`os migrate summary-nulls --apply`, naming each + * roll-up). A process that dies mid-walk records nothing either, but its next + * boot seals what it serves, so there the operator command is the re-run. + */ + +import { + backfillSummaryNulls, + summaryBackfillComplete, + type SummaryBackfillEngine, + type SummaryBackfillReport, +} from './summary-backfill.js'; + +/** The engine surface the materialisation reads and writes through. `ObjectQL` is one. */ +export interface SummaryMaterialiseEngine extends SummaryBackfillEngine { + getConfigs(): Record; +} + +export interface SummaryMaterialiseLogger { + info(msg: string, meta?: unknown): void; + warn(msg: string, meta?: unknown): void; + error?(msg: string, meta?: unknown): void; +} + +/** What one {@link materialiseSummariesAddedSinceBoot} did. */ +export type SummaryMaterialiseOutcome = + /** The boot has not completed: the roll-ups served now are the boot's own. */ + | { status: 'boot-not-complete' } + /** No roll-up is served that the boot (or an earlier walk) did not record. */ + | { status: 'nothing-added' } + /** The added roll-ups (`object.field`) were walked to completion and recorded. */ + | { status: 'materialised'; added: string[]; report: SummaryBackfillReport } + /** The walk did not complete; the roll-ups stay unrecorded and the next sync walks them again. */ + | { status: 'incomplete'; added: string[]; report?: SummaryBackfillReport; error?: string }; + +/** Per engine: the roll-ups (`object.field`) the stored rows are known to be computed for. */ +const recorded = new WeakMap>(); +/** Per engine: the walk in progress, so two doors' syncs do not walk the same roll-ups twice at once. */ +const inFlight = new WeakMap>(); + +/** Every roll-up the engine serves now, as `object.field` → its parent object. */ +function servedSummaries(engine: SummaryMaterialiseEngine): Map { + const served = new Map(); + for (const object of Object.keys(engine.getConfigs())) { + for (const desc of engine.getOwnedSummaryDescriptors(object)) { + served.set(`${desc.parentObject}.${desc.summaryField}`, desc.parentObject); + } + } + return served; +} + +/** + * Record the roll-ups the engine serves at the end of the boot as computed for + * the stored rows. Called once per boot; a later call adds what is served then. + * Returns how many roll-ups are recorded. + */ +export function sealSummariesMaterialisedAtBoot(engine: SummaryMaterialiseEngine): number { + const set = recorded.get(engine) ?? new Set(); + for (const key of servedSummaries(engine).keys()) set.add(key); + recorded.set(engine, set); + return set.size; +} + +/** The incompleteness line: consequence and the command that finishes it. */ +function incompleteMessage(added: string[], detail: string): string { + const named = added.map((k) => `--recompute-undefined-on-empty ${k}`).join(' '); + return ( + `[summary-materialise] the roll-up summary field(s) ${added.join(', ')} added by a package install or upgrade were ` + + `NOT computed on every existing row (${detail}). CONSEQUENCE: those rows keep NULL there while a new row with the ` + + `same children reads the computed value, and nothing else fills them until one of their children is written. ` + + `FIX: clear the cause, then run \`os migrate summary-nulls --apply ${named}\` (idempotent: it fills only the rows ` + + `still NULL); the next package install in this process also walks them again.` + ); +} + +async function walkAdded( + engine: SummaryMaterialiseEngine, + logger: SummaryMaterialiseLogger, +): Promise { + const set = recorded.get(engine); + if (!set) return { status: 'boot-not-complete' }; + const served = servedSummaries(engine); + const added = [...served.keys()].filter((key) => !set.has(key)).sort(); + if (added.length === 0) return { status: 'nothing-added' }; + const objects = [...new Set(added.map((key) => served.get(key)!))].sort(); + const say = (msg: string, meta: unknown) => { + // Sanctioned logger shape (PR #9750): reach for `error`, fall back to `warn`. + if (typeof logger.error === 'function') logger.error(msg, meta); + else logger.warn(msg, meta); + }; + let report: SummaryBackfillReport; + try { + report = await backfillSummaryNulls(engine, logger, { + apply: true, + objects, + recomputeUndefinedOnEmpty: added, + }); + } catch (err) { + const error = (err as Error)?.message ?? String(err); + say(incompleteMessage(added, `the walk could not run: ${error}`), { added }); + return { status: 'incomplete', added, error }; + } + if (!summaryBackfillComplete(report)) { + const parts = [ + report.failures.length > 0 + ? `${report.failures.length} row(s) failed, e.g. ${report.failures.slice(0, 3).map((f) => `${f.object}/${f.recordId}: ${f.error}`).join('; ')}` + : '', + report.unreadableObjects.length > 0 ? `unreadable: ${report.unreadableObjects.join(', ')}` : '', + report.truncated && report.unreadableObjects.length === 0 ? 'the walk reached its per-object bound' : '', + ].filter(Boolean); + say(incompleteMessage(added, parts.join('; ')), { added, failures: report.failures }); + return { status: 'incomplete', added, report }; + } + for (const key of added) set.add(key); + logger.info( + `[summary-materialise] computed the roll-up summary field(s) ${added.join(', ')} added by a package install or ` + + `upgrade on the existing rows: ${report.filled} value(s) written over ${report.scannedRecords} row(s).`, + { added, filled: report.filled, scannedRecords: report.scannedRecords }, + ); + return { status: 'materialised', added, report }; +} + +/** + * Walk the roll-ups the engine serves that the boot did not record (see the + * module comment), filling every existing row still `NULL` there, and record + * them once the walk completes. Never throws: an incomplete walk is logged at + * `error` and reported. Serialised per engine. + */ +export function materialiseSummariesAddedSinceBoot( + engine: SummaryMaterialiseEngine, + logger: SummaryMaterialiseLogger, +): Promise { + const previous = inFlight.get(engine) ?? Promise.resolve(); + const run = previous.then(() => walkAdded(engine, logger), () => walkAdded(engine, logger)); + inFlight.set(engine, run); + return run; +} From 0eaeb98b5814c41f62080918d60fbe7a2339b0f5 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 02:09:12 +0000 Subject: [PATCH 3/6] chore: changeset for the upgrade-added roll-up materialisation Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- .../34096-upgrade-added-summary-materialise.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .changeset/34096-upgrade-added-summary-materialise.md diff --git a/.changeset/34096-upgrade-added-summary-materialise.md b/.changeset/34096-upgrade-added-summary-materialise.md new file mode 100644 index 00000000000..00375c84d23 --- /dev/null +++ b/.changeset/34096-upgrade-added-summary-materialise.md @@ -0,0 +1,18 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): a roll-up summary field that a package install or upgrade adds is computed on the rows stored before it + +Clause-②: yes (widening) +Metadata-protocol: none + +A `summary` field that an upgrade adds, for example through `objectExtensions`, used to read `null` on every parent row stored before the upgrade, until one of that parent's children was written. A parent created after the upgrade read `0` for the same empty child set. + +`ObjectQL.syncSchemas()` is the sync an install door runs after its hot register, as `MarketplaceInstallLocal` does. It now computes those new roll-ups on every stored row that still holds `NULL`. It uses the aggregate and the system-context parent `update` that the child-write recompute uses. No child row is written, and the rows of every organization are covered. After the upgrade, a pre-existing parent reads what a new parent with the same children reads. For an empty child set that is `0` for `count`/`sum` and `null` for `min`/`max`/`avg`. + +The engine records the roll-ups it serves when the boot completes (`kernel:bootstrapped`). Only roll-ups added after that are walked, so a second upgrade that adds none reads and writes nothing for roll-ups. A walk that fails on a row, cannot read an object, or reaches its per-object bound is logged at `error` and is not recorded. The next install's sync walks it again and fills only what is still `NULL`. `os migrate summary-nulls --apply --recompute-undefined-on-empty OBJECT.FIELD` finishes it from the command line. + +A roll-up that arrives with a restart rather than through an install door is not walked. This covers a code-defined app's new version and a marketplace install whose hot register failed and loads at the next restart. There, `os migrate summary-nulls --apply` remains the backfill. + +New engine members: `ObjectQL.materialiseAddedSummaries()` (re-run it after clearing a logged failure) and `ObjectQL.sealSummariesMaterialisedAtBoot()`, which the ObjectQL plugin calls. From 71f012a48acc9e99056a288933475d2bd6702e9a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 02:34:06 +0000 Subject: [PATCH 4/6] test(objectql): pin the plugin's boot seal under a real kernel boot Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- ...-upgrade-added-summary-materialise.test.ts | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts b/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts index 0536c844809..f9289f8a877 100644 --- a/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts +++ b/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts @@ -19,7 +19,9 @@ */ import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; import { ObjectQL } from './engine.js'; +import { ObjectQLPlugin } from './plugin.js'; function makeDriver() { const stores = new Map>(); @@ -290,3 +292,32 @@ describe('#34096 — a roll-up an upgrade adds is materialised on the rows store expect([...rewritten]).toEqual([acme.id]); }); }); + +describe('#34096 — the ObjectQL plugin records the boot\'s roll-ups, so an install door after it materialises', () => { + it('an upgrade after a real kernel boot fills the pre-upgrade parents', async () => { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + const d = makeDriver(); + await kernel.use({ + name: 'qx-store-plugin', type: 'driver', version: '1.0.0', + init: async (ctx: any) => { ctx.registerService('driver.memory', d.driver); }, + } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.bootstrap(); + try { + const engine = kernel.getService('objectql'); + engine.registerApp(v1); + await engine.syncSchemas(); + const SYS = { context: { isSystem: true } } as const; + const acme = await engine.insert(CONTRACT, { title: 'acme' }, SYS); + await engine.insert(INVOICE, { contract: acme.id, amount: 36000 }, SYS); + + engine.registerApp(v2); + await engine.syncSchemas(); + + const row = await engine.findOne(CONTRACT, { where: { id: acme.id }, ...SYS }); + expect(row).toMatchObject({ [INVOICED]: 36000, [INVOICE_COUNT]: 1, [LAST_INVOICE]: 36000 }); + } finally { + await kernel.shutdown(); + } + }); +}); From 2d39431494fa4f9b961d13bda806c3586c9eb6c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 03:13:14 +0000 Subject: [PATCH 5/6] docs(cli): say when an install materialises added roll-ups and when summary-nulls is still owed Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- content/docs/deployment/cli.mdx | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 7c11806b76e..d4bc6b58794 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1679,6 +1679,26 @@ name that is not a roll-up this run walks — a typo, a plain field, or an objec `sum` is accepted and changes nothing, so a caller can pass every column it just declared. +**A package install or upgrade does this for you.** When a running deployment +installs or upgrades a package through an install door (the marketplace +install, for example), the door's schema sync computes every roll-up the +package added, on each stored row still holding `NULL`. It uses the aggregate +and the system-context write that the child-write recompute uses, for every +organization's rows, and it writes no child row. `min` / `max` / `avg` are +included, because the door knows those columns are new. Roll-ups the deployment +already served when it booted are not walked again, so an upgrade that adds no +roll-up costs nothing here. Two cases still need this command: + +- **The walk did not complete.** A row failed, an object could not be read, or + the per-object bound was reached. The server logs it at `error`, naming each + roll-up, and gives the exact + `os migrate summary-nulls --apply --recompute-undefined-on-empty …` line. + The next install in the same process also walks those roll-ups again. +- **The roll-up arrived with a restart, not through an install door.** This + covers a code-defined app's new version and a marketplace install whose hot + register failed and loaded at the next restart. A boot records what it serves + and computes nothing. + Idempotent — every write turns a `NULL` into a number, so a second run finds nothing and writes nothing. Re-running until the report says zero *is* the verification, which is why this command records no flag: it repairs values and From c6ff87ce6be3c8306e560911b197b13112a453e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 16 Nov 2026 05:29:29 +0000 Subject: [PATCH 6/6] fix(objectql): the install walk writes backfilled parents with automations off The parent write carries skipAutomations, as the install door's own seed writes do, through a new opt-in skipAutomations option on backfillSummaryNulls; os migrate summary-nulls is unchanged. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh --- ...34096-upgrade-added-summary-materialise.md | 2 +- content/docs/deployment/cli.mdx | 7 +- ...-upgrade-added-summary-materialise.test.ts | 89 +++++++++++++++++++ packages/objectql/src/summary-backfill.ts | 17 +++- .../src/summary-install-materialise.ts | 16 +++- 5 files changed, 123 insertions(+), 8 deletions(-) diff --git a/.changeset/34096-upgrade-added-summary-materialise.md b/.changeset/34096-upgrade-added-summary-materialise.md index 00375c84d23..5485b36cc82 100644 --- a/.changeset/34096-upgrade-added-summary-materialise.md +++ b/.changeset/34096-upgrade-added-summary-materialise.md @@ -9,7 +9,7 @@ Metadata-protocol: none A `summary` field that an upgrade adds, for example through `objectExtensions`, used to read `null` on every parent row stored before the upgrade, until one of that parent's children was written. A parent created after the upgrade read `0` for the same empty child set. -`ObjectQL.syncSchemas()` is the sync an install door runs after its hot register, as `MarketplaceInstallLocal` does. It now computes those new roll-ups on every stored row that still holds `NULL`. It uses the aggregate and the system-context parent `update` that the child-write recompute uses. No child row is written, and the rows of every organization are covered. After the upgrade, a pre-existing parent reads what a new parent with the same children reads. For an empty child set that is `0` for `count`/`sum` and `null` for `min`/`max`/`avg`. +`ObjectQL.syncSchemas()` is the sync an install door runs after its hot register, as `MarketplaceInstallLocal` does. It now computes those new roll-ups on every stored row that still holds `NULL`. It uses the aggregate the child-write recompute uses and a system-context parent `update` that covers the rows of every organization. No child row is written. The parent write carries `skipAutomations: true`, as the install door's own seed writes do, so no metadata-bound hook or record-change flow runs on a backfilled parent. The engine's roll-up recompute still runs, so a roll-up over the backfilled parent moves too. `os migrate summary-nulls` is unchanged and still runs them. The new `skipAutomations` option on `backfillSummaryNulls` selects this. After the upgrade, a pre-existing parent reads what a new parent with the same children reads. For an empty child set that is `0` for `count`/`sum` and `null` for `min`/`max`/`avg`. The engine records the roll-ups it serves when the boot completes (`kernel:bootstrapped`). Only roll-ups added after that are walked, so a second upgrade that adds none reads and writes nothing for roll-ups. A walk that fails on a row, cannot read an object, or reaches its per-object bound is logged at `error` and is not recorded. The next install's sync walks it again and fills only what is still `NULL`. `os migrate summary-nulls --apply --recompute-undefined-on-empty OBJECT.FIELD` finishes it from the command line. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index d4bc6b58794..cc8e6ad103e 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -1683,8 +1683,11 @@ just declared. installs or upgrades a package through an install door (the marketplace install, for example), the door's schema sync computes every roll-up the package added, on each stored row still holding `NULL`. It uses the aggregate -and the system-context write that the child-write recompute uses, for every -organization's rows, and it writes no child row. `min` / `max` / `avg` are +the child-write recompute uses and a system-context write that covers every +organization's rows, and it writes no child row. Like the door's own seed +writes, it runs with automations off: no metadata-bound hook or record-change +flow fires on a backfilled parent. A roll-up over that parent is still +recomputed. This command, run by hand, keeps running them. `min` / `max` / `avg` are included, because the door knows those columns are new. Roll-ups the deployment already served when it booted are not walked again, so an upgrade that adds no roll-up costs nothing here. Two cases still need this command: diff --git a/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts b/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts index f9289f8a877..88b95bfe712 100644 --- a/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts +++ b/packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts @@ -22,6 +22,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { ObjectKernel } from '@objectstack/core'; import { ObjectQL } from './engine.js'; import { ObjectQLPlugin } from './plugin.js'; +import { backfillSummaryNulls } from './summary-backfill.js'; function makeDriver() { const stores = new Map>(); @@ -321,3 +322,91 @@ describe('#34096 — the ObjectQL plugin records the boot\'s roll-ups, so an ins } }); }); + +/** + * The install door's writes are end-state data, not user events: its seed + * writes carry `skipAutomations`, and so does this walk's parent write. No + * metadata-bound hook or record-change flow runs on a backfilled parent, + * while the engine's own roll-up recompute does, so a chained roll-up moves. + * `os migrate summary-nulls` is the operator's run, at the operator's time, + * and keeps firing them. + */ +describe('#34096 — the install walk runs no automation on the parents it backfills', () => { + const ACCOUNT = 'qx_account'; + const ROLLED = 'contracts_invoiced'; + const account = { name: ACCOUNT, label: 'Account', fields: { title: { name: 'title', type: 'text', label: 'Title' } } }; + const contractOfAccount = { + ...contract, + fields: { ...contract.fields, account: { name: 'account', type: 'lookup', label: 'Account', reference: ACCOUNT } }, + }; + const c1 = { id: APP, name: 'o2c', version: '6.2.0', objects: [account, contractOfAccount, invoice] }; + // The upgrade adds the contract roll-ups AND one on the account over the + // contract's new `invoiced_amount`: the account is a parent of a parent. + const c2 = { + ...c1, version: '6.3.0', + objectExtensions: [ + { extend: CONTRACT, fields: ROLLUPS }, + { extend: ACCOUNT, fields: { [ROLLED]: { name: ROLLED, type: 'summary', label: 'Invoiced over contracts', summaryOperations: { object: CONTRACT, field: INVOICED, function: 'sum' } } } }, + ], + }; + const SYS = { context: { isSystem: true } } as const; + + async function setUp(opts: { sealed: boolean }) { + const logger: any = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), trace: vi.fn(), fatal: vi.fn() }; + logger.child = () => logger; + const engine = new ObjectQL({ logger }); + const d = makeDriver(); + engine.registerDriver(d.driver, true); + await engine.init(); + engine.registerApp(c1); + if (opts.sealed) bootCompleted(engine); + const firm = await engine.insert(ACCOUNT, { title: 'firm' }, SYS); + const acme = await engine.insert(CONTRACT, { title: 'acme', account: firm.id }, SYS); + await engine.insert(INVOICE, { contract: acme.id, amount: 36000 }, SYS); + await engine.insert(INVOICE, { contract: acme.id, amount: 4000 }, SYS); + // A metadata-bound hook on the parent, bound as an app binds one. + const boundCalls: string[] = []; + engine.bindHooks([ + { name: 'contract_touch', object: CONTRACT, events: ['beforeUpdate', 'afterUpdate'], handler: async (ctx: any) => { boundCalls.push(ctx.event); } }, + ] as any, { packageId: APP }); + const parentWrites: Array<{ skipAutomations: unknown }> = []; + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + if (opCtx.object === CONTRACT && opCtx.operation === 'update') parentWrites.push({ skipAutomations: opCtx.context?.skipAutomations }); + return next(); + }); + engine.registerApp(c2); + return { engine, firm, acme, boundCalls, parentWrites, logger }; + } + + it('writes each backfilled parent with skipAutomations, and its metadata-bound update hook does not fire', async () => { + const { engine, acme, boundCalls, parentWrites } = await setUp({ sealed: true }); + await engine.syncSchemas(); + + expect((await engine.findOne(CONTRACT, { where: { id: acme.id }, ...SYS }))?.[INVOICED]).toBe(40000); + expect(parentWrites.length).toBeGreaterThan(0); + for (const w of parentWrites) expect(w.skipAutomations).toBe(true); + expect(boundCalls).toEqual([]); + }); + + it('still recomputes a chained roll-up: the account over the contracts it just filled', async () => { + const { engine, firm } = await setUp({ sealed: true }); + await engine.syncSchemas(); + + expect((await engine.findOne(ACCOUNT, { where: { id: firm.id }, ...SYS }))?.[ROLLED]).toBe(40000); + }); + + it('CONTROL — the operator backfill (os migrate summary-nulls) writes with automations on, as before', async () => { + const { engine, acme, boundCalls, parentWrites, logger } = await setUp({ sealed: false }); + // Unsealed: the door's sync walks nothing, so only the operator's run writes. + await engine.syncSchemas(); + expect(parentWrites).toEqual([]); + + await backfillSummaryNulls(engine, logger, { apply: true, recomputeUndefinedOnEmpty: [`${CONTRACT}.${LAST_INVOICE}`] }); + + expect((await engine.findOne(CONTRACT, { where: { id: acme.id }, ...SYS }))?.[INVOICED]).toBe(40000); + expect(parentWrites.length).toBeGreaterThan(0); + for (const w of parentWrites) expect(w.skipAutomations).toBeUndefined(); + expect(boundCalls).toContain('beforeUpdate'); + }); +}); + diff --git a/packages/objectql/src/summary-backfill.ts b/packages/objectql/src/summary-backfill.ts index 2fb88f18451..a49fd4ea95f 100644 --- a/packages/objectql/src/summary-backfill.ts +++ b/packages/objectql/src/summary-backfill.ts @@ -195,6 +195,18 @@ export interface SummaryBackfillOptions { * exactly the `count`/`sum` backfill it always was. */ recomputeUndefinedOnEmpty?: string[]; + /** + * [#34096] Write each recomputed parent with `skipAutomations: true` on the + * system context, so its metadata-bound hooks and record-change flows do not + * run (the seed-loader rule: end-state data, not user events). The engine's + * own roll-up recompute is not an automation and still runs, so a parent + * that is itself a child of another roll-up still moves its own parent. + * Set by the install door's walk (`summary-install-materialise.ts`), which + * runs with no operator choosing the moment. Omitted, the write context is + * exactly the bare system context it always was, so `os migrate + * summary-nulls` keeps firing them, at the time the operator picks. + */ + skipAutomations?: boolean; /** Safety bound on parent rows read per object. */ maxRecordsPerObject?: number; /** Retry policy for one row's aggregate + update; defaults to the transient @@ -326,6 +338,9 @@ export async function backfillSummaryNulls( options: SummaryBackfillOptions = {}, ): Promise { const apply = options.apply === true; + // The parent write's context: the bare system context unless the caller + // asked for automations to stay off (see `skipAutomations`). + const writeCtx = options.skipAutomations === true ? { ...SYSTEM_CTX, skipAutomations: true } : { ...SYSTEM_CTX }; const maxPerObject = options.maxRecordsPerObject ?? 100_000; const candidates = options.objects ?? @@ -412,7 +427,7 @@ export async function backfillSummaryNulls( await engine.update( desc.parentObject, { id: parentId, [desc.summaryField]: computed }, - { context: { ...SYSTEM_CTX } }, + { context: { ...writeCtx } }, ); }, options.retry ?? {}); if (undefinedOnEmpty && computed == null) { diff --git a/packages/objectql/src/summary-install-materialise.ts b/packages/objectql/src/summary-install-materialise.ts index ad74e833638..a3b846744f1 100644 --- a/packages/objectql/src/summary-install-materialise.ts +++ b/packages/objectql/src/summary-install-materialise.ts @@ -27,10 +27,13 @@ * The install door is the one moment that both knows a summary is new and has * just created its column, so the values are written there, through * {@link backfillSummaryNulls}: the same aggregate the engine's own recompute - * uses, the same system context (`{ isSystem: true }`, no tenant — every - * organization's rows), the same `update` verb on the parent, so a parent - * write fires what the child-write recompute's parent write fires and no - * child row is written. Keyset pages of 500, bounded per object. + * uses, a system context with no tenant (every organization's rows), and the + * engine's `update` verb on the parent. No child row is written. The parent + * write carries `skipAutomations: true`, as the door's own seed writes do + * (end-state data, not user events): no metadata-bound hook and no + * record-change flow runs on a backfilled parent, while the engine's own + * roll-up recompute still runs, so a parent that is itself a child of another + * roll-up moves that roll-up too. Keyset pages of 500, bounded per object. * * ## Which summaries are new * @@ -152,6 +155,11 @@ async function walkAdded( apply: true, objects, recomputeUndefinedOnEmpty: added, + // The door's own writes are end-state data, not user events (its seed + // owner stamp, the seed-loader rule): no metadata-bound hook or + // record-change flow runs on a backfilled parent. The roll-up recompute + // is the engine's, so a chained roll-up still moves. + skipAutomations: true, }); } catch (err) { const error = (err as Error)?.message ?? String(err);