Skip to content

Commit c6ff87c

Browse files
committed
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QsR2jUg7BKfRBcTPyMxbLh
1 parent e3a4385 commit c6ff87c

5 files changed

Lines changed: 123 additions & 8 deletions

File tree

‎.changeset/34096-upgrade-added-summary-materialise.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ Metadata-protocol: none
99

1010
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.
1111

12-
`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`.
12+
`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`.
1313

1414
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.
1515

‎content/docs/deployment/cli.mdx‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1683,8 +1683,11 @@ just declared.
16831683
installs or upgrades a package through an install door (the marketplace
16841684
install, for example), the door's schema sync computes every roll-up the
16851685
package added, on each stored row still holding `NULL`. It uses the aggregate
1686-
and the system-context write that the child-write recompute uses, for every
1687-
organization's rows, and it writes no child row. `min` / `max` / `avg` are
1686+
the child-write recompute uses and a system-context write that covers every
1687+
organization's rows, and it writes no child row. Like the door's own seed
1688+
writes, it runs with automations off: no metadata-bound hook or record-change
1689+
flow fires on a backfilled parent. A roll-up over that parent is still
1690+
recomputed. This command, run by hand, keeps running them. `min` / `max` / `avg` are
16881691
included, because the door knows those columns are new. Roll-ups the deployment
16891692
already served when it booted are not walked again, so an upgrade that adds no
16901693
roll-up costs nothing here. Two cases still need this command:

‎packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest';
2222
import { ObjectKernel } from '@objectstack/core';
2323
import { ObjectQL } from './engine.js';
2424
import { ObjectQLPlugin } from './plugin.js';
25+
import { backfillSummaryNulls } from './summary-backfill.js';
2526

2627
function makeDriver() {
2728
const stores = new Map<string, Map<string, any>>();
@@ -321,3 +322,91 @@ describe('#34096 — the ObjectQL plugin records the boot\'s roll-ups, so an ins
321322
}
322323
});
323324
});
325+
326+
/**
327+
* The install door's writes are end-state data, not user events: its seed
328+
* writes carry `skipAutomations`, and so does this walk's parent write. No
329+
* metadata-bound hook or record-change flow runs on a backfilled parent,
330+
* while the engine's own roll-up recompute does, so a chained roll-up moves.
331+
* `os migrate summary-nulls` is the operator's run, at the operator's time,
332+
* and keeps firing them.
333+
*/
334+
describe('#34096 — the install walk runs no automation on the parents it backfills', () => {
335+
const ACCOUNT = 'qx_account';
336+
const ROLLED = 'contracts_invoiced';
337+
const account = { name: ACCOUNT, label: 'Account', fields: { title: { name: 'title', type: 'text', label: 'Title' } } };
338+
const contractOfAccount = {
339+
...contract,
340+
fields: { ...contract.fields, account: { name: 'account', type: 'lookup', label: 'Account', reference: ACCOUNT } },
341+
};
342+
const c1 = { id: APP, name: 'o2c', version: '6.2.0', objects: [account, contractOfAccount, invoice] };
343+
// The upgrade adds the contract roll-ups AND one on the account over the
344+
// contract's new `invoiced_amount`: the account is a parent of a parent.
345+
const c2 = {
346+
...c1, version: '6.3.0',
347+
objectExtensions: [
348+
{ extend: CONTRACT, fields: ROLLUPS },
349+
{ extend: ACCOUNT, fields: { [ROLLED]: { name: ROLLED, type: 'summary', label: 'Invoiced over contracts', summaryOperations: { object: CONTRACT, field: INVOICED, function: 'sum' } } } },
350+
],
351+
};
352+
const SYS = { context: { isSystem: true } } as const;
353+
354+
async function setUp(opts: { sealed: boolean }) {
355+
const logger: any = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), trace: vi.fn(), fatal: vi.fn() };
356+
logger.child = () => logger;
357+
const engine = new ObjectQL({ logger });
358+
const d = makeDriver();
359+
engine.registerDriver(d.driver, true);
360+
await engine.init();
361+
engine.registerApp(c1);
362+
if (opts.sealed) bootCompleted(engine);
363+
const firm = await engine.insert(ACCOUNT, { title: 'firm' }, SYS);
364+
const acme = await engine.insert(CONTRACT, { title: 'acme', account: firm.id }, SYS);
365+
await engine.insert(INVOICE, { contract: acme.id, amount: 36000 }, SYS);
366+
await engine.insert(INVOICE, { contract: acme.id, amount: 4000 }, SYS);
367+
// A metadata-bound hook on the parent, bound as an app binds one.
368+
const boundCalls: string[] = [];
369+
engine.bindHooks([
370+
{ name: 'contract_touch', object: CONTRACT, events: ['beforeUpdate', 'afterUpdate'], handler: async (ctx: any) => { boundCalls.push(ctx.event); } },
371+
] as any, { packageId: APP });
372+
const parentWrites: Array<{ skipAutomations: unknown }> = [];
373+
engine.registerMiddleware(async (opCtx: any, next: () => Promise<void>) => {
374+
if (opCtx.object === CONTRACT && opCtx.operation === 'update') parentWrites.push({ skipAutomations: opCtx.context?.skipAutomations });
375+
return next();
376+
});
377+
engine.registerApp(c2);
378+
return { engine, firm, acme, boundCalls, parentWrites, logger };
379+
}
380+
381+
it('writes each backfilled parent with skipAutomations, and its metadata-bound update hook does not fire', async () => {
382+
const { engine, acme, boundCalls, parentWrites } = await setUp({ sealed: true });
383+
await engine.syncSchemas();
384+
385+
expect((await engine.findOne(CONTRACT, { where: { id: acme.id }, ...SYS }))?.[INVOICED]).toBe(40000);
386+
expect(parentWrites.length).toBeGreaterThan(0);
387+
for (const w of parentWrites) expect(w.skipAutomations).toBe(true);
388+
expect(boundCalls).toEqual([]);
389+
});
390+
391+
it('still recomputes a chained roll-up: the account over the contracts it just filled', async () => {
392+
const { engine, firm } = await setUp({ sealed: true });
393+
await engine.syncSchemas();
394+
395+
expect((await engine.findOne(ACCOUNT, { where: { id: firm.id }, ...SYS }))?.[ROLLED]).toBe(40000);
396+
});
397+
398+
it('CONTROL — the operator backfill (os migrate summary-nulls) writes with automations on, as before', async () => {
399+
const { engine, acme, boundCalls, parentWrites, logger } = await setUp({ sealed: false });
400+
// Unsealed: the door's sync walks nothing, so only the operator's run writes.
401+
await engine.syncSchemas();
402+
expect(parentWrites).toEqual([]);
403+
404+
await backfillSummaryNulls(engine, logger, { apply: true, recomputeUndefinedOnEmpty: [`${CONTRACT}.${LAST_INVOICE}`] });
405+
406+
expect((await engine.findOne(CONTRACT, { where: { id: acme.id }, ...SYS }))?.[INVOICED]).toBe(40000);
407+
expect(parentWrites.length).toBeGreaterThan(0);
408+
for (const w of parentWrites) expect(w.skipAutomations).toBeUndefined();
409+
expect(boundCalls).toContain('beforeUpdate');
410+
});
411+
});
412+

