Skip to content

Commit f0ea834

Browse files
committed
fix(objectql): a refused upgrade leaves the installed version serving
The registry records each entry an upgrade writes before its first write and, when the upgrade is refused part-way, puts exactly those entries back. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5kohmFH2NCe2Gvxduz
1 parent e4764f8 commit f0ea834

4 files changed

Lines changed: 237 additions & 11 deletions

File tree

‎packages/objectql/src/engine.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9329,8 +9329,19 @@ export class ObjectQL implements IObjectQLEngine {
93299329
// record, object, app or item behind; asked here, before anything is
93309330
// written. See {@link refusedRegistrationWithdrawable}.
93319331
const withdrawable = refusedRegistrationWithdrawable(this._registry, id, manifest, this.residualOwnerSources);
9332+
// [#28697] A re-register of an installed id is an upgrade: refused
9333+
// part-way, the registry puts back exactly the entries it wrote, so the
9334+
// installed version keeps serving whole, with other packages'
9335+
// extensions of its objects and tenant overlays as they were. Never
9336+
// through uninstall, which refuses an extended object and drops a
9337+
// tenant's overlay. See {@link SchemaRegistry.restoringOnRefusal}.
9338+
const upgrade = Boolean(id) && this._registry.getPackage(id) !== undefined;
93329339
try {
9333-
this.registerPackageBody(manifest, id, namespace, version, source, scope);
9340+
if (upgrade) {
9341+
this._registry.restoringOnRefusal(() => this.registerPackageBody(manifest, id, namespace, version, source, scope));
9342+
} else {
9343+
this.registerPackageBody(manifest, id, namespace, version, source, scope);
9344+
}
93349345
} catch (err) {
93359346
if (withdrawable) this.withdrawRefusedRegistration(id, manifest, err);
93369347
throw err;

‎packages/objectql/src/package-refused-registration-withdrawn.test.ts‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@
2323
* - CONTROLS: a clean body registers everything as before; a body that took
2424
* over a tenant's object is not withdrawn (the withdrawal would drop the
2525
* tenant's layer); nor is an installed id refused part-way by the registry
26-
* (the withdrawal would take the installed version with it).
26+
* (the withdrawal would take the installed version with it), which keeps
27+
* serving its installed version instead
28+
* (`package-refused-upgrade-keeps-installed.test.ts`).
2729
*/
2830

2931
import { describe, it, expect } from 'vitest';
@@ -225,22 +227,22 @@ describe('[#28697] controls', () => {
225227
expect(engine.registry.getPackage(PKG), 'not withdrawn').toBeDefined();
226228
});
227229

228-
it('an installed id refused part-way by the registry is not withdrawn', () => {
230+
it('an installed id refused part-way by the registry is not withdrawn: the installed version keeps serving', () => {
229231
const engine = new ObjectQL();
230232
engine.registerApp({ id: HOST, name: HOST, objects: [object('probe_held')] } as any);
231233
engine.registerApp({ id: PKG, name: PKG, version: '1.0.0', objects: [object('probe_a'), object('probe_old')], apps: [app('probe_app')] } as any);
234+
const before = trace(engine);
232235
const err = refusal(() => engine.registerApp(body({
233236
version: '2.0.0',
234237
objects: [object('probe_a', { label: 'v2 label' }), object('probe_held')],
235238
}) as any));
236239
expect(err).toMatchObject({ code: 'OBJECT_OWNERSHIP_CONFLICT', status: 422 });
237-
const t = trace(engine);
238-
// Not withdrawn: the withdrawal would take v1 with it.
239-
expect(t.pkg?.manifest.version).toBe('2.0.0');
240-
expect((engine.registry.getObject('probe_a') as any)?.label).toBe('v2 label');
241-
expect(t.objects).toEqual(['probe_a', 'probe_held', 'probe_old']);
242-
expect(t.apps).toEqual(['probe_app']);
243-
// What `registerApp` writes only once the body registered whole is not written.
244-
expect({ nav: t.nav, kinds: t.kinds, datasources: t.datasources }).toEqual({ nav: [], kinds: [], datasources: [] });
240+
// Not withdrawn (the withdrawal would take v1 with it), and nothing of
241+
// v2 stays: the registry puts back what the refused upgrade wrote.
242+
expect(trace(engine)).toEqual(before);
243+
expect(engine.registry.getPackage(PKG)?.manifest.version).toBe('1.0.0');
244+
expect((engine.registry.getObject('probe_a') as any)?.label).toBe('probe_a');
245+
expect(trace(engine).objects).toEqual(['probe_a', 'probe_held', 'probe_old']);
246+
expect(engine.registry.getObjectOwner('probe_held')?.packageId).toBe(HOST);
245247
});
246248
});

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,10 @@ export function createRegistryModuleMock(
183183
// `TypeError` at every `registerApp`.
184184
getPackage: vi.fn(() => undefined),
185185
getObjectContributors: vi.fn(() => []),
186+
// [#28697] …and an upgrade (a `getPackage` hit) runs its body through this
187+
// member, so a refused upgrade is put back. The double runs the body as
188+
// given: it records nothing, so it has nothing to put back.
189+
restoringOnRefusal: vi.fn((register: () => unknown) => register()),
186190
reset: vi.fn(),
187191
metadata: { get: vi.fn(() => new Map()) },
188192
...instanceOverrides,

‎packages/objectql/src/registry.ts‎

Lines changed: 209 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3141,6 +3141,34 @@ function withoutField(schema: ServiceObject, name: string): ServiceObject {
31413141
return { ...schema, fields: rest } as ServiceObject;
31423142
}
31433143

3144+
/**
3145+
* [#28697] The undo record of one registration run under
3146+
* {@link SchemaRegistry.restoringOnRefusal}: for each registry entry the run
3147+
* writes, the way to put back what the entry held just before the run's FIRST
3148+
* write to it. An entry the run never writes is never recorded, so a restore
3149+
* puts back exactly the entries the run touched and nothing else — another
3150+
* package's entries and a tenant's layers are left as they are.
3151+
*/
3152+
class RegistrationRestorePoint {
3153+
private readonly touched = new Set<string>();
3154+
private readonly undo: Array<() => void> = [];
3155+
3156+
/**
3157+
* Record `key` before its first write in this run. `capture` reads the
3158+
* entry as it is now and returns how to put it back.
3159+
*/
3160+
note(key: string, capture: () => () => void): void {
3161+
if (this.touched.has(key)) return;
3162+
this.touched.add(key);
3163+
this.undo.push(capture());
3164+
}
3165+
3166+
/** Put every recorded entry back, the last one written first. */
3167+
restore(): void {
3168+
for (let i = this.undo.length - 1; i >= 0; i--) this.undo[i]();
3169+
}
3170+
}
3171+
31443172
export class SchemaRegistry {
31453173
// ==========================================
31463174
// Logging control
@@ -3423,6 +3451,173 @@ export class SchemaRegistry {
34233451
this.initialDisabledPackageIds = new Set(ids);
34243452
}
34253453

3454+
// ==========================================
3455+
// Restore on refusal
3456+
// ==========================================
3457+
3458+
/** The open {@link RegistrationRestorePoint}, while {@link restoringOnRefusal} runs. */
3459+
private restorePoint: RegistrationRestorePoint | undefined;
3460+
3461+
/**
3462+
* [#28697] Run `register` — one registration made of several registry
3463+
* writes, such as an upgrade of an installed package — and, when it throws,
3464+
* put back exactly the entries it wrote, then throw the same error.
3465+
*
3466+
* Every refusal a verb below raises keeps its code and words; this changes
3467+
* only what is left afterwards. A refusal raised after some of the run's
3468+
* writes (an object another package owns, a field with no `type`, a
3469+
* picklist value already added, …) would otherwise leave those writes
3470+
* serving beside the entries they replaced: an upgrade's new package record
3471+
* and the objects it reached, next to the installed version's remainder.
3472+
*
3473+
* What is recorded, each entry before the run's first write to it: an
3474+
* object's contributor list (an `extend` or overlay layer of another package
3475+
* or a tenant sits in it and is put back unchanged), a namespace's owners,
3476+
* an item slot (the package record included), this package's picklist
3477+
* extension of one list, and the security catalog and default record page
3478+
* claims the package door records. Nothing the run does not write is
3479+
* recorded or put back. After a restore every merged object is
3480+
* re-resolved, since a fold computed during the run may have read an entry
3481+
* the restore put back.
3482+
*
3483+
* ⛔ Not a way back from an operator's verb: {@link uninstallPackage},
3484+
* {@link unregisterObject} and the overlay removals are never journaled.
3485+
* Synchronous by contract: `register` must not return a promise, so no
3486+
* other caller's write can land between the run's writes and its restore.
3487+
* A nested call joins the run that is already open.
3488+
*/
3489+
restoringOnRefusal<T>(register: () => T): T {
3490+
if (this.restorePoint) return register();
3491+
const point = new RegistrationRestorePoint();
3492+
this.restorePoint = point;
3493+
try {
3494+
const result = register();
3495+
if (result instanceof Promise) {
3496+
throw new TypeError('[Registry] restoringOnRefusal takes a synchronous registration; it was handed one that returned a promise.');
3497+
}
3498+
return result;
3499+
} catch (err) {
3500+
point.restore();
3501+
this.invalidateAll();
3502+
throw err;
3503+
} finally {
3504+
this.restorePoint = undefined;
3505+
}
3506+
}
3507+
3508+
/** Record an object's contributor list (and each contributor's mutable slots) before its first write. */
3509+
private noteObjectEntry(fqn: string): void {
3510+
this.restorePoint?.note(`object\u0000${fqn}`, () => {
3511+
const list = this.objectContributors.get(fqn);
3512+
if (!list) return () => this.closeObjectEntry(fqn);
3513+
// The late-install branch re-classifies a sitting contributor in place,
3514+
// so its ownership and priority are kept beside the reference.
3515+
const saved = list.map((c) => ({ c, ownership: c.ownership, priority: c.priority }));
3516+
return () => {
3517+
for (const s of saved) {
3518+
s.c.ownership = s.ownership;
3519+
s.c.priority = s.priority;
3520+
}
3521+
list.splice(0, list.length, ...saved.map((s) => s.c));
3522+
this.mergedObjectCache.delete(fqn);
3523+
};
3524+
});
3525+
}
3526+
3527+
/** Record a namespace's owner set before its first write. */
3528+
private noteNamespace(namespace: string): void {
3529+
this.restorePoint?.note(`namespace\u0000${namespace}`, () => {
3530+
const owners = this.namespaceRegistry.get(namespace);
3531+
const saved = owners ? new Set(owners) : undefined;
3532+
return () => {
3533+
if (saved) this.namespaceRegistry.set(namespace, saved);
3534+
else this.namespaceRegistry.delete(namespace);
3535+
};
3536+
});
3537+
}
3538+
3539+
/** Record whether an item type had a store at all, before the run can create one. */
3540+
private noteItemType(type: string): void {
3541+
this.restorePoint?.note(`type\u0000${type}`, () => {
3542+
const hadType = this.metadata.has(type);
3543+
return () => {
3544+
if (!hadType && this.metadata.get(type)?.size === 0) this.metadata.delete(type);
3545+
};
3546+
});
3547+
}
3548+
3549+
/** Record one item slot before its first write. */
3550+
private noteItem(type: string, key: string): void {
3551+
this.restorePoint?.note(`item\u0000${type}\u0000${key}`, () => {
3552+
const collection = this.metadata.get(type);
3553+
const had = collection?.has(key) ?? false;
3554+
const value = collection?.get(key);
3555+
return () => {
3556+
const now = this.metadata.get(type);
3557+
if (had) now?.set(key, value);
3558+
else now?.delete(key);
3559+
};
3560+
});
3561+
}
3562+
3563+
/** Record this package's extension of one picklist before its first write. */
3564+
private notePicklistExtension(target: string, packageKey: string): void {
3565+
this.restorePoint?.note(`picklistExtension\u0000${target}\u0000${packageKey}`, () => {
3566+
const byPackage = this.picklistExtensionContributions.get(target);
3567+
const saved = byPackage?.get(packageKey);
3568+
return () => {
3569+
let now = this.picklistExtensionContributions.get(target);
3570+
if (saved) {
3571+
if (!now) this.picklistExtensionContributions.set(target, now = new Map());
3572+
now.set(packageKey, saved);
3573+
} else if (now) {
3574+
now.delete(packageKey);
3575+
if (now.size === 0) this.picklistExtensionContributions.delete(target);
3576+
}
3577+
};
3578+
});
3579+
}
3580+
3581+
/** Record who holds one security catalog name before its first write. */
3582+
private noteSecurityCatalogClaim(type: SecurityCatalogType, name: string): void {
3583+
this.restorePoint?.note(`catalogClaim\u0000${type}\u0000${name}`, () => {
3584+
const saved = this.securityCatalogClaims.get(type)?.get(name);
3585+
return () => {
3586+
let byName = this.securityCatalogClaims.get(type);
3587+
if (saved !== undefined) {
3588+
if (!byName) this.securityCatalogClaims.set(type, byName = new Map());
3589+
byName.set(name, saved);
3590+
} else {
3591+
byName?.delete(name);
3592+
}
3593+
};
3594+
});
3595+
}
3596+
3597+
/**
3598+
* Record the default record page claims before `packageId`'s first rewrite
3599+
* of them ({@link recordDefaultRecordPageClaims} drops all of the package's
3600+
* claims, then adds what the manifest declares). Put back per object, and
3601+
* only for the objects `packageId` held a claim on before or after, each in
3602+
* its holders' original order.
3603+
*/
3604+
private noteDefaultRecordPageClaims(packageId: string): void {
3605+
this.restorePoint?.note(`defaultPageClaims\u0000${packageId}`, () => {
3606+
const saved = new Map<string, Map<string, string>>();
3607+
for (const [object, byPackage] of this.defaultRecordPageClaims) saved.set(object, new Map(byPackage));
3608+
return () => {
3609+
const objects = new Set<string>();
3610+
for (const [object, byPackage] of saved) if (byPackage.has(packageId)) objects.add(object);
3611+
for (const [object, byPackage] of this.defaultRecordPageClaims) if (byPackage.has(packageId)) objects.add(object);
3612+
for (const object of objects) {
3613+
const before = saved.get(object);
3614+
if (before) this.defaultRecordPageClaims.set(object, new Map(before));
3615+
else this.defaultRecordPageClaims.delete(object);
3616+
}
3617+
};
3618+
});
3619+
}
3620+
34263621
// ==========================================
34273622
// Namespace Management
34283623
// ==========================================
@@ -3433,6 +3628,7 @@ export class SchemaRegistry {
34333628
*/
34343629
registerNamespace(namespace: string, packageId: string): void {
34353630
if (!namespace) return;
3631+
this.noteNamespace(namespace);
34363632

34373633
let owners = this.namespaceRegistry.get(namespace);
34383634
if (!owners) {
@@ -3449,6 +3645,7 @@ export class SchemaRegistry {
34493645
unregisterNamespace(namespace: string, packageId: string): void {
34503646
const owners = this.namespaceRegistry.get(namespace);
34513647
if (owners) {
3648+
this.noteNamespace(namespace);
34523649
owners.delete(packageId);
34533650
if (owners.size === 0) {
34543651
this.namespaceRegistry.delete(namespace);
@@ -3623,6 +3820,7 @@ export class SchemaRegistry {
36233820
* {@link defaultRecordPageClaims} for why a re-install replaces).
36243821
*/
36253822
private recordDefaultRecordPageClaims(packageId: string, manifest: ObjectStackManifest): void {
3823+
this.noteDefaultRecordPageClaims(packageId);
36263824
this.forgetDefaultRecordPageClaims(packageId);
36273825
for (const { object, page } of declaredDefaultRecordPages(manifest)) {
36283826
let byPackage = this.defaultRecordPageClaims.get(object);
@@ -3752,6 +3950,7 @@ export class SchemaRegistry {
37523950
byName = new Map();
37533951
this.securityCatalogClaims.set(type, byName);
37543952
}
3953+
this.noteSecurityCatalogClaim(type, name);
37553954
byName.set(name, packageId);
37563955
}
37573956
}
@@ -4101,6 +4300,11 @@ export class SchemaRegistry {
41014300
// record — skip rather than registering `undefined` as an owner (which
41024301
// would also mean widening `registerNamespace`'s own required-string
41034302
// contract, out of scope here).
4303+
// [#28697] Recorded before the first write below (the namespace claim),
4304+
// so a refusal raised after it — the ownership conflict — puts this
4305+
// object's layers back exactly ({@link restoringOnRefusal}).
4306+
this.noteObjectEntry(fqn);
4307+
41044308
if (namespace && packageId) {
41054309
this.registerNamespace(namespace, packageId);
41064310
}
@@ -6122,6 +6326,7 @@ export class SchemaRegistry {
61226326
* Universal Register Method for non-object metadata.
61236327
*/
61246328
registerItem<T>(type: string, item: T, keyField: keyof T = 'name' as keyof T, packageId?: string) {
6329+
this.noteItemType(type);
61256330
if (!this.metadata.has(type)) {
61266331
this.metadata.set(type, new Map());
61276332
}
@@ -6400,6 +6605,7 @@ export class SchemaRegistry {
64006605
}
64016606
}
64026607

6608+
this.noteItem(type, storageKey);
64036609
collection.set(storageKey, item);
64046610
if (type === 'picklist') this.invalidateAll();
64056611
// [#24400] A bound action is attached to its target on read
@@ -7165,6 +7371,7 @@ export class SchemaRegistry {
71657371
this.registerNamespace(manifest.namespace, manifest.id);
71667372
}
71677373

7374+
this.noteItemType('package');
71687375
if (!this.metadata.has('package')) {
71697376
this.metadata.set('package', new Map());
71707377
}
@@ -7174,6 +7381,7 @@ export class SchemaRegistry {
71747381
// a normal path, not an error — keep it at debug (#3420).
71757382
this.debug(`[Registry] Overwriting package: ${manifest.id}`);
71767383
}
7384+
this.noteItem('package', manifest.id);
71777385
collection.set(manifest.id, pkg);
71787386
// The names this package now holds, recorded whether or not an item store
71797387
// entry will carry them (see `securityCatalogClaims`).
@@ -7699,6 +7907,7 @@ export class SchemaRegistry {
76997907

77007908
let byPackage = this.picklistExtensionContributions.get(target);
77017909
if (!byPackage) this.picklistExtensionContributions.set(target, byPackage = new Map());
7910+
this.notePicklistExtension(target, packageKey);
77027911
byPackage.set(packageKey, { packageId, options: merged });
77037912
this.invalidateAll();
77047913
this.log(`[Registry] Registered picklist extension: ${target} (+${extension.options?.length ?? 0}) from ${packageId}`);

0 commit comments

Comments
 (0)