Skip to content

Commit 803f909

Browse files
fix(objectql): compute on stored rows the roll-ups a package install or upgrade adds (#34282)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbKnsd8ZLsq9hBbRRm5JvJb2)_ Fixes #34096 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:包安装/升级(安装门的 `syncSchemas`)现在会在已有记录上计算升级新增的汇总(roll-up)字段,只补仍为 NULL 的行。 - 为什么改:HotCRM 6.2→6.4 升级后,旧合同/客户的已开票、已收款、应收余额一律为空,新建记录却是 0,直到某个子记录被写入才会填上。 - 风险与回滚:只走启动后新出现的汇总字段;启动时已存在的不扫,二次升级零读写。回填写父记录时带 `skipAutomations`,与安装门自己的种子写入一致,不触发父对象的元数据钩子和记录变更流程,但上一层汇总照常重算。失败按 error 记日志并在下次安装时重试。回滚即回退本 PR,已写入的值本就是引擎自己会写的值。 - 先看:`packages/objectql/src/summary-install-materialise.ts`(新增字段判定与失败处理)、`engine-compatibility-api.ts` 的 `syncSchemas` 末尾、`plugin.ts` 的 `kernel:bootstrapped` 封存。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run --project local src/engine-34096-upgrade-added-summary-materialise.test.ts`,预期 10/10 通过。 - 需要你做的:确认"随重启到达的汇总字段(代码应用新版本、热注册失败后重启加载)仍由 `os migrate summary-nulls` 补"这一边界可接受。 ## What changes - **New `packages/objectql/src/summary-install-materialise.ts`.** When the boot completes, the engine records the roll-ups it serves (`ObjectQLPlugin` calls `ObjectQL.sealSummariesMaterialisedAtBoot()` at `kernel:bootstrapped`, after the install-local rehydrate at `kernel:ready`). Later, `ObjectQL.materialiseAddedSummaries()` walks only the roll-ups served now that are not recorded. It fills them through the existing `backfillSummaryNulls` and records them once the walk is complete. - **`ObjectQL.syncSchemas()`** runs it last. That is the sync every runtime install door asks for after its hot register; `MarketplaceInstallLocal` is the measured door. A sync before the boot completes walks nothing, and that includes the rehydrate's sync. - **How the walk writes.** It uses `aggregateSummaryValue`, the child-write recompute's aggregate, and the parent `update` with `{ isSystem: true, skipAutomations: true }` and no tenant, so it covers every organization's rows. `skipAutomations` matches the install door's own seed writes (`SEED_OWNER_STAMP_CTX`, the seed-loader rule: end-state data, not user events), so no metadata-bound hook or record-change flow runs on a backfilled parent. The engine's roll-up recompute is not an automation and still runs, so a roll-up over a backfilled parent moves too. The walk writes no child row. Pages are keyset pages of 500, bounded per object at 100,000. Only rows still `NULL` are written, so the walk is idempotent. - **New opt-in `skipAutomations` on `SummaryBackfillOptions`.** Only `summary-install-materialise.ts` sets it. Without it, the write context is the bare `{ isSystem: true }` it always was, so `os migrate summary-nulls` is unchanged and still runs those automations at the time the operator picks. - **Each new roll-up is named in `recomputeUndefinedOnEmpty`.** The door knows these columns are new, so new `min`/`max`/`avg` columns are computed too. - **Null versus 0, settled.** After the fix, an empty child set reads `0` for `count`/`sum` and `null` for `min`/`max`/`avg`. A pre-existing row and a new row read the same. - **A failed or interrupted walk.** This covers a row that fails, an object that cannot be read, or the per-object bound reached. The engine logs it at `error` once, with the consequence and the exact `os migrate summary-nulls --apply --recompute-undefined-on-empty OBJECT.FIELD` line. It does not record those roll-ups, so the next install's sync in the same process walks them again and fills only what is still `NULL`. - **Why materialise rather than compute on read.** A value computed on read is not the stored column. Filters, sorts, `GROUP BY` and formulas would still read `NULL`, and every list read would pay an aggregate per row. The install door is the one moment that knows the column is new and has just created it. - **Docs:** `content/docs/deployment/cli.mdx` (`os migrate summary-nulls`) says when an install does this and when the command is still owed. - **Changeset:** `@objectstack/objectql` patch. ## Tests New `packages/objectql/src/engine-34096-upgrade-added-summary-materialise.test.ts`, 10 cases: - **v1 → v2 upgrade.** Version 2 adds `sum`/`count`/`max` roll-ups through `objectExtensions` over existing parents and children. Every parent reads the computed value, and no child row is written. A parent with no children reads `0`/`0`/`null`. - A pre-existing parent reads exactly what a new parent with the same children reads. - A second upgrade (v3) that adds no roll-up makes zero driver reads and zero writes. - A roll-up already present when the boot completed is not walked by a later sync. - The parent writes are `isSystem` with no `tenantId`, and no hook of the child object fires. - A failed row leaves the walk unrecorded and logs once at `error`, naming the roll-up and the command. The next sync rewrites only that row. - A real `ObjectKernel` boot with `ObjectQLPlugin` seals at `kernel:bootstrapped`, then the upgrade fills. - Each backfilled parent's write carries `skipAutomations: true`, and a metadata-bound parent update hook (bound through `bindHooks`) does not fire. - A chained roll-up still recomputes: an account roll-up over the contracts' new `invoiced_amount` reads 40000 after the walk. - CONTROL: the operator path (`backfillSummaryNulls` with no option) writes without `skipAutomations`, and the bound hook fires as before. <details><summary>Red first, green on the fix, objectql full suite</summary> - Red, test file only, on the code of main: `Tests 4 failed | 2 passed (6)`, `AssertionError: expected null to be 700`. The two that pass there are the "runs nothing" pins, which nothing on main can violate. - Round 1, green at 71f012a, before the three S1 cases were added: `Test Files 1 passed (1)`, `Tests 7 passed (7)`. The file now holds 10 cases; see the S1 lines below. - `pnpm --filter @objectstack/objectql exec vitest run --project local --maxWorkers=2` at 71f012a: `Test Files 599 passed (599)`, `Tests 13287 passed (13287)`, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/objectql build && pnpm --filter @objectstack/objectql typecheck`: exit 0, and `check:test-typecheck: OK`. - The round-1 head 2d39431 added only the docs commit after 71f012a. - Review S1 (skipAutomations on the install walk), head c6ff87c: - Red first, with the new pins against the e3a4385 code: `Tests 1 failed | 9 passed (10)`, `AssertionError: expected undefined to be true`. The parent write carried no `skipAutomations`. The chained-roll-up and CONTROL pins pass there, as they should. - Green: this file plus `summary-backfill.test.ts` gives `Test Files 2 passed (2)`, `Tests 30 passed (30)`. - These single-file runs ran outside the shared verify lock, as a declared narrowing, because the lock queue was held by a long dogfood run for about 30 minutes. - `pnpm --filter @objectstack/objectql build && pnpm --filter @objectstack/objectql typecheck` under the lock: exit 0, and `check:test-typecheck: OK`. - `pnpm --filter @objectstack/objectql exec vitest run --project local --maxWorkers=2` under the lock at c6ff87c: `Test Files 599 passed (599)`, `Tests 13331 passed (13331)`, `VERDICT command-exit 0`. </details> <details><summary>Ablations (each mutated through scripts/ablation-replace.mjs, restored with git checkout HEAD and checked by blob hash)</summary> - A1: drop `await this.materialiseAddedSummaries()` from `syncSchemas` → 4 failed. Restored, blob 9844dc3 == HEAD. - A2: drop `recomputeUndefinedOnEmpty: added` → 3 failed (the `max` column stays null). Restored. - A3: never record a completed walk → 1 failed: the second upgrade re-walks. Restored. - A4: the boot seal records nothing → 1 failed: a boot-present roll-up is walked. Restored. - A5: treat an incomplete walk as complete → 1 failed: the failed row is never retried. Restored. - A6: drop the plugin's `sealSummariesMaterialisedAtBoot()` call → 1 failed (the real-kernel case). Restored, blob d5b497b == HEAD. - A7 (S1): drop `skipAutomations: true` from the install walk → 1 failed (the skipAutomations / bound-hook pin). Restored, blob a3b8467 == HEAD. The subject resolves to `src/` through relative imports, so no dist preflight applies. </details> ## Acceptance notes - **Boundary: a roll-up that arrives with a restart rather than through an install door is not walked.** That 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, because a boot cannot tell "new since the last version" from "already computed" without a persisted record. `os migrate summary-nulls --apply` remains the backfill there. The changeset and the CLI docs say so. - **A process that dies mid-walk** records nothing. Its next boot seals what it serves, so the operator command is the re-run there. - **Authored-package publish.** The single-object publish door (`syncObjectSchema`, `protocol.installPackage`) is not wired. A batch publish can sync a parent before its new child table exists, and the walk would then log a false failure. Left for a decision, not guessed. - **Automations stay off on a backfilled parent.** A field that a parent's own update hook derives from a new roll-up is therefore not refreshed by the install. It fills at that row's next ordinary write, or when `os migrate summary-nulls` is run by hand. The changeset states the same rule. - **Review N2 is an accepted nit, not pushed.** It asks for that consequence as one more sentence in `cli.mdx`. The head c6ff87c is green and holds a PASS record, and the note above and the changeset already carry the rule, so a docs-only push would only restart review. - **Uninstall then reinstall.** The recorded set only grows, so a reinstall does not re-walk a roll-up this process already recorded. ## Verification <details><summary>Derived gate union at c6ff87c: dispatch-gates --commands, 106 families</summary> - 101 exited 0. - 5 exited 3, PREREQUISITE NOT MET, because this worktree's install was filtered to the objectql closure: `check:type-check-debt`, `check:dual-build-cjs-loads`, `check:doc-frontmatter` (no `apps/docs` install), `spec check:skill-examples`, and `check:lean-entry-closure` (objectql's dist was not yet rebuilt when it ran). NOT MEASURED locally; CI measures them. - The derivation flagged its tree as stale: 17 commits behind origin/main, and one derived-from script changed there (`scripts/check-facade-delegation-only.mjs`). CI runs the current script. - Gates that read the touched files, all exit 0: `check:test-source-alias`, `check:facade-delegation-only`, `check:durability-log-level`, `check:system-context-census`, `check:dts-closure`, `check:doc-authoring`, `check:nul-bytes`, `check:changeset-no-major`, `check:adr-0087-registration`. - CI check-runs on c6ff87c: 38 success, 15 skipped. </details> Not run locally, and declared to CI: `test:repo`, and the consumer suites of `syncSchemas` (`@objectstack/cloud-connection`; none of its tests declares a summary field). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- signed: domain:server#5 · zhuangjianguo · session_01QsR2jUg7BKfRBcTPyMxbLh --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7d06248 commit 803f909

9 files changed

Lines changed: 715 additions & 2 deletions
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
fix(objectql): a roll-up summary field that a package install or upgrade adds is computed on the rows stored before it
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: none
9+
10+
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.
11+
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`.
13+
14+
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.
15+
16+
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.
17+
18+
New engine members: `ObjectQL.materialiseAddedSummaries()` (re-run it after clearing a logged failure) and `ObjectQL.sealSummariesMaterialisedAtBoot()`, which the ObjectQL plugin calls.

‎content/docs/deployment/cli.mdx‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1679,6 +1679,29 @@ name that is not a roll-up this run walks — a typo, a plain field, or an objec
16791679
`sum` is accepted and changes nothing, so a caller can pass every column it
16801680
just declared.
16811681
1682+
**A package install or upgrade does this for you.** When a running deployment
1683+
installs or upgrades a package through an install door (the marketplace
1684+
install, for example), the door's schema sync computes every roll-up the
1685+
package added, on each stored row still holding `NULL`. It uses the aggregate
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
1691+
included, because the door knows those columns are new. Roll-ups the deployment
1692+
already served when it booted are not walked again, so an upgrade that adds no
1693+
roll-up costs nothing here. Two cases still need this command:
1694+
1695+
- **The walk did not complete.** A row failed, an object could not be read, or
1696+
the per-object bound was reached. The server logs it at `error`, naming each
1697+
roll-up, and gives the exact
1698+
`os migrate summary-nulls --apply --recompute-undefined-on-empty …` line.
1699+
The next install in the same process also walks those roll-ups again.
1700+
- **The roll-up arrived with a restart, not through an install door.** This
1701+
covers a code-defined app's new version and a marketplace install whose hot
1702+
register failed and loaded at the next restart. A boot records what it serves
1703+
and computes nothing.
1704+
16821705
Idempotent — every write turns a `NULL` into a number, so a second run finds
16831706
nothing and writes nothing. Re-running until the report says zero *is* the
16841707
verification, which is why this command records no flag: it repairs values and

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

Lines changed: 412 additions & 0 deletions
Large diffs are not rendered by default.

‎packages/objectql/src/engine-compatibility-api.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,8 @@ export interface CompatibilityApiHost {
7171
readonly logger: ObjectQL['logger'];
7272
getDriverForObject: ObjectQL['getDriverForObject'];
7373
removeActionsByPackage: ObjectQL['removeActionsByPackage'];
74+
/** [#34096] The roll-ups an install added, computed on the stored rows. */
75+
materialiseAddedSummaries: ObjectQL['materialiseAddedSummaries'];
7476
}
7577

7678
/** The body of `ObjectQL#registerObject`; the method's docblock there is its contract. */
@@ -120,7 +122,7 @@ export async function introspectDatasource(
120122

121123
/** The body of `ObjectQL#syncSchemas`; the method's docblock there is its contract. */
122124
export async function syncSchemas(
123-
this: Pick<CompatibilityApiHost, '_registry' | 'getDriverForObject' | 'logger'>,
125+
this: Pick<CompatibilityApiHost, '_registry' | 'getDriverForObject' | 'logger' | 'materialiseAddedSummaries'>,
124126
): Promise<void> {
125127
// The storage layer's objects: a disabled package's extensions folded in,
126128
// so the DDL keeps their columns (`SchemaRegistry.getStorageObject`).
@@ -187,6 +189,12 @@ export async function syncSchemas(
187189
}
188190
}
189191
}
192+
// [#34096] Every runtime caller of this sync is an install door, after its
193+
// hot register: a roll-up the install added now has its column on every
194+
// stored row, NULL. Compute it there, as the child-write recompute would
195+
// (`summary-install-materialise.ts`); a roll-up the boot already served is
196+
// not walked, and a sync before the boot completes walks nothing.
197+
await this.materialiseAddedSummaries();
190198
}
191199

