Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/30377-extension-rollup-recompute-on-enable.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
'@objectstack/objectql': patch
'@objectstack/runtime': patch
---

fix(objectql): a roll-up summary a disabled package adds by extension is recomputed when the package is enabled again

Clause-②: no — a stored summary column stays current across a disable; nothing a caller sends is refused
Metadata-protocol: none

- **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.
- **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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* [#30377] A roll-up summary a package contributes BY EXTENSION, over a child
* of an ENABLED package, is current again the moment its package is
* re-enabled.
*
* While a package is disabled its `objectExtensions` fields are withheld from
* the served object fold (#30304), so the roll-up index — built from that fold
* — does not hold the package's summary, and the child writes made during the
* disable recompute nothing. The child here belongs to the enabled app, so
* those writes land; the stored summary column keeps the value it had when the
* package was switched off. Re-enabling serves the field again, so without a
* recompute it serves that stale value until the next write of a child.
*/

import { describe, it, expect, beforeEach, vi } from 'vitest';
import { ObjectQL } from './engine.js';

function makeDriver() {
const stores = new Map<string, Map<string, any>>();
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;
/** Parent-row writes, by object, so a case can count them. */
const updates: Array<{ object: string; id: string; data: Record<string, unknown> }> = [];
/** Ids whose next `update` throws, to drive a recompute failure. */
const failUpdateOf = new Set<string>();
const driver: any = {
name: 'memory', version: '0.0.0', supports: {},
async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; },
async find(object: string, ast: any) {
const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where));
const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows;
return page.map((r) => ({ ...r }));
},
async findOne(object: string, ast: any) {
for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r };
return null;
},
async create(object: string, data: Record<string, unknown>) {
n += 1;
const id = (data.id as string) ?? `r_${n}`;
const row = { ...data, id };
storeFor(object).set(id, row);
return { ...row };
},
async update(object: string, id: string, data: Record<string, unknown>) {
if (failUpdateOf.has(id)) throw new Error(`fake driver: update of ${id} refused`);
updates.push({ object, id, data });
const s = storeFor(object);
const row = { ...s.get(id), ...data, id };
s.set(id, row);
return { ...row };
},
async updateMany(object: string, ast: any, data: Record<string, unknown>) {
const s = storeFor(object);
let count = 0;
for (const [id, r] of Array.from(s.entries())) if (matches(r, ast?.where)) { s.set(id, { ...r, ...data, id }); count += 1; }
return count;
},
async delete(object: string, id: string) { return storeFor(object).delete(id); },
async deleteMany(object: string, ast: any) {
const s = storeFor(object);
let count = 0;
for (const [id, r] of Array.from(s.entries())) if (matches(r, ast?.where)) { s.delete(id); count += 1; }
return count;
},
async count() { return 0; },
async bulkCreate(object: string, rows: Record<string, unknown>[]) { 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, updates, failUpdateOf };
}

const APP = 'com.qa.rollup.app';
const MODULE = 'com.qa.rollup.notes';
const ACCOUNT = 'qr_account';
const NOTE = 'qr_note';
const TOTAL = 'qr_note_total';

const manifest = (id: string, type: string) =>
({ id, name: id, version: '1.0.0', type, namespace: 'qr', ...(type === 'module' ? { dependencies: { [APP]: '^1.0.0' } } : {}) }) as any;

describe('a roll-up a disabled package contributes by extension, over an enabled package\'s child', () => {
let engine: ObjectQL;
let storeFor: ReturnType<typeof makeDriver>['storeFor'];
let driver: ReturnType<typeof makeDriver>;
let logger: Record<'debug' | 'info' | 'warn' | 'error', ReturnType<typeof vi.fn>> & Record<string, unknown>;

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 });
const d = makeDriver();
driver = d;
storeFor = d.storeFor;
engine.registerDriver(d.driver, true);
await engine.init();
const registry = engine.registry;
registry.installPackage(manifest(APP, 'app'), 'code');
registry.installPackage(manifest(MODULE, 'module'), 'code');
// The app owns both the parent and the child.
registry.registerObject({
name: ACCOUNT, label: 'Account',
fields: { name: { name: 'name', type: 'text', label: 'Name' } },
} as any, APP, 'qr', 'own');
registry.registerObject({
name: NOTE, label: 'Note',
fields: {
amount: { name: 'amount', type: 'number', label: 'Amount' },
account: { name: 'account', type: 'lookup', label: 'Account', reference: ACCOUNT },
},
} as any, APP, 'qr', 'own');
// The module adds the roll-up to the app's parent, by extension.
registry.registerObject({
name: ACCOUNT,
fields: {
[TOTAL]: { name: TOTAL, type: 'summary', label: 'Note total', summaryOperations: { object: NOTE, field: 'amount', function: 'sum' } },
},
} as any, MODULE, 'qr', 'extend');
});