‎packages/objectql/src/summary-backfill.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,18 @@ export interface SummaryBackfillOptions {
195195
* exactly the `count`/`sum` backfill it always was.
196196
*/
197197
recomputeUndefinedOnEmpty?: string[];
198+
/**
199+
* [#34096] Write each recomputed parent with `skipAutomations: true` on the
200+
* system context, so its metadata-bound hooks and record-change flows do not
201+
* run (the seed-loader rule: end-state data, not user events). The engine's
202+
* own roll-up recompute is not an automation and still runs, so a parent
203+
* that is itself a child of another roll-up still moves its own parent.
204+
* Set by the install door's walk (`summary-install-materialise.ts`), which
205+
* runs with no operator choosing the moment. Omitted, the write context is
206+
* exactly the bare system context it always was, so `os migrate
207+
* summary-nulls` keeps firing them, at the time the operator picks.
208+
*/
209+
skipAutomations?: boolean;
198210
/** Safety bound on parent rows read per object. */
199211
maxRecordsPerObject?: number;
200212
/** Retry policy for one row's aggregate + update; defaults to the transient
@@ -326,6 +338,9 @@ export async function backfillSummaryNulls(
326338
options: SummaryBackfillOptions = {},
327339
): Promise<SummaryBackfillReport> {
328340
const apply = options.apply === true;
341+
// The parent write's context: the bare system context unless the caller
342+
// asked for automations to stay off (see `skipAutomations`).
343+
const writeCtx = options.skipAutomations === true ? { ...SYSTEM_CTX, skipAutomations: true } : { ...SYSTEM_CTX };
329344
const maxPerObject = options.maxRecordsPerObject ?? 100_000;
330345
const candidates =
331346
options.objects ??
@@ -412,7 +427,7 @@ export async function backfillSummaryNulls(
412427
await engine.update(
413428
desc.parentObject,
414429
{ id: parentId, [desc.summaryField]: computed },
415-
{ context: { ...SYSTEM_CTX } },
430+
{ context: { ...writeCtx } },
416431
);
417432
}, options.retry ?? {});
418433
if (undefinedOnEmpty && computed == null) {

‎packages/objectql/src/summary-install-materialise.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,13 @@
2727
* The install door is the one moment that both knows a summary is new and has
2828
* just created its column, so the values are written there, through
2929
* {@link backfillSummaryNulls}: the same aggregate the engine's own recompute
30-
* uses, the same system context (`{ isSystem: true }`, no tenant — every
31-
* organization's rows), the same `update` verb on the parent, so a parent
32-
* write fires what the child-write recompute's parent write fires and no
33-
* child row is written. Keyset pages of 500, bounded per object.
30+
* uses, a system context with no tenant (every organization's rows), and the
31+
* engine's `update` verb on the parent. No child row is written. The parent
32+
* write carries `skipAutomations: true`, as the door's own seed writes do
33+
* (end-state data, not user events): no metadata-bound hook and no
34+
* record-change flow runs on a backfilled parent, while the engine's own
35+
* roll-up recompute still runs, so a parent that is itself a child of another
36+
* roll-up moves that roll-up too. Keyset pages of 500, bounded per object.
3437
*
3538
* ## Which summaries are new
3639
*
@@ -152,6 +155,11 @@ async function walkAdded(
152155
apply: true,
153156
objects,
154157
recomputeUndefinedOnEmpty: added,
158+
// The door's own writes are end-state data, not user events (its seed
159+
// owner stamp, the seed-loader rule): no metadata-bound hook or
160+
// record-change flow runs on a backfilled parent. The roll-up recompute
161+
// is the engine's, so a chained roll-up still moves.
162+
skipAutomations: true,
155163
});
156164
} catch (err) {
157165
const error = (err as Error)?.message ?? String(err);

0 commit comments

Comments
 (0)