diff --git a/.changeset/35609-reregister-extension-withdraw.md b/.changeset/35609-reregister-extension-withdraw.md new file mode 100644 index 00000000000..efc85239b87 --- /dev/null +++ b/.changeset/35609-reregister-extension-withdraw.md @@ -0,0 +1,14 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): a package registered again stops serving an object extension its new manifest no longer declares + +Clause-②: no +Metadata-protocol: none + +When a package was registered again without uninstalling it first (an `os dev` artifact reload, or an upgrade or re-install through the marketplace install-local door) and its new manifest no longer carried an `objectExtensions` entry for an object the previous registration extended, the old extension stayed registered. Its fields, validations and indexes kept being served on that object until the process restarted. A package's previous extension of an object was replaced only when the new manifest named that same object again. + +A re-registered package body now withdraws each extension its previous body registered for an object the new body no longer extends, through the same per-object withdrawal the `object_extension` item delete uses. The object then serves exactly the extensions the package's current manifest declares. Another package's extension of the same object is untouched, and so is an extension registered under the package id outside a body (the `object_extension` item door's layer). A refusal later in the same registration run puts the withdrawn extension back with the rest of the installed version. + +Stored data is not touched: the column the dropped field used keeps its values, and schema sync drops no column. The field is simply no longer served. The install-local dry run already listed the dropped field under `plan.fields.removed`; that answer is unchanged. diff --git a/packages/cloud-connection/src/marketplace-install-local-reregister-extension-withdraw-35609.test.ts b/packages/cloud-connection/src/marketplace-install-local-reregister-extension-withdraw-35609.test.ts new file mode 100644 index 00000000000..2b4f225c7ab --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-reregister-extension-withdraw-35609.test.ts @@ -0,0 +1,220 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35609] The install-local door: an upgrade or a re-install of a package + * whose new version no longer extends an object serves that object without + * the dropped extension's fields, with no restart. + * + * The door registers the new version through the `manifest` service without + * uninstalling the installed one first (an upgrade and a re-install of the + * same id are both a hot re-register). Before the fix the registry withdrew a + * package's previous extension of a target only when the new registration + * named that target again, so a dropped extension kept serving its fields. + * + * Real here: an `ObjectKernel` with a SQL driver and `ObjectQLPlugin` (the + * `manifest` service over the real `SchemaRegistry`, and the real schema + * sync), the base package registered at boot as code. The door's side readers + * (binder, translations, seeds) are recorders, as in the hot-resync suite. + * + * What it pins, per door: the served object; the dry run's plan names the + * dropped field; the stored column and its value are untouched (the field is + * no longer served, nothing is dropped); and the CONTROL, a version that keeps + * the extension, keeps the field. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +// The first load of the runtime's dist paid at module top, never inside a +// clocked `it` (`scripts/check-test-source-alias.mjs`): the plugin reaches the +// same module through a dynamic `import()` for its handler binder. +import '@objectstack/runtime'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { MarketplaceInstallLocalPlugin } from './marketplace-install-local-plugin.js'; +import { installerAuthService, withInstallerGrants } from './install-local-principal.fixtures.js'; + +type Handler = (c: any) => Promise; + +const CORE = 'com.acme.core'; +const MOD = 'com.acme.mod'; +const SYSTEM = { context: { isSystem: true } } as const; + +const core = { + id: CORE, + name: 'Core', + namespace: 'crm', + version: '1.0.0', + type: 'app', + objects: [{ name: 'crm_line', label: 'Line', fields: { name: { type: 'text', label: 'Name' } } }], +}; + +/** The module's install body at `version`, extending `crm_line` with `cb_account` unless `extends` is false. */ +const mod = (version: string, opts: { extends: boolean }) => ({ + manifest: { + id: MOD, + name: 'Mod', + namespace: 'crmmod', + version, + type: 'module', + dependencies: { [CORE]: '^1.0.0' }, + objectExtensions: opts.extends + ? [{ extend: 'crm_line', fields: { cb_account: { type: 'text', label: 'Account' } } }] + : [], + }, +}); + +function makeRawApp() { + const routes = new Map(); + return { + routes, + get: (p: string, h: Handler) => routes.set(`GET ${p}`, h), + post: (p: string, h: Handler) => routes.set(`POST ${p}`, h), + delete: (p: string, h: Handler) => routes.set(`DELETE ${p}`, h), + }; +} + +function makeC(body: any) { + return { + req: { + url: 'http://localhost:3000/api/v1/marketplace/install-local', + raw: new Request('http://localhost:3000/x'), + json: async () => body, + param: () => undefined, + }, + json: vi.fn((payload: any, status?: number) => ({ payload, status: status ?? 200 })), + }; +} + +let dir: string; +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'mil-35609-')); }); +afterEach(() => { rmSync(dir, { recursive: true, force: true }); vi.restoreAllMocks(); }); + +async function bootDoor() { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + let kernelCtx: PluginContext | undefined; + await kernel.use({ + name: 'test.35609.driver', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { ctx.registerService('driver.default', driver); }, + } as Plugin); + await kernel.use(new ObjectQLPlugin()); + await kernel.use({ + name: 'test.35609.core', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + kernelCtx = ctx; + await ctx.getService<{ register(m: unknown): unknown }>('manifest').register(core); + }, + } as Plugin); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + ql.registry.logLevel = 'silent'; + + const rawApp = makeRawApp(); + const hooks = new Map(); + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + const services: Record = { + manifest: kernel.getService('manifest'), + auth: installerAuthService(), + objectql: withInstallerGrants({ + convertPackageBodyForward: (body: unknown) => ql.convertPackageBodyForward(body), + registry: ql.registry, + get manifests() { return (ql as unknown as { manifests: Map }).manifests; }, + syncSchemas: () => ql.syncSchemas(), + find: (...a: Parameters) => ql.find(...a), + count: (...a: Parameters) => ql.count(...a), + }), + }; + const ctx: any = { + hook: (e: string, h: any) => hooks.set(e, h), + trigger: (event: string, payload: unknown) => kernelCtx!.trigger(event, payload), + getService: (name: string) => { + if (name === 'http-server') return { getRawApp: () => rawApp }; + if (!(name in services)) throw new Error(`no ${name}`); + return services[name]; + }, + logger, + }; + const plugin = new MarketplaceInstallLocalPlugin({ controlPlaneUrl: 'off', storageDir: dir }); + const p = plugin as unknown as Record; + p.bindArtifactHandlers = async () => undefined; + p.applySideEffects = async () => ({ translationsLoaded: 0, seeded: { mode: 'none' } }); + await plugin.start(ctx); + await hooks.get('kernel:ready')?.(); + + const post = async (body: unknown) => rawApp.routes.get('POST /api/v1/marketplace/install-local')!(makeC(body)); + const servedFields = (): string[] => Object.keys((ql.registry.getObject('crm_line') as any)?.fields ?? {}) + .filter((f) => f === 'name' || f.startsWith('cb_')).sort(); + const knex = (driver as unknown as { knex: any }).knex; + const column = async () => { + const rows = await knex('crm_line').select('*'); + return { hasColumn: await knex.schema.hasColumn('crm_line', 'cb_account'), values: rows.map((r: any) => r.cb_account) }; + }; + return { kernel, ql, post, servedFields, column, logger }; +} + +async function settle(k: { kernel: ObjectKernel }) { + await Promise.race([k.kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); +} + +describe('[#35609] install-local: a version that no longer extends an object serves it without the extension', () => { + it('an upgrade that drops the extension: the plan names the field, the object no longer serves it, the column keeps its value', async () => { + const k = await bootDoor(); + try { + expect((await k.post(mod('1.0.0', { extends: true }))).payload?.data?.hotLoaded).toBe(true); + expect(k.servedFields()).toEqual(['cb_account', 'name']); + await k.ql.insert('crm_line', { id: 'l1', name: 'one', cb_account: 'ACME', organization_id: 'org_a' }, SYSTEM); + + // The dry run already said so (unchanged by this fix): the field is removed, its column holds a row. + const dry = await k.post({ ...mod('1.0.1', { extends: false }), dryRun: true }); + expect(dry.status).toBe(200); + expect(dry.payload.data.plan.fields.removed).toEqual([expect.objectContaining({ object: 'crm_line', field: 'cb_account' })]); + expect(dry.payload.data.environment.columns).toEqual([expect.objectContaining({ object: 'crm_line', field: 'cb_account', reasons: ['removed'], rows: 1 })]); + + const upgraded = await k.post(mod('1.0.1', { extends: false })); + expect(upgraded.status, JSON.stringify(upgraded.payload)).toBe(200); + expect(upgraded.payload.data.hotLoaded).toBe(true); + + expect(k.servedFields()).toEqual(['name']); + const [row] = (await k.ql.find('crm_line', { where: {}, ...SYSTEM })) as Array>; + expect(row).toMatchObject({ id: 'l1', name: 'one' }); + expect(row).not.toHaveProperty('cb_account'); + // Stored data is untouched: nothing drops the column. + expect(await k.column()).toEqual({ hasColumn: true, values: ['ACME'] }); + } finally { + await settle(k); + } + }, 60_000); + + it('a re-install of the same version without the extension withdraws it too', async () => { + const k = await bootDoor(); + try { + await k.post(mod('1.0.0', { extends: true })); + expect(k.servedFields()).toEqual(['cb_account', 'name']); + const res = await k.post(mod('1.0.0', { extends: false })); + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(k.servedFields()).toEqual(['name']); + } finally { + await settle(k); + } + }, 60_000); + + it('CONTROL: an upgrade that keeps the extension keeps its field', async () => { + const k = await bootDoor(); + try { + await k.post(mod('1.0.0', { extends: true })); + const res = await k.post(mod('1.0.1', { extends: true })); + expect(res.status, JSON.stringify(res.payload)).toBe(200); + expect(k.servedFields()).toEqual(['cb_account', 'name']); + } finally { + await settle(k); + } + }, 60_000); +}); diff --git a/packages/objectql/src/registry-items.ts b/packages/objectql/src/registry-items.ts index cf0545e7c87..5646d64a20a 100644 --- a/packages/objectql/src/registry-items.ts +++ b/packages/objectql/src/registry-items.ts @@ -43,6 +43,7 @@ import { collectBundle, entriesOfMember, isStoredActionRow, overlaySlotEntriesOf, packageBodySlot, packagelessActionOwnerKey, packagelessActionSlotEntriesOf, packagelessActionSlotKey, } from './registry-top-level.js'; +import type { ObjectContributor } from './registry-top-level.js'; import type { SchemaRegistry } from './registry.js'; /** @@ -58,20 +59,39 @@ export interface ItemsHost { invalidateAll: SchemaRegistry['invalidateAll']; log: SchemaRegistry['log']; readonly metadata: SchemaRegistry['metadata']; + readonly objectContributors: SchemaRegistry['objectContributors']; noteBareNameClaim: SchemaRegistry['noteBareNameClaim']; noteItem: SchemaRegistry['noteItem']; noteItemOrder: SchemaRegistry['noteItemOrder']; noteSecurityCatalogClaim: SchemaRegistry['noteSecurityCatalogClaim']; openPackageBody: SchemaRegistry['openPackageBody']; orderedOverlayTier: SchemaRegistry['orderedOverlayTier']; + readonly packageBodyExtensions: SchemaRegistry['packageBodyExtensions']; readonly packageBodyItems: SchemaRegistry['packageBodyItems']; readonly restorePoint: SchemaRegistry['restorePoint']; readonly securityCatalogClaims: SchemaRegistry['securityCatalogClaims']; unregisterPicklistExtensionsByPackage: SchemaRegistry['unregisterPicklistExtensionsByPackage']; + withdrawObjectExtension: SchemaRegistry['withdrawObjectExtension']; withdrawPackageBodyItemsNotShipped: SchemaRegistry['withdrawPackageBodyItemsNotShipped']; withdrawPackageClaimsNotDeclared: SchemaRegistry['withdrawPackageClaimsNotDeclared']; } +/** + * [#35609] Each object `packageId` holds an `extend` layer of, by key: the + * layer itself, so a caller can tell a layer it saw from one written since. + */ +function packageExtensionLayers( + objectContributors: ReadonlyMap, + packageId: string, +): Map { + const layers = new Map(); + for (const [fqn, contributors] of objectContributors) { + const layer = contributors.find((c) => c.ownership === 'extend' && c.packageId === packageId); + if (layer) layers.set(fqn, layer); + } + return layers; +} + /** The bodies of the "Generic metadata items and package bodies" section of `SchemaRegistry`: a stateless facet, called by the class's stubs. */ export class ItemsFacet { /** @@ -202,11 +222,29 @@ export class ItemsFacet { return { removed, orphanedOverlays }; } - /** The body of `SchemaRegistry#replacingPackageBody`; the method's docblock there is its contract. */ - static replacingPackageBody(this: Pick, packageId: string | undefined, manifest: ObjectStackManifest, register: () => T): T { + /** + * The body of `SchemaRegistry#replacingPackageBody`; the method's docblock there is its contract. + * + * [#35609] The extension half in detail: `packageBodyExtensions` holds, per package id, the + * extension layers its last body wrote, by object key — the layer object itself, so a layer + * another door has since put in the package's slot of that object (the `object_extension` + * item door) is told apart and kept. A dropped target's layer leaves through `withdrawObjectExtension`, the per-target + * withdrawal the `object_extension` item delete uses, so the target serves exactly the + * extensions the current manifest declares. Before this, the extend splice replaced the + * package's layer only for a target the new body named again, and a dropped extension kept + * its fields served until a restart. Schema sync drops no column. The withdrawal is recorded + * in the open run, so a refusal later in it puts the layer back. The map is forgotten by + * `uninstallPackage`. + */ + static replacingPackageBody(this: Pick, packageId: string | undefined, manifest: ObjectStackManifest, register: () => T): T { if (!packageId) return register(); const open = this.openPackageBody; const body = { packageId, written: new Set() }; + // [#35609] The package's extension layers before the body registers. The + // extend splice replaces a package's layer of a target with a NEW + // contributor, so a layer still the same object afterwards is one this + // body did not write. + const extensionsBefore = packageExtensionLayers(this.objectContributors, packageId); this.openPackageBody = body; let result: T; try { @@ -214,11 +252,41 @@ export class ItemsFacet { } finally { this.openPackageBody = open; } + const extended = new Map(); + for (const [fqn, layer] of packageExtensionLayers(this.objectContributors, packageId)) { + if (extensionsBefore.get(fqn) !== layer) extended.set(fqn, layer); + } const previous = this.packageBodyItems.get(packageId); if (previous !== undefined) { this.withdrawPackageBodyItemsNotShipped(packageId, previous, body.written); this.withdrawPackageClaimsNotDeclared(packageId, manifest); } + // [#35609] …and the extension layers the previous body wrote of a target + // this one does not extend, through the per-target withdrawal the + // `object_extension` item delete uses. Only the layer that body wrote: + // one another door has since put in the package's slot is not the body's. + const previousExtensions = this.packageBodyExtensions.get(packageId); + if (previousExtensions !== undefined) { + const withdrawn: string[] = []; + for (const [fqn, layer] of previousExtensions) { + if (extended.has(fqn) || !this.objectContributors.get(fqn)?.includes(layer)) continue; + if (this.withdrawObjectExtension(fqn, packageId)) withdrawn.push(fqn); + } + if (withdrawn.length > 0) { + this.log( + `[Registry] Withdrew ${withdrawn.length} object extension(s) package ${packageId}'s new body no longer declares: ${withdrawn.join(', ')}`, + ); + } + } + this.restorePoint?.note(`packageBodyExtensions\u0000${packageId}`, () => { + const had = this.packageBodyExtensions.has(packageId); + const saved = this.packageBodyExtensions.get(packageId); + return () => { + if (had && saved !== undefined) this.packageBodyExtensions.set(packageId, saved); + else this.packageBodyExtensions.delete(packageId); + }; + }); + this.packageBodyExtensions.set(packageId, extended); this.restorePoint?.note(`packageBody\u0000${packageId}`, () => { const had = this.packageBodyItems.has(packageId); const saved = this.packageBodyItems.get(packageId); diff --git a/packages/objectql/src/registry-packages.ts b/packages/objectql/src/registry-packages.ts index b958dd52a67..6c7655e0359 100644 --- a/packages/objectql/src/registry-packages.ts +++ b/packages/objectql/src/registry-packages.ts @@ -82,6 +82,7 @@ export interface PackagesHost { noteItem: SchemaRegistry['noteItem']; noteItemType: SchemaRegistry['noteItemType']; readonly objectContributors: SchemaRegistry['objectContributors']; + readonly packageBodyExtensions: SchemaRegistry['packageBodyExtensions']; readonly packageBodyItems: SchemaRegistry['packageBodyItems']; recordBareNameClaims: SchemaRegistry['recordBareNameClaims']; recordDefaultRecordPageClaims: SchemaRegistry['recordDefaultRecordPageClaims']; @@ -560,7 +561,7 @@ export class PackagesFacet { } /** The body of `SchemaRegistry#uninstallPackage`; the method's docblock there is its contract. */ - static uninstallPackage(this: Pick, id: string, options?: { keepBootSeed?: boolean }): boolean { + static uninstallPackage(this: Pick, id: string, options?: { keepBootSeed?: boolean }): boolean { const pkg = this.getPackage(id); if (!pkg) { console.warn(`[Registry] Package not found for uninstall: ${id}`); @@ -602,6 +603,9 @@ export class PackagesFacet { // [#33050] …and the record of what its body shipped: a later install of // the id is a first registration, with nothing of its own to withdraw. this.packageBodyItems.delete(id); + // [#35609] …and of the extension layers it wrote: the object verb above + // has withdrawn them. + this.packageBodyExtensions.delete(id); // [#31720] …and the namespace names a stack's residual holds under this // id: the residual's items are registered under their owner id, so // `unregisterItemsByPackage(id)` above has just withdrawn them (the diff --git a/packages/objectql/src/registry-platform-global.ts b/packages/objectql/src/registry-platform-global.ts index 7f14554214d..a27d15c85ba 100644 --- a/packages/objectql/src/registry-platform-global.ts +++ b/packages/objectql/src/registry-platform-global.ts @@ -75,6 +75,7 @@ export interface PlatformGlobalHost { readonly multiTenant: SchemaRegistry['multiTenant']; readonly objectContributors: SchemaRegistry['objectContributors']; readonly objectKeysByShortName: SchemaRegistry['objectKeysByShortName']; + noteObjectEntry: SchemaRegistry['noteObjectEntry']; packagedRules: SchemaRegistry['packagedRules']; registerObject: SchemaRegistry['registerObject']; resolveObject: SchemaRegistry['resolveObject']; @@ -624,12 +625,15 @@ export class PlatformGlobalFacet { } /** The body of `SchemaRegistry#withdrawObjectExtension`; the method's docblock there is its contract. */ - static withdrawObjectExtension(this: Pick, name: string, packageId: string): boolean { + static withdrawObjectExtension(this: Pick, name: string, packageId: string): boolean { const fqn = this.resolveObjectKey(name) ?? name; const contributors = this.objectContributors.get(fqn); if (!contributors) return false; const idx = contributors.findIndex(c => c.ownership === 'extend' && c.packageId === packageId); if (idx === -1) return false; + // [#35609] Recorded for an open registration run before the removal, so a + // refusal later in the run puts the layer back (no-op outside a run). + this.noteObjectEntry(fqn); contributors.splice(idx, 1); if (contributors.length === 0) this.closeObjectEntry(fqn); // The same two invalidations every other contributor mutation performs. diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 8e971fb04dc..5e3a944a849 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -4572,6 +4572,9 @@ export class SchemaRegistry { */ private readonly packageBodyItems = new Map>(); + /** [#35609] Package id → the extension layers its last body wrote, by object key (see `ItemsFacet`). */ + private readonly packageBodyExtensions = new Map>(); + /** The body registration {@link replacingPackageBody} has open, while it runs. */ private openPackageBody: { readonly packageId: string; readonly written: Set } | undefined; @@ -4600,8 +4603,12 @@ export class SchemaRegistry { * claim recorded before it is removed, so a refusal later in the run (a later * member of the artifact, the run-end record-currency door) puts them back * with the rest of the installed version. `register` throwing withdraws - * nothing. Objects and object extensions are not items and are not touched - * here. + * nothing. Owned objects are not items and are not touched here. + * + * [#35609] An extension the previous body registered for a target the new + * body no longer extends is withdrawn (`withdrawObjectExtension`), the whole + * layer with it; stored column data is not touched, and a layer another door + * put under the package id is kept. */ replacingPackageBody(packageId: string | undefined, manifest: ObjectStackManifest, register: () => T): T { // [#33949 codemod] The body moved to `registry-items.ts` (see `ItemsHost`). @@ -6096,13 +6103,16 @@ export class SchemaRegistry { noteItem: (...a) => registry.noteItem(...a), noteItemOrder: (...a) => registry.noteItemOrder(...a), noteSecurityCatalogClaim: (...a) => registry.noteSecurityCatalogClaim(...a), + get objectContributors() { return registry.objectContributors; }, get openPackageBody() { return registry.openPackageBody; }, set openPackageBody(v) { registry.openPackageBody = v; }, orderedOverlayTier: (...a) => registry.orderedOverlayTier(...a), + get packageBodyExtensions() { return registry.packageBodyExtensions; }, get packageBodyItems() { return registry.packageBodyItems; }, get restorePoint() { return registry.restorePoint; }, get securityCatalogClaims() { return registry.securityCatalogClaims; }, unregisterPicklistExtensionsByPackage: (...a) => registry.unregisterPicklistExtensionsByPackage(...a), + withdrawObjectExtension: (...a) => registry.withdrawObjectExtension(...a), withdrawPackageBodyItemsNotShipped: (...a) => registry.withdrawPackageBodyItemsNotShipped(...a), withdrawPackageClaimsNotDeclared: (...a) => registry.withdrawPackageClaimsNotDeclared(...a), })); @@ -6242,6 +6252,7 @@ export class SchemaRegistry { noteItem: (...a) => registry.noteItem(...a), noteItemType: (...a) => registry.noteItemType(...a), get objectContributors() { return registry.objectContributors; }, + get packageBodyExtensions() { return registry.packageBodyExtensions; }, get packageBodyItems() { return registry.packageBodyItems; }, recordBareNameClaims: (...a) => registry.recordBareNameClaims(...a), recordDefaultRecordPageClaims: (...a) => registry.recordDefaultRecordPageClaims(...a), @@ -6320,6 +6331,7 @@ export class SchemaRegistry { get multiTenant() { return registry.multiTenant; }, get objectContributors() { return registry.objectContributors; }, get objectKeysByShortName() { return registry.objectKeysByShortName; }, + noteObjectEntry: (...a) => registry.noteObjectEntry(...a), packagedRules: (...a) => registry.packagedRules(...a), registerObject: (...a) => registry.registerObject(...a), resolveObject: (...a) => registry.resolveObject(...a), diff --git a/packages/objectql/src/reregister-extension-withdraw-35609.test.ts b/packages/objectql/src/reregister-extension-withdraw-35609.test.ts new file mode 100644 index 00000000000..231981bc1d9 --- /dev/null +++ b/packages/objectql/src/reregister-extension-withdraw-35609.test.ts @@ -0,0 +1,217 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35609] A package registered again serves exactly the extensions its + * current manifest declares. + * + * ## What was wrong + * + * The extend branch of object registration replaces a package's previous + * contribution to a target only when the new registration names that same + * target. A body registered again without an `objectExtensions` entry it used + * to carry left the old extension registered, so its fields, validations and + * indexes stayed on the served object until a restart. The real doors that + * re-register a package without uninstalling it first: the `os dev` artifact + * reload (`metadata:reloaded` → `ObjectQLPlugin` re-registering each installed + * body) and the marketplace install-local door's upgrade or re-install + * (`manifest.register`, pinned in `@objectstack/cloud-connection`). + * + * ## What these pin + * + * - re-registering without the extension withdraws it: the fields, the + * validation and the index it added are no longer served, and the target's + * owner layer is untouched; + * - CONTROL (already right): re-registering with a renamed field serves the + * new field and not the old one; + * - another package's extension of the same target is untouched; + * - the same body registered again keeps its extension; + * - an extension registered under the package id outside a body (the + * `object_extension` item door's layer) is not the body's and is kept; + * - a refusal later in the same registration run puts the withdrawn + * extension back; + * - the reload door: an artifact reload whose module no longer extends the + * base's object withdraws the extension. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin } from './plugin.js'; +import { ObjectQL } from './engine.js'; + +type ManifestService = { register(artifact: unknown, options?: { source?: 'code' | 'marketplace' }): Promise }; + +const CORE = 'com.t.core'; +const MOD = 'com.t.mod'; +const OTHER = 'com.t.other'; + +const text = (label: string) => ({ type: 'text', label }); + +const core = () => ({ + id: CORE, + name: 'core', + version: '1.0.0', + type: 'app', + namespace: 'crm', + objects: [{ name: 'crm_line', label: 'Line', fields: { name: { name: 'name', type: 'text', label: 'Name' } } }], +}); + +/** The module at `version`, extending `crm_line` with `extension` (none when `undefined`). */ +const mod = (version: string, extension?: Record) => ({ + id: MOD, + name: 'mod', + version, + type: 'module', + dependencies: { [CORE]: '^1.0.0' }, + objectExtensions: extension === undefined ? [] : [{ extend: 'crm_line', ...extension }], +}); + +const ACCOUNT_EXTENSION = { + fields: { cb_account: { name: 'cb_account', type: 'text', label: 'A' } }, + validations: [{ name: 'cb_account_required', type: 'script', condition: 'record.cb_account == null', message: 'Account is required' }], + indexes: [{ name: 'crm_line_cb_account', fields: ['cb_account'] }], +}; + +/** The served `crm_line`, as every read of it sees it. */ +function served(ql: ObjectQL) { + const line = ql.registry.getObject('crm_line') as any; + return { + fields: Object.keys(line?.fields ?? {}).filter((f) => f === 'name' || f.startsWith('cb_')).sort(), + validations: (line?.validations ?? []).map((v: any) => v.name).filter((n: string) => n.startsWith('cb_')), + indexes: (line?.indexes ?? []).map((i: any) => i.name).filter((n: string) => n.startsWith('crm_line_cb_')), + layers: ql.registry.getObjectContributors('crm_line').map((c) => `${c.packageId}:${c.ownership}`), + }; +} + +function bare(): ObjectQL { + const ql = new ObjectQL(); + ql.registry.logLevel = 'silent'; + ql.registerApp(core() as any); + ql.registerApp(mod('1.0.0', ACCOUNT_EXTENSION) as any); + return ql; +} + +describe('[#35609] a re-registered package serves exactly the extensions its current manifest declares', () => { + it('re-registering without the extension withdraws its fields, validation and index; the owner stays', () => { + const ql = bare(); + expect(served(ql)).toEqual({ + fields: ['cb_account', 'name'], + validations: ['cb_account_required'], + indexes: ['crm_line_cb_account'], + layers: [`${CORE}:own`, `${MOD}:extend`], + }); + + ql.registerApp(mod('1.0.1') as any); + + expect(served(ql)).toEqual({ fields: ['name'], validations: [], indexes: [], layers: [`${CORE}:own`] }); + expect(ql.registry.getObjectExtensionsOf(MOD)).toEqual([]); + }); + + it('CONTROL: re-registering with a renamed field serves the new field and not the old one', () => { + const ql = bare(); + ql.registerApp(mod('1.0.1', { fields: { cb_account2: { name: 'cb_account2', type: 'text', label: 'A2' } } }) as any); + expect(served(ql)).toMatchObject({ fields: ['cb_account2', 'name'], layers: [`${CORE}:own`, `${MOD}:extend`] }); + }); + + it('another package\'s extension of the same target is untouched', () => { + const ql = bare(); + ql.registerApp({ id: OTHER, name: 'other', version: '1.0.0', type: 'module', objectExtensions: [{ extend: 'crm_line', fields: { cb_other: text('Other') } }] } as any); + + ql.registerApp(mod('1.0.1') as any); + + expect(served(ql)).toMatchObject({ fields: ['cb_other', 'name'], layers: [`${CORE}:own`, `${OTHER}:extend`] }); + }); + + it('the same body registered again keeps its extension', () => { + const ql = bare(); + const before = served(ql); + ql.registerApp(mod('1.0.0', ACCOUNT_EXTENSION) as any); + expect(served(ql)).toEqual(before); + }); + + it('an extension registered under the package id outside a body is not the body\'s, and is kept', () => { + const ql = new ObjectQL(); + ql.registry.logLevel = 'silent'; + ql.registerApp(core() as any); + ql.registerApp({ ...core(), id: OTHER, name: 'other', namespace: 'oth', objects: [{ name: 'oth_thing', label: 'Thing', fields: { name: text('Name') } }] } as any); + ql.registerApp(mod('1.0.0', ACCOUNT_EXTENSION) as any); + // The `object_extension` item door's layer: registered under MOD's id by no body. + ql.registry.registerObject({ name: 'oth_thing', fields: { cb_side: text('Side') } } as any, MOD, undefined, 'extend'); + + ql.registerApp(mod('1.0.1') as any); + + expect(served(ql).fields).toEqual(['name']); + expect(Object.keys((ql.registry.getObject('oth_thing') as any).fields)).toContain('cb_side'); + }); + + it('a refusal later in the same registration run puts the withdrawn extension back', () => { + const ql = bare(); + const before = served(ql); + let refusal: any; + try { + ql.registry.restoringOnRefusal(() => { + ql.registerApp(mod('1.0.1') as any); + expect(served(ql).fields).toEqual(['name']); + throw Object.assign(new Error('a later member of the artifact is refused'), { code: 'INVALID_METADATA', status: 422 }); + }); + } catch (e) { + refusal = e; + } + expect(refusal).toMatchObject({ code: 'INVALID_METADATA', status: 422 }); + expect(served(ql)).toEqual(before); + // …and the record of what the body shipped is put back too: the next + // re-registration without the extension still withdraws it. + ql.registerApp(mod('1.0.1') as any); + expect(served(ql).fields).toEqual(['name']); + }); +}); + +// ── the reload door (`os dev`): `metadata:reloaded` re-registers each installed body ── + +const kernels: ObjectKernel[] = []; +afterEach(async () => { + while (kernels.length) { + const kernel = kernels.pop()!; + if (kernel.getState() === 'running') await kernel.shutdown(); + } +}); + +const artifact = (members: unknown[]) => ({ id: 'com.t.suite', version: '1.0.0', packages: members.map((manifest) => ({ manifest })) }); + +/** A kernel whose cold boot registers `atBoot` through the `manifest` service, and the reload announce. */ +async function bootWith(atBoot: unknown) { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never); + kernels.push(kernel); + let trigger: ((name: string, payload: unknown) => Promise) | undefined; + await kernel.use(new ObjectQLPlugin()); + await kernel.use({ + name: 'test.35609.boot', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + init: async () => {}, + start: async (ctx: { getService(name: string): T; trigger: (name: string, payload: unknown) => Promise }) => { + trigger = (name, payload) => ctx.trigger(name, payload); + await ctx.getService('manifest').register(atBoot); + }, + } as never); + await kernel.bootstrap(); + const ql = kernel.getService('objectql'); + ql.registry.logLevel = 'silent'; + return { ql, reload: (m: unknown) => trigger!('metadata:reloaded', { metadata: m }) }; +} + +describe('[#35609] the artifact reload door withdraws an extension the reloaded module no longer declares', () => { + it('a reload whose module drops its extension of the base\'s object serves the object without its fields', async () => { + const { ql, reload } = await bootWith(artifact([core(), mod('1.0.0', ACCOUNT_EXTENSION)])); + expect(served(ql).fields).toEqual(['cb_account', 'name']); + + await reload(artifact([core(), mod('1.0.0')])); + + expect(served(ql)).toEqual({ fields: ['name'], validations: [], indexes: [], layers: [`${CORE}:own`] }); + }); + + it('CONTROL: a reload that keeps the extension keeps its fields', async () => { + const { ql, reload } = await bootWith(artifact([core(), mod('1.0.0', ACCOUNT_EXTENSION)])); + await reload(artifact([core(), mod('1.0.0', ACCOUNT_EXTENSION)])); + expect(served(ql).fields).toEqual(['cb_account', 'name']); + }); +});