const stored = (id: string) => storeFor(ACCOUNT).get(id)?.[TOTAL];

it('is current after re-enable, with no further child write', async () => {
const acme = await engine.insert(ACCOUNT, { name: 'acme' });
const beta = await engine.insert(ACCOUNT, { name: 'beta' });
const first = await engine.insert(NOTE, { account: acme.id, amount: 10 });
expect(stored(acme.id), 'precondition: the roll-up tracks while the module is enabled').toBe(10);

engine.registry.disablePackage(MODULE);
// The child belongs to the enabled app: its writes land during the disable.
await engine.insert(NOTE, { account: acme.id, amount: 5 });
await engine.update(NOTE, { id: first.id, amount: 20 });
await engine.insert(NOTE, { account: beta.id, amount: 7 });

engine.registry.enablePackage(MODULE);
await engine.summaryRefreshSettled();

const served = await engine.findOne(ACCOUNT, { where: { id: acme.id }, context: { isSystem: true } });
expect(served?.[TOTAL]).toBe(25);
expect(stored(beta.id)).toBe(7);
});

it('writes no parent row on an enable when no child moved during the disable', async () => {
const acme = await engine.insert(ACCOUNT, { name: 'acme' });
await engine.insert(NOTE, { account: acme.id, amount: 10 });
engine.registry.disablePackage(MODULE);
driver.updates.length = 0;

engine.registry.enablePackage(MODULE);
await engine.summaryRefreshSettled();

expect(driver.updates.filter((u) => u.object === ACCOUNT)).toEqual([]);
expect(stored(acme.id)).toBe(10);
});

it('brings every other parent current when one parent\'s recompute fails, and says so at error', async () => {
const acme = await engine.insert(ACCOUNT, { name: 'acme' });
const beta = await engine.insert(ACCOUNT, { name: 'beta' });
engine.registry.disablePackage(MODULE);
await engine.insert(NOTE, { account: acme.id, amount: 5 });
await engine.insert(NOTE, { account: beta.id, amount: 7 });
driver.failUpdateOf.add(acme.id);

engine.registry.enablePackage(MODULE);
await engine.summaryRefreshSettled();

expect(stored(beta.id)).toBe(7);
expect(stored(acme.id)).toBe(0);
const said = logger.error.mock.calls.map((c) => String(c[0])).filter((m) => m.startsWith('[summary-refresh]'));
expect(said).toHaveLength(1);
expect(said[0]).toContain(`${ACCOUNT}/${acme.id}`);
// The operator's re-run, once the cause is cleared.
driver.failUpdateOf.clear();
const report = await engine.refreshSummariesEnabledBy(MODULE);
expect(report.failures).toEqual([]);
expect(stored(acme.id)).toBe(5);
});
});

