From b2ebdc834bf110df98af436ab75de7c694b29b7f Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 03:43:31 +0000 Subject: [PATCH 1/5] test(objectql,cloud-connection): measure a re-registered package that drops an object extension (WIP probes) Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh Co-authored-by: Claude --- ...eregister-extension-withdraw-35609.test.ts | 193 ++++++++++++++++ ...eregister-extension-withdraw-35609.test.ts | 217 ++++++++++++++++++ 2 files changed, 410 insertions(+) create mode 100644 packages/cloud-connection/src/marketplace-install-local-reregister-extension-withdraw-35609.test.ts create mode 100644 packages/objectql/src/reregister-extension-withdraw-35609.test.ts 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..40fe6705095 --- /dev/null +++ b/packages/cloud-connection/src/marketplace-install-local-reregister-extension-withdraw-35609.test.ts @@ -0,0 +1,193 @@ +// 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('READINGS (measure first)', async () => { + const k = await bootDoor(); + try { + const r1 = await k.post(mod('1.0.0', { extends: true })); + console.log('install v1', r1.status, JSON.stringify(r1.payload?.data?.hotLoaded), k.servedFields()); + await k.ql.insert('crm_line', { id: 'l1', name: 'one', cb_account: 'ACME' }, SYSTEM as any); + console.log('column after v1', JSON.stringify(await k.column())); + const dry = await k.post({ ...mod('1.0.1', { extends: false }), dryRun: true }); + console.log('dry run', dry.status, JSON.stringify(dry.payload?.data?.plan?.fields ?? dry.payload, null, 0).slice(0, 2000)); + console.log('dry env', JSON.stringify(dry.payload?.data?.environment ?? null).slice(0, 1000)); + const r2 = await k.post(mod('1.0.1', { extends: false })); + console.log('upgrade v1.0.1', r2.status, JSON.stringify(r2.payload).slice(0, 1500)); + console.log('served after upgrade', k.servedFields()); + console.log('column after upgrade', JSON.stringify(await k.column())); + const rows = await k.ql.find('crm_line', { where: {}, ...SYSTEM } as any); + console.log('find after upgrade', JSON.stringify(rows)); + const r3 = await k.post(mod('1.0.1', { extends: true })); + console.log('reinstall same version w/ ext', r3.status, k.servedFields()); + const r4 = await k.post(mod('1.0.1', { extends: false })); + console.log('reinstall same version w/o ext', r4.status, JSON.stringify(r4.payload).slice(0, 600), k.servedFields()); + console.log('warns', JSON.stringify(k.logger.warn.mock.calls.map((c: any[]) => String(c[0]).slice(0, 300)))); + } finally { + await settle(k); + } + }, 60_000); +}); 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']); + }); +}); From fe51ef458b364e279468ff4ef390011728d0140a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:10:38 +0000 Subject: [PATCH 2/5] fix(objectql): a re-registered package body withdraws the object extensions its new manifest no longer declares Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh Co-authored-by: Claude --- packages/objectql/src/registry-items.ts | 57 ++++++++++++++++++- packages/objectql/src/registry-packages.ts | 6 +- .../objectql/src/registry-platform-global.ts | 6 +- packages/objectql/src/registry.ts | 36 +++++++++++- 4 files changed, 100 insertions(+), 5 deletions(-) diff --git a/packages/objectql/src/registry-items.ts b/packages/objectql/src/registry-items.ts index cf0545e7c87..68034c906d5 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 { /** @@ -203,10 +223,15 @@ export class ItemsFacet { } /** 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 { + 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 +239,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 239c9c0f46d..22adf441f22 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -3738,6 +3738,11 @@ export class SchemaRegistry { * layer and every other package's extension stay exactly where they are; a * package's whole set leaves with {@link unregisterObjectsByPackage}. * + * [#35609] Also the withdrawal a re-registered package body makes of an + * extension its new manifest no longer declares ({@link replacingPackageBody}). + * The object's layers are recorded in an open registration run before the + * removal, so a refusal later in that run puts the layer back. + * * @returns whether a contribution was removed (idempotent: `false` when the * package contributes no extension to the object). */ @@ -4554,6 +4559,14 @@ export class SchemaRegistry { */ private readonly packageBodyItems = new Map>(); + /** + * [#35609] Package id → the object extension layers its last body + * registration wrote ({@link replacingPackageBody}), by object key: the + * layer itself, so a layer another door has since put in the package's slot + * of that object is told apart. Forgotten by {@link uninstallPackage}. + */ + private readonly packageBodyExtensions = new Map>(); + /** The body registration {@link replacingPackageBody} has open, while it runs. */ private openPackageBody: { readonly packageId: string; readonly written: Set } | undefined; @@ -4582,8 +4595,22 @@ 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. + * + * [#35609] The same holds for the package's object extensions: an + * `objectExtensions` entry the previous body registered for a target the + * new body no longer extends is withdrawn (`withdrawObjectExtension`, the + * per-target withdrawal the `object_extension` item delete uses), so the + * target serves exactly the extensions the current manifest declares — + * fields, validations, indexes and the rest of the layer go with it. 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. Stored column data is not touched: the field is no longer + * served, and schema sync drops no column. Only the layer the previous body + * wrote is withdrawn — one another door registered under the package id (the + * `object_extension` item door) is kept — and the withdrawal is recorded in + * the open run, so a refusal later in it puts the layer back. Owned objects + * the new body no longer ships are not touched here. */ replacingPackageBody(packageId: string | undefined, manifest: ObjectStackManifest, register: () => T): T { // [#33949 codemod] The body moved to `registry-items.ts` (see `ItemsHost`). @@ -6078,13 +6105,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), })); @@ -6222,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), @@ -6300,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), From f8c6e018405d9404c8df5410efbe7b46b93cb175 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 04:24:27 +0000 Subject: [PATCH 3/5] test(cloud-connection): pin the install-local upgrade and re-install that drop an object extension; changeset Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh Co-authored-by: Claude --- .../35609-reregister-extension-withdraw.md | 14 +++++ ...eregister-extension-withdraw-35609.test.ts | 63 +++++++++++++------ 2 files changed, 59 insertions(+), 18 deletions(-) create mode 100644 .changeset/35609-reregister-extension-withdraw.md 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 index 40fe6705095..45f85d4b768 100644 --- 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 @@ -165,27 +165,54 @@ async function settle(k: { kernel: ObjectKernel }) { } describe('[#35609] install-local: a version that no longer extends an object serves it without the extension', () => { - it('READINGS (measure first)', async () => { + 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 { - const r1 = await k.post(mod('1.0.0', { extends: true })); - console.log('install v1', r1.status, JSON.stringify(r1.payload?.data?.hotLoaded), k.servedFields()); - await k.ql.insert('crm_line', { id: 'l1', name: 'one', cb_account: 'ACME' }, SYSTEM as any); - console.log('column after v1', JSON.stringify(await k.column())); + 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 as any); + + // 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 }); - console.log('dry run', dry.status, JSON.stringify(dry.payload?.data?.plan?.fields ?? dry.payload, null, 0).slice(0, 2000)); - console.log('dry env', JSON.stringify(dry.payload?.data?.environment ?? null).slice(0, 1000)); - const r2 = await k.post(mod('1.0.1', { extends: false })); - console.log('upgrade v1.0.1', r2.status, JSON.stringify(r2.payload).slice(0, 1500)); - console.log('served after upgrade', k.servedFields()); - console.log('column after upgrade', JSON.stringify(await k.column())); - const rows = await k.ql.find('crm_line', { where: {}, ...SYSTEM } as any); - console.log('find after upgrade', JSON.stringify(rows)); - const r3 = await k.post(mod('1.0.1', { extends: true })); - console.log('reinstall same version w/ ext', r3.status, k.servedFields()); - const r4 = await k.post(mod('1.0.1', { extends: false })); - console.log('reinstall same version w/o ext', r4.status, JSON.stringify(r4.payload).slice(0, 600), k.servedFields()); - console.log('warns', JSON.stringify(k.logger.warn.mock.calls.map((c: any[]) => String(c[0]).slice(0, 300)))); + 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 any)) 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); } From 555ef3e2c7c32127acdc5145ce01d78e87c96cd6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 05:25:34 +0000 Subject: [PATCH 4/5] test(cloud-connection): type the 35609 pin's query options instead of casting them Claude-Session: https://claude.ai/code/session_01FEkQ5miLqNucRZevceHwNh Co-authored-by: Claude --- ...-install-local-reregister-extension-withdraw-35609.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 index 45f85d4b768..2b4f225c7ab 100644 --- 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 @@ -170,7 +170,7 @@ describe('[#35609] install-local: a version that no longer extends an object ser 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 as any); + 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 }); @@ -183,7 +183,7 @@ describe('[#35609] install-local: a version that no longer extends an object ser expect(upgraded.payload.data.hotLoaded).toBe(true); expect(k.servedFields()).toEqual(['name']); - const [row] = (await k.ql.find('crm_line', { where: {}, ...SYSTEM } as any)) as Array>; + 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. From 368b000bed24b936e4d4a5610da4f3a637c2d6e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 22 Nov 2026 10:33:09 +0000 Subject: [PATCH 5/5] refactor(objectql): keep the #35609 prose out of the registry facade so it stays under its line ceiling Merged with main, registry.ts measured 6441 lines against its facade line ceiling of 6426 (merge-queue red in check-facade-delegation-only N6). The facade does not grow: the detailed extension-withdrawal prose moves to the facet docblock (registry-items.ts), the facade keeps a short contract paragraph. No code change; 6421 lines, 5 under the ceiling. Co-authored-by: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTeURPvEm465RcoYEC --- packages/objectql/src/registry-items.ts | 15 ++++++++++- packages/objectql/src/registry.ts | 34 +++++-------------------- 2 files changed, 21 insertions(+), 28 deletions(-) diff --git a/packages/objectql/src/registry-items.ts b/packages/objectql/src/registry-items.ts index 68034c906d5..5646d64a20a 100644 --- a/packages/objectql/src/registry-items.ts +++ b/packages/objectql/src/registry-items.ts @@ -222,7 +222,20 @@ export class ItemsFacet { return { removed, orphanedOverlays }; } - /** The body of `SchemaRegistry#replacingPackageBody`; the method's docblock there is its contract. */ + /** + * 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; diff --git a/packages/objectql/src/registry.ts b/packages/objectql/src/registry.ts index 08b18e96c28..5e3a944a849 100644 --- a/packages/objectql/src/registry.ts +++ b/packages/objectql/src/registry.ts @@ -3756,11 +3756,6 @@ export class SchemaRegistry { * layer and every other package's extension stay exactly where they are; a * package's whole set leaves with {@link unregisterObjectsByPackage}. * - * [#35609] Also the withdrawal a re-registered package body makes of an - * extension its new manifest no longer declares ({@link replacingPackageBody}). - * The object's layers are recorded in an open registration run before the - * removal, so a refusal later in that run puts the layer back. - * * @returns whether a contribution was removed (idempotent: `false` when the * package contributes no extension to the object). */ @@ -4577,12 +4572,7 @@ export class SchemaRegistry { */ private readonly packageBodyItems = new Map>(); - /** - * [#35609] Package id → the object extension layers its last body - * registration wrote ({@link replacingPackageBody}), by object key: the - * layer itself, so a layer another door has since put in the package's slot - * of that object is told apart. Forgotten by {@link uninstallPackage}. - */ + /** [#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. */ @@ -4613,22 +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. - * - * [#35609] The same holds for the package's object extensions: an - * `objectExtensions` entry the previous body registered for a target the - * new body no longer extends is withdrawn (`withdrawObjectExtension`, the - * per-target withdrawal the `object_extension` item delete uses), so the - * target serves exactly the extensions the current manifest declares — - * fields, validations, indexes and the rest of the layer go with it. 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. Stored column data is not touched: the field is no longer - * served, and schema sync drops no column. Only the layer the previous body - * wrote is withdrawn — one another door registered under the package id (the - * `object_extension` item door) is kept — and the withdrawal is recorded in - * the open run, so a refusal later in it puts the layer back. Owned objects - * the new body no longer ships 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`).