192200
/** The body of `ObjectQL#syncObjectSchema`; the method's docblock there is its contract. */

‎packages/objectql/src/engine.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ import {
146146
type SummaryDescriptor,
147147
} from './summary-aggregate.js';
148148
import { refreshSummariesExtendedBy, summaryRefreshesSettled, type SummaryEnableRefreshReport } from './summary-enable-refresh.js';
149+
import { materialiseSummariesAddedSinceBoot, sealSummariesMaterialisedAtBoot, type SummaryMaterialiseOutcome } from './summary-install-materialise.js';
149150
import {
150151
DriverConnectError,
151152
DatasourceUnavailableError,
@@ -4101,6 +4102,29 @@ export class ObjectQL implements IObjectQLEngine {
41014102
return refreshSummariesExtendedBy(this, this.logger, packageId);
41024103
}
41034104

4105+
/**
4106+
* [#34096] Record the roll-up `summary` fields served at the end of the
4107+
* boot as the ones the stored rows were computed for. `ObjectQLPlugin` calls
4108+
* it at `kernel:bootstrapped`; until then {@link materialiseAddedSummaries}
4109+
* walks nothing. Returns how many roll-ups are recorded.
4110+
*/
4111+
sealSummariesMaterialisedAtBoot(): number {
4112+
return sealSummariesMaterialisedAtBoot(this);
4113+
}
4114+
4115+
/**
4116+
* [#34096] Compute, on every stored row still `NULL` there, the roll-up
4117+
* `summary` fields served now that the boot did not record — the ones a
4118+
* package install or upgrade added — through the child-write recompute's own
4119+
* aggregate and system-context `update`, then record them. {@link syncSchemas}
4120+
* runs it, so every install door's sync does. Never throws: an incomplete
4121+
* walk is logged at `error`, left unrecorded, and walked again by the next
4122+
* call (`summary-install-materialise.ts`).
4123+
*/
4124+
materialiseAddedSummaries(): Promise<SummaryMaterialiseOutcome> {
4125+
return materialiseSummariesAddedSinceBoot(this, this.logger);
4126+
}
4127+
41044128
/** [#30377] Resolves once the summary recomputes the enables so far started ({@link refreshSummariesEnabledBy}) have settled, so a door can answer after them. */
41054129
summaryRefreshSettled(): Promise<void> {
41064130
return summaryRefreshesSettled(this);
@@ -5565,6 +5589,7 @@ export class ObjectQL implements IObjectQLEngine {
55655589
const readLogger = () => this.logger;
55665590
const host: ThisParameterType<typeof syncSchemas> = {
55675591
getDriverForObject: (...a) => this.getDriverForObject(...a),
5592+
materialiseAddedSummaries: () => this.materialiseAddedSummaries(),
55685593
get _registry() { return readRegistry(); },
55695594
get logger() { return readLogger(); },
55705595
};

‎packages/objectql/src/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,9 @@ export type {
633633
SummaryBackfillLogger,
634634
SummaryBackfillOptions,
635635
} from './summary-backfill.js';
636+
// [#34096] What `ObjectQL.materialiseAddedSummaries` (run by every install
637+
// door's `syncSchemas`) did with the roll-ups an install or upgrade added.
638+
export type { SummaryMaterialiseOutcome } from './summary-install-materialise.js';
636639
// [#29961] The backfill behind `os migrate stored-expressions`: stored computed
637640
// fields over rows no write has computed since the field was declared, and the
638641
// boot advisory naming it. Same split as the roll-up backfill above.

‎packages/objectql/src/plugin.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1382,6 +1382,12 @@ export class ObjectQLPlugin implements Plugin {
13821382
// hooks: there the doors never refuse.
13831383
const registry = this.ql?.registry;
13841384
if (registry) sealBareNameHoldersAtColdBoot(registry, BARE_NAME_COLD_BOOT_MODE, ctx.logger);
1385+
// [#34096] The same moment, for roll-ups: every package of this boot
1386+
// is registered and schema sync has run, so the roll-ups served now are
1387+
// the ones the stored rows were computed for. From here on an install
1388+
// door's `syncSchemas` computes, on the stored rows, the roll-ups an
1389+
// install or upgrade adds (`summary-install-materialise.ts`).
1390+
this.ql?.sealSummariesMaterialisedAtBoot();
13851391
// [ADR-0150 D8 row R4] With the holders sealed, bind every activation
13861392
// ledger row that names no package to the one package that holds its
13871393
// item, and report the rows two packages hold (never guessed). Writes

‎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) {

0 commit comments

Comments
 (0)