describe('SchemaRegistry.onPackageEnabled', () => {
it('announces an enable of a disabled package, and not one of a package already enabled', () => {
const engine = new ObjectQL();
const registry = engine.registry;
registry.installPackage(manifest(APP, 'app'), 'code');
const heard: string[] = [];
const stop = registry.onPackageEnabled((id) => { heard.push(id); });

registry.enablePackage(APP);
expect(heard).toEqual([]);
registry.disablePackage(APP);
registry.enablePackage(APP);
expect(heard).toEqual([APP]);
stop();
registry.disablePackage(APP);
registry.enablePackage(APP);
expect(heard).toEqual([APP]);
});
});
24 changes: 24 additions & 0 deletions packages/objectql/src/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ import {
withoutDeletedSelfParents,
type SummaryDescriptor,
} from './summary-aggregate.js';
import { refreshSummariesExtendedBy, startSummaryRefreshOnEnable, summaryRefreshesSettled, type SummaryEnableRefreshReport } from './summary-enable-refresh.js';
import { ReadonlyFieldRejectedError } from './readonly-strict-errors.js';
import { HookTargetRebindError } from './hook-target-rebind-errors.js';
import { FindHookResultNotArrayError } from './find-hook-result-shape.js';
Expand Down Expand Up @@ -730,6 +731,10 @@ export class ObjectQL implements IObjectQLEngine {
// (which reads this map first) kept an uninstalled package read-only until
// a restart.
this._registry.onPackageUninstalled((packageId) => { this.manifests.delete(packageId); });
// [#30377] A roll-up a package adds by extension is withheld with it, so
// the child writes made during a disable recompute nothing: an enable
// recomputes it (`summary-enable-refresh.ts`), on every enable door.
this._registry.onPackageEnabled((packageId) => startSummaryRefreshOnEnable(this, this.logger, packageId));
// Pick up production hardening switches from env so deployers can
// enforce strict-body without code changes:
// OBJECTQL_STRICT_HOOKS=1 → unresolved hooks throw at bind time
Expand Down Expand Up @@ -4400,6 +4405,25 @@ export class ObjectQL implements IObjectQLEngine {
return SummariesAndExpansionFacet.getOwnedSummaryDescriptors.call(summariesAndExpansionHost.of(this), parentObject);
}

/**
* [#30377] Recompute, on every parent row, the roll-up `summary` fields
* `packageId` adds to other packages' objects by extension, writing a row
* only where its stored value differs. An enable of a disabled package runs
* this by itself ({@link SchemaRegistry.onPackageEnabled}): while the
* package was disabled those fields were withheld from the roll-up index, so
* the child writes made then recomputed nothing. Public so an operator can
* re-run it after a failure the enable logged. Never throws on a row: each
* failure is in the report, and logged at `error`.
*/
refreshSummariesEnabledBy(packageId: string): Promise<SummaryEnableRefreshReport> {
return refreshSummariesExtendedBy(this, this.logger, packageId);
}

/** [#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);
}

private initializeSummaryFields(object: string, record: any): any {
// [#29986 codemod] The body moved to `engine-summaries-and-expansion.ts`, its docblock with it (see `SummariesAndExpansionHost`).
return SummariesAndExpansionFacet.initializeSummaryFields.call(summariesAndExpansionHost.of(this), object, record);
Expand Down
4 changes: 4 additions & 0 deletions packages/objectql/src/registry-module-mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,10 @@ export function createRegistryModuleMock(
// so it never announces: it records the subscription and answers the
// unsubscribe the real member answers.
onPackageUninstalled: vi.fn(() => () => {}),
// [#30377] The engine's constructor subscribes the roll-up recompute an
// enable owes. The double never enables a disabled package, so it never
// announces either.
onPackageEnabled: vi.fn(() => () => {}),
reset: vi.fn(),
metadata: { get: vi.fn(() => new Map()) },
...instanceOverrides,
Expand Down
37 changes: 37 additions & 0 deletions packages/objectql/src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3684,6 +3684,41 @@ export class SchemaRegistry {
/** See {@link onPackageUninstalled}. */
private packageUninstalledListeners = new Set<(packageId: string) => void>();

/** See {@link onPackageEnabled}. */
private packageEnabledListeners = new Set<(packageId: string) => void>();

/**
* [#30377] Be told that {@link enablePackage} has switched a DISABLED package
* back on, after its served folds are dropped: never for an enable of a
* package that was already enabled (`enableOnInstall: true` on a fresh
* install). Returns the unsubscribe.
*
* For state derived from what a disable withholds, so it is brought current
* on every enable door at once (`PATCH /packages/:id/enable`, an install's
* `enableOnInstall`, the protocol's install), never per door. The engine is
* the one today: a roll-up `summary` a package contributes by extension is
* withheld with its package, so the child writes made during the disable
* recompute nothing, and the engine recomputes it on enable.
*/
onPackageEnabled(listener: (packageId: string) => void): () => void {
this.packageEnabledListeners.add(listener);
return () => { this.packageEnabledListeners.delete(listener); };
}

/** Tell every {@link onPackageEnabled} listener. Never throws: the enable has happened, and a failing listener is logged at `error`. */
private announcePackageEnabled(id: string): void {
for (const listener of this.packageEnabledListeners) {
try {
listener(id);
} catch (err) {
console.error(
`[Registry] package "${id}" was enabled, but a listener bringing state derived from it current failed `
+ `(${(err as Error)?.message ?? err}) — that state may still read as it did while the package was disabled.`,
);
}
}
}

/**
* [#30215] Be told, once per package, that {@link uninstallPackage} has
* withdrawn it — after its record is gone, never for a refused uninstall
Expand Down Expand Up @@ -8449,6 +8484,7 @@ export class SchemaRegistry {
enablePackage(id: string): InstalledPackage | undefined {
const pkg = this.getPackage(id);
if (pkg) {
const wasDisabled = this.isPackageDisabled(id);
pkg.enabled = true;
pkg.status = 'installed';
pkg.statusChangedAt = new Date().toISOString();
Expand All @@ -8457,6 +8493,7 @@ export class SchemaRegistry {
// [#24400] A disabled package's bound actions are not attached
// ({@link boundCodeActions}), so every object's fold is re-derived.
this.invalidateAll();
if (wasDisabled) this.announcePackageEnabled(id);
}
return pkg;
}
Expand Down
Loading
Loading