Skip to content
Merged
18 changes: 18 additions & 0 deletions .changeset/34096-upgrade-added-summary-materialise.md
Original file line number Diff line number Diff line change
@@ -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 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.

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.
23 changes: 23 additions & 0 deletions content/docs/deployment/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -1679,6 +1679,29 @@ 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
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:

- **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
Expand Down

Large diffs are not rendered by default.

10 changes: 9 additions & 1 deletion packages/objectql/src/engine-compatibility-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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<CompatibilityApiHost, '_registry' | 'getDriverForObject' | 'logger'>,
this: Pick<CompatibilityApiHost, '_registry' | 'getDriverForObject' | 'logger' | 'materialiseAddedSummaries'>,
): Promise<void> {
// The storage layer's objects: a disabled package's extensions folded in,
// so the DDL keeps their columns (`SchemaRegistry.getStorageObject`).
Expand Down Expand Up @@ -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. */
Expand Down
25 changes: 25 additions & 0 deletions packages/objectql/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,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,
Expand Down Expand Up @@ -4101,6 +4102,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<SummaryMaterialiseOutcome> {
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<void> {
return summaryRefreshesSettled(this);
Expand Down Expand Up @@ -5565,6 +5589,7 @@ export class ObjectQL implements IObjectQLEngine {
const readLogger = () => this.logger;
const host: ThisParameterType<typeof syncSchemas> = {
getDriverForObject: (...a) => this.getDriverForObject(...a),
materialiseAddedSummaries: () => this.materialiseAddedSummaries(),
get _registry() { return readRegistry(); },
get logger() { return readLogger(); },
};
Expand Down
3 changes: 3 additions & 0 deletions packages/objectql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions packages/objectql/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,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
Expand Down
17 changes: 16 additions & 1 deletion packages/objectql/src/summary-backfill.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -326,6 +338,9 @@ export async function backfillSummaryNulls(
options: SummaryBackfillOptions = {},
): Promise<SummaryBackfillReport> {
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 ??
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading