Skip to content

Commit 7b80724

Browse files
fix(objectql): recompute a disabled package's extension roll-ups when it is enabled again (#30587)
<!-- claude-projects-attribution: {"github_login":"os-bill"} --> _Requested by **Bill** · [project thread](https://claude.ai/code/project/chan_016iMXWSZDzqWRWvWzdNo8wg?thread=cmsg_016iMXWSZDzqWRWvWzdNo8wg2u15WkFyGtun9mJtYPTkdg)_ domain:server#4 · os-bill · session_01Utp6CZMkHvuDeVYgTD73qF ## 维护者速读 - 改了什么:一个模块用扩展给别的模块的对象加了汇总字段(例如给客户加「拜访金额合计」),汇总的子记录属于仍启用的应用。模块停用期间子记录照常写入,但汇总不重算;现在模块重新启用时会把这些汇总按每条父记录重算一遍,只改值不一致的行。 - 为什么改:#30377。PR #30362 停用时隐藏模块加的字段,汇总索引也跟着少了这个汇总,于是重新启用后汇总显示停用那一刻的旧值,直到下一次子记录写入。 - 风险与回滚:启用接口(`PATCH /packages/:id/enable`、安装时 `enableOnInstall: true`)现在等重算完成再回答,父记录多时启用会变慢;某行重算失败只记 error 日志,不让启用失败。回滚即还原本 PR。 - 先看:`packages/objectql/src/summary-enable-refresh.ts`(整文件,重算逻辑);`packages/objectql/src/registry.ts` 的 `enablePackage` 与新 `onPackageEnabled`;`packages/runtime/src/domains/packages.ts` 两处 `await summaryRefreshSettled(qlService)`。 - 两分钟验证:`pnpm --filter @objectstack/objectql exec vitest run --maxWorkers=2 src/engine-summary-disabled-extension-reenable.test.ts`,预期 4 个全绿(第一个用例停用期间写子记录,启用后汇总读到 25 而不是 10)。 - 需要你做的:无,席位落地。 Fixes #30377 Clause-②: no — a stored summary column stays current across a disable; nothing a caller sends is refused Metadata-protocol: none ## What changes While a package is disabled, the `summary` fields its `objectExtensions` add to another package's object are withheld from the served fold (#30304), and `ObjectQL.buildSummaryIndex` reads that fold, so the summary is not in the roll-up index. When the summary's child belongs to an enabled package, the child writes made during the disable land and recompute nothing. After the enable the parent serves the value the summary held at the disable, until a child write names it. **Route chosen: recompute the withheld summaries on enable** (the card's second option), not an index over the storage fold. Why: - The recompute writes the parent through `ObjectQL.update`, whose field map is the served fold. A withheld column is refused there as an unknown field (`INVALID_FIELD`), by #30304's design. An index over the storage fold would turn each such child write into a `SummaryRecomputeError` (a 500 on a committed write), unless the write path grew a second, storage-level door for one kind of column. - The column is not served while its package is disabled, so nothing reads it stale before the enable. Recomputing it at the enable makes it current at the first moment it is served again, through the one write path and the one aggregate (`aggregateSummaryValue`) the engine already uses. Changes: - `registry.ts`: new `SchemaRegistry.onPackageEnabled(listener)`, announced by `enablePackage` only when the package was disabled (never for an enable of an enabled package, e.g. a fresh `enableOnInstall: true`). Same shape as `onPackageUninstalled` (#30215): one signal for every enable door, never per door; a throwing listener is logged at `error` and never fails the enable. - `summary-enable-refresh.ts` (new): `refreshSummariesExtendedBy` takes the roll-ups the package adds by extension (`getObjectExtensionsOf`, matched to the engine's own `getOwnedSummaryDescriptors` index), walks every parent row in keyset order, recomputes each one with `aggregateSummaryValue`, and updates a row only where a value differs (an enable over unchanged children writes nothing). A failed row is recorded and the walk goes on; failures are logged once at `error` with consequence and fix. `startSummaryRefreshOnEnable` is the listener (tracks the run, never rejects); `summaryRefreshesSettled` waits for the runs in flight. - `registry-module-mock.ts`: the shared registry double answers `onPackageEnabled` (the engine's constructor subscribes; the double never enables a disabled package, so it never announces). - `engine.ts`: the constructor subscribes the listener; two public delegations: `refreshSummariesEnabledBy(packageId)` (the operator's re-run after a logged failure) and `summaryRefreshSettled()`. - `runtime/src/domains/packages.ts`: `PATCH /packages/:id/enable` and the install door's `enableOnInstall: true` arm answer after `summaryRefreshSettled()`, so the first read after the answer serves current values. An engine without the member (a test double) answers at once, as before. Only summaries added **by extension** are walked. A summary on an object the disabled package OWNS stays in the index during the disable (its objects are refused on the data plane, not withheld from the fold) and kept tracking an enabled child; measured with a probe before writing this (the parent read 7 during the disable after a child write of 4 over 3). ## Tests - `packages/objectql/src/engine-summary-disabled-extension-reenable.test.ts` (new): the card's scenario (module B extends app A's parent with a `sum` over A's child; disable B; insert, update and insert children of two parents; enable B; the parents read 25 and 7 with no further child write); an enable with no child moved writes no parent row; one parent's failing recompute leaves the others current, logs one `[summary-refresh]` line at `error` naming the row, and `refreshSummariesEnabledBy` re-runs it; `onPackageEnabled` fires for a disabled-to-enabled switch only, and not after unsubscribe. - `packages/runtime/src/domains/packages-disable-module-extension-fields.test.ts`: new describe through the real routes on SQLite (`PATCH /packages/:id/disable`, `/data` writes of the app's child, one under a parent created during the disable, `PATCH /packages/:id/enable`, `GET /data`), with a third module added only for that describe (`suiteArtifact(…, withRollup)`). #30304's own case (child in the same disabled module) is unchanged and still green. ## Acceptance notes - **Second item of seat note 6654197160 (`os migrate` value-rewrite commands under `packages/cli/src/commands/migrate/` scope by the served fold): follow-up owed.** Not the same package (`packages/cli`), and the smallest honest answer the note names (the plan names the columns it skipped, or the run refuses while an extending module is disabled) is a CLI output change, while switching the reads to the storage fold needs engine support (`engine.find` refuses a withheld field by design). Not taken here. - The enable doors now wait for the walk: its cost is one aggregate per parent row of each extending roll-up (keyset pages of 500). A deployment with a very large parent table pays that once per enable. - The refresh runs on the `onPackageEnabled` signal, so a package that comes back enabled WITHOUT an enable (a state file edited or removed between two boots) gets no refresh; its summaries correct on the next child write, as before this PR. The protocol's install door (`metadata-protocol`, `enablePackage` on install) gets the refresh too, but answers without waiting for it. - The walk reads and writes as system (`{ isSystem: true }`), the context `backfillSummaryNulls` (#6063) already uses for the same aggregate. ## Verification All on head `4ca13802` (origin/main `35a8f088` merged once; main has moved since and `git merge-tree` against it is clean). <details><summary>Red on main, green on the fix, two ablations</summary> - Red on main `8e5fabe5` (the new objectql pin, tests only): `AssertionError: expected 10 to be 25` — the parent serves the value it held at the disable. - Green: `engine-summary-disabled-extension-reenable.test.ts` 4/4; `packages-disable-module-extension-fields.test.ts` 12/12 (the new describe plus #30304's own cases unchanged). - Ablation 1, the engine's subscription (`scripts/ablation-replace.mjs --delete` of the `this._registry.onPackageEnabled(…)` line in `engine.ts`; the objectql suite imports `src/`, no build between): anchor 1 to 0, blob `09031204d5df` to `0e83c65fd80e`; `Tests 2 failed | 2 passed (4)` (`expected 10 to be 25`, `expected +0 to be 7`; the no-write control and the registry case stay green, as predicted); restored, blob equals HEAD, `git diff HEAD` empty. - Ablation 2, the door's wait (`--delete` of `await summaryRefreshSettled(qlService);` in the `PATCH /packages/:id/enable` arm; the runtime suite imports the dispatcher from `src/`): anchor 1 to 0, blob `8d43ff30f3e1` to `ae9427714d6b`; `Tests 1 failed | 11 passed (12)`, the new describe reads the pre-recompute row; restored, blob equals HEAD, `git diff HEAD` empty. So the answer-after-recompute is pinned, not only the recompute. </details> <details><summary>Package suites, typecheck, lint, gates</summary> - `pnpm --filter @objectstack/objectql test` under the verify lock: `Test Files 553 passed (553)` · `Tests 11009 passed (11009)` · `VERDICT command-exit 0`. (A first run before the registry double gained `onPackageEnabled` was red in 19 files that mock `./registry`; that is the `registry-module-mock.ts` change.) - `pnpm --filter @objectstack/runtime test`: `Test Files 543 passed (543)` · `Tests 8656 passed | 19 skipped (8675)`. - `pnpm --filter @objectstack/objectql run typecheck` and `@objectstack/runtime`: exit 0, test layers included (`check:test-typecheck: OK`, ledgers unchanged). - `eslint --no-inline-config` on the seven changed source and test files: exit 0. The repo-wide `pnpm lint` is CI's Lint job. - `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on `4ca13802`: 63 commands, each run with its exit code captured before any pipe, plus `check:facade-delegation-only`, `check:error-code-casing`, `check:route-ledger-census`, `check:filter-alias-parity`, `check:authz-resolver`, `check:changeset-fixed` (rosters under the touched trees): all exit 0. `--ran`: `63 derived, 62 run, 1 NOT-MEASURED, 0 UNRUN`; the one is `node scripts/check-plugin-teardown-shape.mjs --self-test` (exit 3, needs an unshallow clone; checker health only), which CI runs. - Fixed on the way: `check:objectql-double-limit` (the new `find` double now slices by `limit` before touching rows) and `check:query-options-erasure` (no `as any` on the new test's query options). - Dogfood battery: n/a, no `!` in the title and no `(narrowing)` arm. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6Cb5eUJ2R5ZJdA6U46A)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 55d9dd4 commit 7b80724

8 files changed

Lines changed: 610 additions & 6 deletions
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/objectql': patch
3+
'@objectstack/runtime': patch
4+
---
5+
6+
fix(objectql): a roll-up summary a disabled package adds by extension is recomputed when the package is enabled again
7+
8+
Clause-②: no — a stored summary column stays current across a disable; nothing a caller sends is refused
9+
Metadata-protocol: none
10+
11+
- **Before.** While a package was disabled, the `summary` fields its `objectExtensions` add to another package's object were withheld from the roll-up index with the rest of the served fold. When the summary's child belongs to an enabled package, the child writes made during the disable landed and recomputed nothing, so after `PATCH /packages/:id/enable` the parent served the value the summary held at the disable, until the next write of one of its children.
12+
- **Now.** Enabling a disabled package recomputes, on every parent row, the roll-ups it adds by extension, and writes a row only where its stored value differs. It runs on every enable door (`SchemaRegistry.onPackageEnabled`, new), and `PATCH /packages/:id/enable` (and an install's `enableOnInstall: true`) answers after it has settled. A row that cannot be recomputed is logged at `error` and the rest of the walk goes on; `ObjectQL.refreshSummariesEnabledBy(packageId)` (new) re-runs it.
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#30377] A roll-up summary a package contributes BY EXTENSION, over a child
5+
* of an ENABLED package, is current again the moment its package is
6+
* re-enabled.
7+
*
8+
* While a package is disabled its `objectExtensions` fields are withheld from
9+
* the served object fold (#30304), so the roll-up index — built from that fold
10+
* — does not hold the package's summary, and the child writes made during the
11+
* disable recompute nothing. The child here belongs to the enabled app, so
12+
* those writes land; the stored summary column keeps the value it had when the
13+
* package was switched off. Re-enabling serves the field again, so without a
14+
* recompute it serves that stale value until the next write of a child.
15+
*/
16+
17+
import { describe, it, expect, beforeEach, vi } from 'vitest';
18+
import { ObjectQL } from './engine.js';
19+
20+
function makeDriver() {
21+
const stores = new Map<string, Map<string, any>>();
22+
const storeFor = (o: string) => {
23+
let s = stores.get(o);
24+
if (!s) { s = new Map(); stores.set(o, s); }
25+
return s;
26+
};
27+
const checkOp = (value: any, cond: any): boolean => {
28+
if (cond === null || typeof cond !== 'object' || Array.isArray(cond) || cond instanceof Date) return value === cond;
29+
return Object.entries(cond).every(([op, target]: [string, any]) => {
30+
switch (op) {
31+
case '$eq': return value === target;
32+
case '$ne': return value !== target;
33+
case '$gt': return value > target;
34+
case '$gte': return value >= target;
35+
case '$lt': return value < target;
36+
case '$lte': return value <= target;
37+
case '$in': return Array.isArray(target) && target.includes(value);
38+
case '$nin': return Array.isArray(target) && !target.includes(value);
39+
default: return true;
40+
}
41+
});
42+
};
43+
const matches = (row: any, where: any): boolean => {
44+
if (!where || typeof where !== 'object') return true;
45+
return Object.entries(where).every(([k, v]: [string, any]) => {
46+
if (k === '$and') return (v as any[]).every((w) => matches(row, w));
47+
if (k === '$or') return (v as any[]).some((w) => matches(row, w));
48+
if (k === '$not') return !matches(row, v);
49+
return checkOp(row?.[k], v);
50+
});
51+
};
52+
let n = 0;
53+
/** Parent-row writes, by object, so a case can count them. */
54+
const updates: Array<{ object: string; id: string; data: Record<string, unknown> }> = [];
55+
/** Ids whose next `update` throws, to drive a recompute failure. */
56+
const failUpdateOf = new Set<string>();
57+
const driver: any = {
58+
name: 'memory', version: '0.0.0', supports: {},
59+
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
60+
async find(object: string, ast: any) {
61+
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
62+
const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
63+
return page.map((r) => ({ ...r }));
64+
},
65+
async findOne(object: string, ast: any) {
66+
for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r };
67+
return null;
68+
},
69+
async create(object: string, data: Record<string, unknown>) {
70+
n += 1;
71+
const id = (data.id as string) ?? `r_${n}`;
72+
const row = { ...data, id };
73+
storeFor(object).set(id, row);
74+
return { ...row };
75+
},
76+
async update(object: string, id: string, data: Record<string, unknown>) {
77+
if (failUpdateOf.has(id)) throw new Error(`fake driver: update of ${id} refused`);
78+
updates.push({ object, id, data });
79+
const s = storeFor(object);
80+
const row = { ...s.get(id), ...data, id };
81+
s.set(id, row);
82+
return { ...row };
83+
},
84+
async updateMany(object: string, ast: any, data: Record<string, unknown>) {
85+
const s = storeFor(object);
86+
let count = 0;
87+
for (const [id, r] of Array.from(s.entries())) if (matches(r, ast?.where)) { s.set(id, { ...r, ...data, id }); count += 1; }
88+
return count;
89+
},
90+
async delete(object: string, id: string) { return storeFor(object).delete(id); },
91+
async deleteMany(object: string, ast: any) {
92+
const s = storeFor(object);
93+
let count = 0;
94+
for (const [id, r] of Array.from(s.entries())) if (matches(r, ast?.where)) { s.delete(id); count += 1; }
95+
return count;
96+
},
97+
async count() { return 0; },
98+
async bulkCreate(object: string, rows: Record<string, unknown>[]) { return Promise.all(rows.map((r) => this.create(object, r))); },
99+
async bulkUpdate() { return []; }, async bulkDelete() {},
100+
async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; },
101+
async commit() {}, async rollback() {},
102+
};
103+
return { driver, storeFor, updates, failUpdateOf };
104+
}
105+
106+
const APP = 'com.qa.rollup.app';
107+
const MODULE = 'com.qa.rollup.notes';
108+
const ACCOUNT = 'qr_account';
109+
const NOTE = 'qr_note';
110+
const TOTAL = 'qr_note_total';
111+
112+
const manifest = (id: string, type: string) =>
113+
({ id, name: id, version: '1.0.0', type, namespace: 'qr', ...(type === 'module' ? { dependencies: { [APP]: '^1.0.0' } } : {}) }) as any;
114+
115+
describe('a roll-up a disabled package contributes by extension, over an enabled package\'s child', () => {
116+
let engine: ObjectQL;
117+
let storeFor: ReturnType<typeof makeDriver>['storeFor'];
118+
let driver: ReturnType<typeof makeDriver>;
119+
let logger: Record<'debug' | 'info' | 'warn' | 'error', ReturnType<typeof vi.fn>> & Record<string, unknown>;
120+
121+
beforeEach(async () => {
122+
logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), trace: vi.fn(), fatal: vi.fn() };
123+
logger.child = () => logger;
124+
engine = new ObjectQL({ logger });
125+
const d = makeDriver();
126+
driver = d;
127+
storeFor = d.storeFor;
128+
engine.registerDriver(d.driver, true);
129+
await engine.init();
130+
const registry = engine.registry;
131+
registry.installPackage(manifest(APP, 'app'), 'code');
132+
registry.installPackage(manifest(MODULE, 'module'), 'code');
133+
// The app owns both the parent and the child.
134+
registry.registerObject({
135+
name: ACCOUNT, label: 'Account',
136+
fields: { name: { name: 'name', type: 'text', label: 'Name' } },
137+
} as any, APP, 'qr', 'own');
138+
registry.registerObject({
139+
name: NOTE, label: 'Note',
140+
fields: {
141+
amount: { name: 'amount', type: 'number', label: 'Amount' },
142+
account: { name: 'account', type: 'lookup', label: 'Account', reference: ACCOUNT },
143+
},
144+
} as any, APP, 'qr', 'own');
145+
// The module adds the roll-up to the app's parent, by extension.
146+
registry.registerObject({
147+
name: ACCOUNT,
148+
fields: {
149+
[TOTAL]: { name: TOTAL, type: 'summary', label: 'Note total', summaryOperations: { object: NOTE, field: 'amount', function: 'sum' } },
150+
},
151+
} as any, MODULE, 'qr', 'extend');
152+
});
153+
154+
const stored = (id: string) => storeFor(ACCOUNT).get(id)?.[TOTAL];
155+
156+
it('is current after re-enable, with no further child write', async () => {
157+
const acme = await engine.insert(ACCOUNT, { name: 'acme' });
158+
const beta = await engine.insert(ACCOUNT, { name: 'beta' });
159+
const first = await engine.insert(NOTE, { account: acme.id, amount: 10 });
160+
expect(stored(acme.id), 'precondition: the roll-up tracks while the module is enabled').toBe(10);
161+
162+
engine.registry.disablePackage(MODULE);
163+
// The child belongs to the enabled app: its writes land during the disable.
164+
await engine.insert(NOTE, { account: acme.id, amount: 5 });
165+
await engine.update(NOTE, { id: first.id, amount: 20 });
166+
await engine.insert(NOTE, { account: beta.id, amount: 7 });
167+
168+
engine.registry.enablePackage(MODULE);
169+
await engine.summaryRefreshSettled();
170+
171+
const served = await engine.findOne(ACCOUNT, { where: { id: acme.id }, context: { isSystem: true } });
172+
expect(served?.[TOTAL]).toBe(25);
173+
expect(stored(beta.id)).toBe(7);
174+
});
175+
176+
it('writes no parent row on an enable when no child moved during the disable', async () => {
177+
const acme = await engine.insert(ACCOUNT, { name: 'acme' });
178+
await engine.insert(NOTE, { account: acme.id, amount: 10 });
179+
engine.registry.disablePackage(MODULE);
180+
driver.updates.length = 0;
181+
182+
engine.registry.enablePackage(MODULE);
183+
await engine.summaryRefreshSettled();
184+
185+
expect(driver.updates.filter((u) => u.object === ACCOUNT)).toEqual([]);
186+
expect(stored(acme.id)).toBe(10);
187+
});
188+
189+
it('brings every other parent current when one parent\'s recompute fails, and says so at error', async () => {
190+
const acme = await engine.insert(ACCOUNT, { name: 'acme' });
191+
const beta = await engine.insert(ACCOUNT, { name: 'beta' });
192+
engine.registry.disablePackage(MODULE);
193+
await engine.insert(NOTE, { account: acme.id, amount: 5 });
194+
await engine.insert(NOTE, { account: beta.id, amount: 7 });
195+
driver.failUpdateOf.add(acme.id);
196+
197+
engine.registry.enablePackage(MODULE);
198+
await engine.summaryRefreshSettled();
199+
200+
expect(stored(beta.id)).toBe(7);
201+
expect(stored(acme.id)).toBe(0);
202+
const said = logger.error.mock.calls.map((c) => String(c[0])).filter((m) => m.startsWith('[summary-refresh]'));
203+
expect(said).toHaveLength(1);
204+
expect(said[0]).toContain(`${ACCOUNT}/${acme.id}`);
205+
// The operator's re-run, once the cause is cleared.
206+
driver.failUpdateOf.clear();
207+
const report = await engine.refreshSummariesEnabledBy(MODULE);
208+
expect(report.failures).toEqual([]);
209+
expect(stored(acme.id)).toBe(5);
210+
});
211+
});
212+
213+
describe('SchemaRegistry.onPackageEnabled', () => {
214+
it('announces an enable of a disabled package, and not one of a package already enabled', () => {
215+
const engine = new ObjectQL();
216+
const registry = engine.registry;
217+
registry.installPackage(manifest(APP, 'app'), 'code');
218+
const heard: string[] = [];
219+
const stop = registry.onPackageEnabled((id) => { heard.push(id); });
220+
221+
registry.enablePackage(APP);
222+
expect(heard).toEqual([]);
223+
registry.disablePackage(APP);
224+
registry.enablePackage(APP);
225+
expect(heard).toEqual([APP]);
226+
stop();
227+
registry.disablePackage(APP);
228+
registry.enablePackage(APP);
229+
expect(heard).toEqual([APP]);
230+
});
231+
});

‎packages/objectql/src/engine.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ import {
150150
withoutDeletedSelfParents,
151151
type SummaryDescriptor,
152152
} from './summary-aggregate.js';
153+
import { refreshSummariesExtendedBy, startSummaryRefreshOnEnable, summaryRefreshesSettled, type SummaryEnableRefreshReport } from './summary-enable-refresh.js';
153154
import { ReadonlyFieldRejectedError } from './readonly-strict-errors.js';
154155
import { HookTargetRebindError } from './hook-target-rebind-errors.js';
155156
import { FindHookResultNotArrayError } from './find-hook-result-shape.js';
@@ -725,6 +726,10 @@ export class ObjectQL implements IObjectQLEngine {
725726
// (which reads this map first) kept an uninstalled package read-only until
726727
// a restart.
727728
this._registry.onPackageUninstalled((packageId) => { this.manifests.delete(packageId); });
729+
// [#30377] A roll-up a package adds by extension is withheld with it, so
730+
// the child writes made during a disable recompute nothing: an enable
731+
// recomputes it (`summary-enable-refresh.ts`), on every enable door.
732+
this._registry.onPackageEnabled((packageId) => startSummaryRefreshOnEnable(this, this.logger, packageId));
728733
// Pick up production hardening switches from env so deployers can
729734
// enforce strict-body without code changes:
730735
// OBJECTQL_STRICT_HOOKS=1 → unresolved hooks throw at bind time
@@ -4335,6 +4340,25 @@ export class ObjectQL implements IObjectQLEngine {
43354340
return SummariesAndExpansionFacet.getOwnedSummaryDescriptors.call(summariesAndExpansionHost.of(this), parentObject);
43364341
}
43374342

4343+
/**
4344+
* [#30377] Recompute, on every parent row, the roll-up `summary` fields
4345+
* `packageId` adds to other packages' objects by extension, writing a row
4346+
* only where its stored value differs. An enable of a disabled package runs
4347+
* this by itself ({@link SchemaRegistry.onPackageEnabled}): while the
4348+
* package was disabled those fields were withheld from the roll-up index, so
4349+
* the child writes made then recomputed nothing. Public so an operator can
4350+
* re-run it after a failure the enable logged. Never throws on a row: each
4351+
* failure is in the report, and logged at `error`.
4352+
*/
4353+
refreshSummariesEnabledBy(packageId: string): Promise<SummaryEnableRefreshReport> {
4354+
return refreshSummariesExtendedBy(this, this.logger, packageId);
4355+
}
4356+
4357+
/** [#30377] Resolves once the summary recomputes the enables so far started ({@link refreshSummariesEnabledBy}) have settled, so a door can answer after them. */
4358+
summaryRefreshSettled(): Promise<void> {
4359+
return summaryRefreshesSettled(this);
4360+
}
4361+
43384362
private initializeSummaryFields(object: string, record: any): any {
43394363
// [#29986 codemod] The body moved to `engine-summaries-and-expansion.ts`, its docblock with it (see `SummariesAndExpansionHost`).
43404364
return SummariesAndExpansionFacet.initializeSummaryFields.call(summariesAndExpansionHost.of(this), object, record);

‎packages/objectql/src/registry-module-mock.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,10 @@ export function createRegistryModuleMock(
188188
// so it never announces: it records the subscription and answers the
189189
// unsubscribe the real member answers.
190190
onPackageUninstalled: vi.fn(() => () => {}),
191+
// [#30377] The engine's constructor subscribes the roll-up recompute an
192+
// enable owes. The double never enables a disabled package, so it never
193+
// announces either.
194+
onPackageEnabled: vi.fn(() => () => {}),
191195
reset: vi.fn(),
192196
metadata: { get: vi.fn(() => new Map()) },
193197
...instanceOverrides,

‎packages/objectql/src/registry.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3684,6 +3684,41 @@ export class SchemaRegistry {
36843684
/** See {@link onPackageUninstalled}. */
36853685
private packageUninstalledListeners = new Set<(packageId: string) => void>();
36863686

3687+
/** See {@link onPackageEnabled}. */
3688+
private packageEnabledListeners = new Set<(packageId: string) => void>();
3689+
3690+
/**
3691+
* [#30377] Be told that {@link enablePackage} has switched a DISABLED package
3692+
* back on, after its served folds are dropped: never for an enable of a
3693+
* package that was already enabled (`enableOnInstall: true` on a fresh
3694+
* install). Returns the unsubscribe.
3695+
*
3696+
* For state derived from what a disable withholds, so it is brought current
3697+
* on every enable door at once (`PATCH /packages/:id/enable`, an install's
3698+
* `enableOnInstall`, the protocol's install), never per door. The engine is
3699+
* the one today: a roll-up `summary` a package contributes by extension is
3700+
* withheld with its package, so the child writes made during the disable
3701+
* recompute nothing, and the engine recomputes it on enable.
3702+
*/
3703+
onPackageEnabled(listener: (packageId: string) => void): () => void {
3704+
this.packageEnabledListeners.add(listener);
3705+
return () => { this.packageEnabledListeners.delete(listener); };
3706+
}
3707+
3708+
/** Tell every {@link onPackageEnabled} listener. Never throws: the enable has happened, and a failing listener is logged at `error`. */
3709+
private announcePackageEnabled(id: string): void {
3710+
for (const listener of this.packageEnabledListeners) {
3711+
try {
3712+
listener(id);
3713+
} catch (err) {
3714+
console.error(
3715+
`[Registry] package "${id}" was enabled, but a listener bringing state derived from it current failed `
3716+
+ `(${(err as Error)?.message ?? err}) — that state may still read as it did while the package was disabled.`,
3717+
);
3718+
}
3719+
}
3720+
}
3721+
36873722
/**
36883723
* [#30215] Be told, once per package, that {@link uninstallPackage} has
36893724
* withdrawn it — after its record is gone, never for a refused uninstall
@@ -8449,6 +8484,7 @@ export class SchemaRegistry {
84498484
enablePackage(id: string): InstalledPackage | undefined {
84508485
const pkg = this.getPackage(id);
84518486
if (pkg) {
8487+
const wasDisabled = this.isPackageDisabled(id);
84528488
pkg.enabled = true;
84538489
pkg.status = 'installed';
84548490
pkg.statusChangedAt = new Date().toISOString();
@@ -8457,6 +8493,7 @@ export class SchemaRegistry {
84578493
// [#24400] A disabled package's bound actions are not attached
84588494
// ({@link boundCodeActions}), so every object's fold is re-derived.
84598495
this.invalidateAll();
8496+
if (wasDisabled) this.announcePackageEnabled(id);
84608497
}
84618498
return pkg;
84628499
}

0 commit comments

Comments
 (0)