From 0800714648ceb169aa5ef34f08a472ac1a69aff5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 02:18:37 +0000 Subject: [PATCH 1/9] fix(metadata): unregistering the host package keeps the environment's own object, view, app, hook and dashboard rows The boot priming pass stamps a package-less stored row with the host's package. For a type not stored per (package, name) the stamp stays, and unregisterPackage(host) took it as membership, deleting the environment's own rows from the registry and storage. The removal now leaves an item a stored-row loader handed on naming no package whose only claim to the package is that stamp. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgThzreKNjha83MypKs --- ...-host-unregister-keeps-environment-rows.md | 12 +++ .../src/loaders/database-loader.test.ts | 93 +++++++++++++++++++ packages/metadata/src/metadata-manager.ts | 39 +++++++- 3 files changed, 142 insertions(+), 2 deletions(-) create mode 100644 .changeset/32986-host-unregister-keeps-environment-rows.md diff --git a/.changeset/32986-host-unregister-keeps-environment-rows.md b/.changeset/32986-host-unregister-keeps-environment-rows.md new file mode 100644 index 00000000000..05931d80e3e --- /dev/null +++ b/.changeset/32986-host-unregister-keeps-environment-rows.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata': patch +--- + +fix(metadata): unregistering the host package keeps the environment's own object, view, app, hook and dashboard rows + +Clause-②: no — no released answer moves: `unregisterPackage` reads the `_packageId` stamp since #32198, which has not shipped, and with this change it leaves the environment's own rows as the released version does. The boot pass's stamp, and every reader of it, answer as before. +Metadata-protocol: none + +On a host that declares its package and stores metadata in a database, the boot pass stamps each stored row that names no package with the host's package. For a type not stored per `(package, name)` — `object`, `view`, `app`, `hook`, `dashboard` and the rest — that stamp stays, so ObjectQL still registers such an object as the host package's contribution. But `MetadataManager.unregisterPackage(host)` took the stamp as membership and deleted those rows, from memory and from the database: the environment's own items were lost when the host package was unregistered. + +`unregisterPackage` now leaves an item that a stored-row loader handed on naming no package and that names the package only by the stamp. The host's own items (a row whose stored body carries the host's stamp, an item registered for the host in memory or from files) are removed as before. Types stored per `(package, name)` are unchanged here. diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index 933c1192d32..a1677a25ec4 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -2930,3 +2930,96 @@ describe('[#32521] the boot priming pass primes every holder of a name', () => { expect((await new DatabaseLoader({ driver }).loadManyKeyed('email_template')).map((entry) => entry.packageId)).toEqual([ALPHA, BETA]); }); }); + +/** + * [#32986; follow-up of #32198, ADR-0150 D4] On a host that declares its + * package, the boot priming pass stamps a package-less stored row of a type + * NOT stored per `(package, name)` (`object`, `view`, `app`, `hook`, + * `dashboard` …) with the host's package (`applyProtection`), and the stamp + * stays: an `object` row so stamped is still registered by ObjectQL as the + * host package's contribution (`_packageId ?? 'metadata-service'`). But since + * #32198 `unregisterPackage` selects a package's items by `_packageId` too, + * so `unregisterPackage(host)` deleted the environment's own rows — the + * registry entry and the stored row both. The removal now leaves an item a + * stored-row loader handed on naming no package, whose only claim to the + * package is the stamp the pass put on it. + * + * BEFORE (`main`): every case below not marked CONTROL lost the row (the + * registry entry gone, the stored row deleted). The CONTROLs answer on `main` + * as here. + */ +describe('[#32986] unregisterPackage of the host package keeps the environment\'s own rows the boot pass stamped with the host', () => { + const HOST = 'com.host.app'; + const OTHER = 'com.other.app'; + /** One name per type, each a name the type's own write rule keeps as it is. */ + const ITEMS: ReadonlyArray = [ + ['object', 'env_account'], ['view', 'env_account.all'], ['app', 'env_app'], ['hook', 'env_hook'], ['dashboard', 'env_dashboard'], + ]; + let driver: IDataDriver; + + const seed = (type: string, name: string, packageId: string | null, body: Record = {}) => + driver.create('sys_metadata', { + id: `${type}_${name}_${packageId ?? 'env'}`, type, name, state: 'active', version: 1, checksum: `${type}_${name}_${packageId ?? 'env'}`, + source: 'database', package_id: packageId, metadata: JSON.stringify({ name, label: packageId ?? 'env', ...body }), + }); + /** The real pass over one database loader, on a host that declares `hostPackage`. */ + const bootPass = async (hostPackage?: string) => { + const plugin = new MetadataPlugin({ ...(hostPackage ? { packageId: hostPackage } : {}), watch: false, config: { bootstrap: 'eager' } }); + const m = (plugin as any).manager as MetadataManager; + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver })); + await (plugin as any)._loadFromFileSystem({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }); + return m; + }; + /** Per item: the registry's stamp, what a read answers, and whether its stored row is still there. */ + const state = async (m: MetadataManager) => { + const out: unknown[] = []; + for (const [type, name] of ITEMS) { + const held = (m as any).registry.get(type)?.get(name) as { _packageId?: string } | undefined; + const read = (await m.get(type, name)) as { label?: string } | undefined; + const rows = await driver.find('sys_metadata', { where: { type, name } } as any); + out.push([type, held?._packageId ?? null, read?.label ?? null, rows.length]); + } + return out; + }; + + beforeEach(() => { + driver = createMockDriver(); + }); + + it('package-less rows of object, view, app, hook and dashboard, on a host declaring its package: the pass stamps them with the host as before, and unregisterPackage(host) keeps each registry entry and stored row (BEFORE: every one deleted)', async () => { + for (const [type, name] of ITEMS) await seed(type, name, null); + const m = await bootPass(HOST); + const primed = ITEMS.map(([type]) => [type, HOST, 'env', 1]); + expect(await state(m), 'the stamp, as before: the object contribution owner does not move').toEqual(primed); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(primed); + }); + + it('CONTROL the host\'s own rows (their bodies carry the host\'s stamp, as a host item the pass seeded is stored): unregisterPackage(host) still removes each, from the registry and storage', async () => { + for (const [type, name] of ITEMS) await seed(type, name, null, { _packageId: HOST }); + const m = await bootPass(HOST); + expect(await state(m)).toEqual(ITEMS.map(([type]) => [type, HOST, 'env', 1])); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(ITEMS.map(([type]) => [type, null, null, 0])); + }); + + it('an item registered in memory for the host (code) beside the environment\'s rows: unregisterPackage(host) removes the host\'s item and keeps the environment\'s (BEFORE: both removed)', async () => { + for (const [type, name] of ITEMS) await seed(type, name, null); + const m = await bootPass(HOST); + await m.registerInMemory('object', 'host_thing', { name: 'host_thing', label: 'code', _packageId: HOST }); + await m.unregisterPackage(HOST); + expect(await m.get('object', 'host_thing')).toBeUndefined(); + expect(await state(m)).toEqual(ITEMS.map(([type]) => [type, HOST, 'env', 1])); + }); + + it('CONTROL unregisterPackage of another package, and a host declaring no package: the environment\'s rows are untouched, unstamped on the second', async () => { + for (const [type, name] of ITEMS) await seed(type, name, null); + const m = await bootPass(HOST); + await m.unregisterPackage(OTHER); + expect(await state(m)).toEqual(ITEMS.map(([type]) => [type, HOST, 'env', 1])); + const bare = await bootPass(); + await bare.unregisterPackage(HOST); + expect(await state(bare)).toEqual(ITEMS.map(([type]) => [type, null, 'env', 1])); + }); +}); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index b361653b8d8..2fd11c33685 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -654,6 +654,17 @@ export class MetadataManager implements IMetadataService { * one with the host's package before it registers it ({@link slotViewOf}). */ private readonly storedPackagelessRows = new WeakSet(); + /** + * [#32986] The items of every OTHER type (one not stored per + * `(package, name)`: `object`, `view`, `app`, `hook`, `dashboard` …) that + * {@link loadMany} read from a stored-row loader (`datasource:`) naming no + * package: the environment's own rows. The boot priming pass stamps one with + * the host's declared package (`_packageId`), and the stamp stays — ObjectQL + * registers such an `object` as the host package's contribution — but the + * row is not the package's item, so {@link unregisterPackage} leaves it + * ({@link isStampedEnvironmentRow}). + */ + private readonly storedEnvironmentRows = new WeakSet(); /** * [ADR-0150 D4, #32791] The {@link storedPackagelessRows} whose registration * replaced an item no loader handed out (one registered in memory or by @@ -2674,6 +2685,10 @@ export class MetadataManager implements IMetadataService { * `(package, name)` drops this package's slot and keeps another package's * same-named item — and, for such a type, the storage half deletes only this * package's row and the `deleted` event names this package. + * + * [#32986] Of every other type, an environment row the boot priming pass + * stamped with this package (the host's) is not one of its items, and stays + * ({@link isStampedEnvironmentRow}). */ async unregisterPackage(packageName: string): Promise { // Collect all items to delete (type and name pairs). [#32517] One entry @@ -2686,6 +2701,10 @@ export class MetadataManager implements IMetadataService { for (const [key, data] of typeStore) { // [#32246] A by-package type: also every item in the package's slot, // a package-less customization of its item (D4) included. + // [#32986] Not the environment's own row the boot pass stamped with + // this package: since #32198 the stamp alone made it a member, and the + // removal deleted it from the registry and from storage. + if (!slotted && this.isStampedEnvironmentRow(data, packageName)) continue; if (isPackageMember(data, packageName) || (slotted && slotPackageOf(key) === packageName)) { const slot = `${type}\u0000${slotOfKey(key)}`; const entry = itemsToDelete.get(slot); @@ -2704,6 +2723,20 @@ export class MetadataManager implements IMetadataService { } } + /** + * [#32986] Whether `data` is one of the {@link storedEnvironmentRows} that + * names `packageId` only by the `_packageId` stamp — the boot priming pass's + * host stamp, which `applyProtection` writes on an unstamped item alone. The + * row's own body named no package when the loader handed it on, so + * `packageId` / `package` naming the package is the item's own claim (the + * row is the package's, as {@link isPackageMember} reads it). + */ + private isStampedEnvironmentRow(data: unknown, packageId: string): boolean { + if (data === null || typeof data !== 'object' || !this.storedEnvironmentRows.has(data)) return false; + const meta = data as { packageId?: unknown; package?: unknown; _packageId?: unknown }; + return meta._packageId === packageId && meta.packageId !== packageId && meta.package !== packageId; + } + /** * [#22113] The registry items that belong to `packageId`, for the two * package-wide writes ({@link publishPackage}, {@link revertPackage}). @@ -3845,8 +3878,10 @@ export class MetadataManager implements IMetadataService { if (item !== null && typeof item === 'object') { this.loadedFrom.set(item, loader); // [#32791] Read here, before any caller stamps it. - if (PACKAGE_SLOTTED_STORE_TYPES.has(type) && loader.contract.protocol === 'datasource:' && indexedItemPackageId(item) === undefined) { - this.storedPackagelessRows.add(item); + if (loader.contract.protocol === 'datasource:' && indexedItemPackageId(item) === undefined) { + if (PACKAGE_SLOTTED_STORE_TYPES.has(type)) this.storedPackagelessRows.add(item); + // [#32986] Read here too, before the boot pass stamps it. + else this.storedEnvironmentRows.add(item); } } }); From 426f47c9a9c3c0e55f307b1def9075e3c804b514 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 03:02:33 +0000 Subject: [PATCH 2/9] test(metadata): the #32986 pin's stored-row read keeps the test surface at its erasure ceiling Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgThzreKNjha83MypKs --- packages/metadata/src/loaders/database-loader.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index a1677a25ec4..d157a39c403 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -2977,7 +2977,7 @@ describe('[#32986] unregisterPackage of the host package keeps the environment\' for (const [type, name] of ITEMS) { const held = (m as any).registry.get(type)?.get(name) as { _packageId?: string } | undefined; const read = (await m.get(type, name)) as { label?: string } | undefined; - const rows = await driver.find('sys_metadata', { where: { type, name } } as any); + const rows = await driver.find('sys_metadata', { where: { type, name } } as never); out.push([type, held?._packageId ?? null, read?.label ?? null, rows.length]); } return out; From a43fc250331266aaf1e9291de90dfeede2136870 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 03:35:48 +0000 Subject: [PATCH 3/9] test(metadata): a stored row naming the host by the legacy package key is still unregistered with it; state the mark's limit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgThzreKNjha83MypKs --- .../32986-host-unregister-keeps-environment-rows.md | 6 ++++-- .../metadata/src/loaders/database-loader.test.ts | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/.changeset/32986-host-unregister-keeps-environment-rows.md b/.changeset/32986-host-unregister-keeps-environment-rows.md index 05931d80e3e..8288ff87fbf 100644 --- a/.changeset/32986-host-unregister-keeps-environment-rows.md +++ b/.changeset/32986-host-unregister-keeps-environment-rows.md @@ -4,9 +4,11 @@ fix(metadata): unregistering the host package keeps the environment's own object, view, app, hook and dashboard rows -Clause-②: no — no released answer moves: `unregisterPackage` reads the `_packageId` stamp since #32198, which has not shipped, and with this change it leaves the environment's own rows as the released version does. The boot pass's stamp, and every reader of it, answer as before. +Clause-②: no — no released answer moves: `unregisterPackage` reads the `_packageId` stamp since #32198, which has not shipped, and with this change it leaves the environment's own rows the boot pass marked, as the released version does. The boot pass's stamp, and every reader of it, answer as before. Metadata-protocol: none On a host that declares its package and stores metadata in a database, the boot pass stamps each stored row that names no package with the host's package. For a type not stored per `(package, name)` — `object`, `view`, `app`, `hook`, `dashboard` and the rest — that stamp stays, so ObjectQL still registers such an object as the host package's contribution. But `MetadataManager.unregisterPackage(host)` took the stamp as membership and deleted those rows, from memory and from the database: the environment's own items were lost when the host package was unregistered. -`unregisterPackage` now leaves an item that a stored-row loader handed on naming no package and that names the package only by the stamp. The host's own items (a row whose stored body carries the host's stamp, an item registered for the host in memory or from files) are removed as before. Types stored per `(package, name)` are unchanged here. +`unregisterPackage` now leaves an item that a stored-row loader handed on naming no package and that names the package only by the stamp. The host's own items (a row whose stored body carries the host's stamp or names it under the legacy `package` key, an item registered for the host in memory or from files) are removed as before. Types stored per `(package, name)` are unchanged here. + +The limit: a row is kept when the boot pass marked it and nothing has rewritten it since. The mark is on the item the pass registered. A later write that replaces that item with a copy still stamped with the host (ObjectQL's late-manifest bridge, `publishPackage` and `revertPackage` of the host) drops the mark and stores the stamp in the row, and `unregisterPackage(host)` then deletes that row again. #33003 closes that before the release that ships #32198. diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index d157a39c403..dcc9be6ff8b 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -3004,6 +3004,19 @@ describe('[#32986] unregisterPackage of the host package keeps the environment\' expect(await state(m)).toEqual(ITEMS.map(([type]) => [type, null, null, 0])); }); + /** + * [#32986, review S2] The legacy `package` key is the item's own claim, as + * 18.3.0's `unregisterPackage` read it: the row is the host's, though its + * stored body names no package the store's reads index (`_packageId`). + */ + it('CONTROL the host\'s own rows naming it through the legacy `package` key in their stored bodies: unregisterPackage(host) still removes each, from the registry and storage', async () => { + for (const [type, name] of ITEMS) await seed(type, name, null, { package: HOST }); + const m = await bootPass(HOST); + expect(await state(m)).toEqual(ITEMS.map(([type]) => [type, HOST, 'env', 1])); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(ITEMS.map(([type]) => [type, null, null, 0])); + }); + it('an item registered in memory for the host (code) beside the environment\'s rows: unregisterPackage(host) removes the host\'s item and keeps the environment\'s (BEFORE: both removed)', async () => { for (const [type, name] of ITEMS) await seed(type, name, null); const m = await bootPass(HOST); From 21ebb7adbe43db15b854cad2305a6bc97f95a5b8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:13:16 +0000 Subject: [PATCH 4/9] fix(metadata): a rewrite of an environment row the boot pass stamped keeps it the environment's, and stores it without the host stamp A copy that replaces such a row and still names the host by the stamp alone (ObjectQL's late-manifest bridge and its restore, its object-copy follow, publishPackage / revertPackage, importMetadata's merge) keeps the row's mark, and register stores the row without the host stamp, so the next boot reads it as the environment's own again. unregisterPackage(host) keeps it in process and after a reboot; the host's own rows are removed as before. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz4sWiJgVrx7vhMJSf --- .../src/loaders/database-loader.test.ts | 172 ++++++++++++++++++ packages/metadata/src/metadata-manager.ts | 76 +++++++- 2 files changed, 244 insertions(+), 4 deletions(-) diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index dcc9be6ff8b..fc86d204a2c 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -3036,3 +3036,175 @@ describe('[#32986] unregisterPackage of the host package keeps the environment\' expect(await state(bare)).toEqual(ITEMS.map(([type]) => [type, null, 'env', 1])); }); }); + +/** + * [#33003; follow-up of #32986, review S1 of PR #32999] The boot pass's mark + * on an environment row it stamped with the host rode the registry object, so + * a later write that registered a COPY still stamped with the host dropped it + * — and stored the stamp in the row's body, so the next boot read the row as + * the host's own too. `unregisterPackage(host)` then deleted the row again, in + * that process and after a restart. The writers measured, each driven here + * through the call it makes on this manager: + * + * - ObjectQL's late-manifest bridge, the `ownPreviousCopy` arm: another + * package extends the environment's object and the bridge re-registers the + * merged object stamped with its owner, the host (`register`, `notify: + * false`); its withdrawal counterpart `restoreExtendedObjectCopies` puts the + * owner's body back the same way; + * - ObjectQL's object-copy follow (`putObjectCopy` → `registerInMemory`); + * - `publishPackage(host)` and `revertPackage(host)`, over + * `collectPackageMembers`, which counts a stamped environment row as the + * host's; + * - `importMetadata` with `conflictResolution: 'merge'` (`{ ...existing, ...item }`). + * + * A copy that replaces such a row and still names the host by the stamp alone + * now keeps the row's mark, and the row is stored without the host stamp: the + * environment's own row, read as such at the next boot. The registry entry + * keeps the stamp (ObjectQL's owner does not move). + * + * Also pinned (review nits N1/N2 of PR #32999): a `state: 'draft'` row is + * treated like an `active` one, and the rule holds for non-slotted types + * beyond the five #32986 names (`page`, `report`; `flow` is stored per + * `(package, name)` and is not under this rule). + * + * BEFORE (#32999's head): every case below not marked CONTROL lost the row. + */ +describe('[#33003] a write that rewrites an environment row the boot pass stamped keeps it the environment\'s: unregisterPackage(host) keeps it in process and after a reboot', () => { + const HOST = 'com.host.app'; + const EXT = 'com.ext.app'; + /** [type, name, state]: one draft row (N1), and two non-slotted types beyond the five (N2). */ + const ITEMS: ReadonlyArray = [ + ['object', 'env_account', 'active'], ['object', 'env_draft', 'draft'], ['view', 'env_account.all', 'active'], + ['app', 'env_app', 'active'], ['hook', 'env_hook', 'active'], ['dashboard', 'env_dashboard', 'active'], + ['page', 'env_page', 'active'], ['report', 'env_report', 'active'], + ]; + const OBJECTS = ITEMS.filter(([type]) => type === 'object'); + let driver: IDataDriver; + + const seed = (type: string, name: string, state: string, body: Record) => + driver.create('sys_metadata', { + id: `${type}_${name}`, type, name, state, version: 1, checksum: `${type}_${name}`, + source: 'database', package_id: null, metadata: JSON.stringify({ name, label: 'env', ...body }), + }); + const bootPass = async () => { + const plugin = new MetadataPlugin({ packageId: HOST, watch: false, config: { bootstrap: 'eager' } }); + const m = (plugin as any).manager as MetadataManager; + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver })); + await (plugin as any)._loadFromFileSystem({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } }); + return m; + }; + /** Per item: the registry's stamp, whether a read answers it, and how many stored rows it has. */ + const state = async (m: MetadataManager, items: ReadonlyArray = ITEMS) => { + const out: unknown[] = []; + for (const [type, name] of items) { + const held = (m as any).registry.get(type)?.get(name) as { _packageId?: string } | undefined; + const rows = await driver.find('sys_metadata', { where: { type, name } } as never); + out.push([type, name, held?._packageId ?? null, (await m.get(type, name)) !== undefined, rows.length]); + } + return out; + }; + const kept = (items: ReadonlyArray = ITEMS) => items.map(([type, name]) => [type, name, HOST, true, 1]); + const gone = (items: ReadonlyArray = ITEMS) => items.map(([type, name]) => [type, name, null, false, 0]); + + /** Each writer, driven through the call it makes on the manager; `items` = the rows it rewrites. */ + const WRITES: ReadonlyArray<{ writer: string; items: typeof ITEMS; write: (m: MetadataManager) => Promise }> = [ + { + writer: 'ObjectQL\'s late-manifest bridge, ownPreviousCopy arm (an extender\'s field merged, re-registered stamped with the owner)', + items: OBJECTS, + write: async (m) => { + for (const [, name] of OBJECTS) { + const current = (m as any).registry.get('object').get(name) as Record; + await m.register('object', name, { ...current, fields: { ext_score: { type: 'number' } }, _packageId: HOST }, { notify: false }); + } + }, + }, + { + writer: 'the bridge, then restoreExtendedObjectCopies (the owner\'s body put back, stamped with the owner)', + items: OBJECTS, + write: async (m) => { + for (const [, name] of OBJECTS) { + await m.register('object', name, { name, label: 'env', fields: { ext_score: { type: 'number' } }, _packageId: HOST }, { notify: false }); + await m.register('object', name, { name, label: 'env', _packageId: HOST }, { notify: false }); + } + }, + }, + { + writer: 'ObjectQL\'s object-copy follow (registerInMemory of the served body, stamped with the owner)', + items: OBJECTS, + write: async (m) => { + for (const [, name] of OBJECTS) m.registerInMemory('object', name, { name, label: 'served', _packageId: HOST }); + }, + }, + { writer: 'publishPackage(host)', items: ITEMS, write: (m) => m.publishPackage(HOST, { validate: false }) }, + { + writer: 'publishPackage(host), then revertPackage(host)', + items: ITEMS, + write: async (m) => { + expect((await m.publishPackage(HOST, { validate: false })).success).toBe(true); + await m.revertPackage(HOST); + }, + }, + { + writer: 'importMetadata, conflictResolution merge', + items: ITEMS, + write: (m) => m.importMetadata( + Object.fromEntries(ITEMS.map(([type]) => [type, ITEMS.filter(([t]) => t === type).map(([, name]) => ({ name, description: 'imported' }))])), + { conflictResolution: 'merge' }, + ), + }, + ]; + + beforeEach(() => { + driver = createMockDriver(); + }); + + for (const { writer, items, write } of WRITES) { + it(`${writer}: unregisterPackage(host) in the same process keeps each rewritten row, registry entry and stored row (BEFORE: deleted)`, async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await write(m); + expect(await state(m, items), 'the stamp stays on the registry entry: the owner does not move').toEqual(kept(items)); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(kept()); + }); + + it(`${writer}: after a reboot from the same database, unregisterPackage(host) keeps each rewritten row (BEFORE: the stored stamp made it the host's, and it was deleted)`, async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + await write(await bootPass()); + const rebooted = await bootPass(); + expect(await state(rebooted)).toEqual(kept()); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted)).toEqual(kept()); + }); + + it(`CONTROL ${writer}: the host's own rows (stored bodies carrying its stamp) are still removed, in the same process and after a reboot`, async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, { _packageId: HOST }); + const m = await bootPass(); + await write(m); + const rebooted = await bootPass(); + expect(await state(rebooted)).toEqual(kept()); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted)).toEqual(gone()); + // The same rows, removed by the first process too (already gone from storage). + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(gone()); + }); + } + + it('CONTROL a copy that names the host by its own key (packageId) is the host\'s item: unregisterPackage(host) removes it', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await m.register('object', 'env_account', { name: 'env_account', label: 'env', packageId: HOST, _packageId: HOST }); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); + }); + + it('CONTROL unregisterPackage of the extender leaves the environment\'s object the bridge rewrote, and of another package nothing moves', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await WRITES[0].write(m); + await m.unregisterPackage(EXT); + expect(await state(m)).toEqual(kept()); + }); +}); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index 2fd11c33685..e8103c660b7 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -114,7 +114,7 @@ import { } from './package-slotted-store.js'; // [#5309] The stored ENVELOPE / authored BODY split — peeled before any spec // schema parses a stored row. See `stored-envelope.ts`. -import { peelStoredEnvelope, STORED_ENVELOPE_KEYS } from './stored-envelope.js'; +import { peelStoredEnvelope, STORED_BODY_KEY, STORED_ENVELOPE_KEYS } from './stored-envelope.js'; // [#13913] Registry-free expansion of an aggregated view container reached // through THIS manager's own store — see `getViewsByObject`. import { expandRuntimeViewContainer } from './view-container-expansion.js'; @@ -186,6 +186,37 @@ function isPackageMember(item: unknown, packageId: string): boolean { return meta?.packageId === packageId || meta?.package === packageId || meta?._packageId === packageId; } +/** + * [#32986, #33003] Whether `item` names `packageId` by the `_packageId` stamp + * alone: neither its own `packageId` nor the legacy `package` key names it. + */ +function namesPackageByStampAlone(item: object, packageId: string): boolean { + const meta = item as { packageId?: unknown; package?: unknown; _packageId?: unknown }; + return meta._packageId === packageId && meta.packageId !== packageId && meta.package !== packageId; +} + +/** + * [#33003] The body {@link MetadataManager.register} stores for an environment + * row the boot pass stamped with `stamp`: `data` without that stamp, at the top + * and in the two bodies a stored row nests — `metadata` (the publish envelope's + * body, which the store's package read peels to) and `publishedDefinition` + * (the snapshot `revertPackage` restores into `metadata`). The registry keeps + * `data` as it is, stamp included. A copy: `data` is never changed. + */ +function withoutEnvironmentRowStamp(data: Record, stamp: string): Record { + const stored: Record = { ...data }; + delete stored._packageId; + for (const key of [STORED_BODY_KEY, 'publishedDefinition'] as const) { + const nested = stored[key]; + if (nested === null || typeof nested !== 'object' || Array.isArray(nested)) continue; + if ((nested as { _packageId?: unknown })._packageId !== stamp) continue; + const body: Record = { ...(nested as Record) }; + delete body._packageId; + stored[key] = body; + } + return stored; +} + /** * [#5276, #32246, #32353] Whether {@link MetadataManager.unregister}'s storage * half deletes from `loader`: a `datasource:` loader that declares write @@ -1182,6 +1213,13 @@ export class MetadataManager implements IMetadataService { const existed = this.writeRegistryEntry(type, name, data); this.invalidateListCache(type); + // [#33003] An environment row the boot pass stamped is stored as the + // environment's own row: without the host stamp, so the next boot reads it + // naming no package again, whichever writer rewrote it + // ({@link withoutEnvironmentRowStamp}). + const stamp = this.environmentRowStamp(data); + const stored = stamp === undefined ? data : withoutEnvironmentRowStamp(data as Record, stamp); + // Persist only to database-backed loaders that declare write capability. // FilesystemLoader is read-only at runtime — writing to it can crash in // read-only environments (e.g. serverless, containerized deployments). @@ -1203,7 +1241,7 @@ export class MetadataManager implements IMetadataService { await loader.bindReadRowPackage?.(type, name, data); continue; } - await loader.save(type, name, data); + await loader.save(type, name, stored); } // Publish metadata.{type}.created / .updated event to realtime service. @@ -1316,6 +1354,8 @@ export class MetadataManager implements IMetadataService { this.storedRowsOverOwnItems.add(data); } } + // [#33003] A copy of an environment row the boot pass stamped, still stamped alone, is that row. + if (this.rewritesEnvironmentRow(typeStore.get(key), data)) this.storedEnvironmentRows.add(data as object); for (const replaced of replaces) typeStore.delete(replaced); typeStore.set(key, data); recordStoreWrite(typeStore, key); @@ -2733,8 +2773,36 @@ export class MetadataManager implements IMetadataService { */ private isStampedEnvironmentRow(data: unknown, packageId: string): boolean { if (data === null || typeof data !== 'object' || !this.storedEnvironmentRows.has(data)) return false; - const meta = data as { packageId?: unknown; package?: unknown; _packageId?: unknown }; - return meta._packageId === packageId && meta.packageId !== packageId && meta.package !== packageId; + return namesPackageByStampAlone(data, packageId); + } + + /** + * [#33003] The host stamp of `data` when it is one of the + * {@link storedEnvironmentRows} naming its package by that stamp alone + * ({@link isStampedEnvironmentRow}); `undefined` for every other item. + */ + private environmentRowStamp(data: unknown): string | undefined { + const stamp = (data as { _packageId?: unknown } | null | undefined)?._packageId; + return typeof stamp === 'string' && this.isStampedEnvironmentRow(data, stamp) ? stamp : undefined; + } + + /** + * [#33003] Whether writing `data` over `before` rewrites an environment row + * the boot pass stamped: `before` is such a row ({@link environmentRowStamp}), + * and `data` is a copy no loader handed out that still names that package by + * the stamp alone. Every writer that registers such a copy reaches this — + * ObjectQL's late-manifest bridge (the `ownPreviousCopy` re-register and + * `restoreExtendedObjectCopies`) and its object-copy follow + * (`registerInMemory`), `publishPackage` / `revertPackage` over + * {@link collectPackageMembers}, and `importMetadata`'s merge — so the copy + * keeps the row's mark instead of the mark riding the replaced object. An + * item a loader handed out (a file's, a stored row's) is that loader's + * item, never a copy: a stored row is marked by {@link loadMany} itself. + */ + private rewritesEnvironmentRow(before: unknown, data: unknown): boolean { + if (data === null || typeof data !== 'object' || data === before || this.loadedFrom.has(data)) return false; + const stamp = this.environmentRowStamp(before); + return stamp !== undefined && namesPackageByStampAlone(data, stamp); } /** From 4ceecfaf0492a8a3a4d7974e2932dd7d1c3543d1 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:15:14 +0000 Subject: [PATCH 5/9] test(metadata): a stored row naming the host, read again over a marked entry, is the host's; store only the envelope body unstamped Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz4sWiJgVrx7vhMJSf --- .../src/loaders/database-loader.test.ts | 19 ++++++++++++++++++ packages/metadata/src/metadata-manager.ts | 20 +++++++++---------- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index fc86d204a2c..7fa174deb92 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -3200,6 +3200,25 @@ describe('[#33003] a write that rewrites an environment row the boot pass stampe expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); }); + it('CONTROL a stored row that now names the host in its own body, read again by the pass over the marked entry, is the host\'s: unregisterPackage(host) removes it', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const plugin = new MetadataPlugin({ packageId: HOST, watch: false, config: { bootstrap: 'eager' } }); + const m = (plugin as any).manager as MetadataManager; + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver })); + const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }; + await (plugin as any)._loadFromFileSystem({ logger }); + // Another writer (a peer node, a CLI) stores the host's own row under the name. + await driver.update('sys_metadata', 'object_env_account', { metadata: JSON.stringify({ name: 'env_account', label: 'host', _packageId: HOST }), checksum: 'host' }); + // A fresh loader over the store (no read cache), as a reload reads it. + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver })); + await (plugin as any)._loadFromFileSystem({ logger }); + expect((m as any).registry.get('object').get('env_account')).toMatchObject({ label: 'host', _packageId: HOST }); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); + }); + it('CONTROL unregisterPackage of the extender leaves the environment\'s object the bridge rewrote, and of another package nothing moves', async () => { for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); const m = await bootPass(); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index e8103c660b7..78dbd8b9dd9 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -198,21 +198,19 @@ function namesPackageByStampAlone(item: object, packageId: string): boolean { /** * [#33003] The body {@link MetadataManager.register} stores for an environment * row the boot pass stamped with `stamp`: `data` without that stamp, at the top - * and in the two bodies a stored row nests — `metadata` (the publish envelope's - * body, which the store's package read peels to) and `publishedDefinition` - * (the snapshot `revertPackage` restores into `metadata`). The registry keeps - * `data` as it is, stamp included. A copy: `data` is never changed. + * and in the publish envelope's `metadata` body (`revertPackage` restores the + * stamped snapshot there, and the store's package read peels to it). The + * registry keeps `data` as it is, stamp included. A copy: `data` is never + * changed. */ function withoutEnvironmentRowStamp(data: Record, stamp: string): Record { const stored: Record = { ...data }; delete stored._packageId; - for (const key of [STORED_BODY_KEY, 'publishedDefinition'] as const) { - const nested = stored[key]; - if (nested === null || typeof nested !== 'object' || Array.isArray(nested)) continue; - if ((nested as { _packageId?: unknown })._packageId !== stamp) continue; - const body: Record = { ...(nested as Record) }; - delete body._packageId; - stored[key] = body; + const body = stored[STORED_BODY_KEY]; + if (body !== null && typeof body === 'object' && !Array.isArray(body) && (body as { _packageId?: unknown })._packageId === stamp) { + const unstamped: Record = { ...(body as Record) }; + delete unstamped._packageId; + stored[STORED_BODY_KEY] = unstamped; } return stored; } From 54add70e55eebc6b6f01bcc60e85e8eb8d52d32f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:16:23 +0000 Subject: [PATCH 6/9] refactor(metadata): a copy over a stamped environment row carries the mark when it keeps the stamp; pin a copy stamped with another package Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz4sWiJgVrx7vhMJSf --- .../src/loaders/database-loader.test.ts | 8 ++++ packages/metadata/src/metadata-manager.ts | 40 +++++++++---------- 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index 7fa174deb92..b6bead2e858 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -3219,6 +3219,14 @@ describe('[#33003] a write that rewrites an environment row the boot pass stampe expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); }); + it('CONTROL a copy stamped with another package is that package\'s item: unregisterPackage of that package removes it', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await m.register('object', 'env_account', { name: 'env_account', label: 'env', _packageId: EXT }, { notify: false }); + await m.unregisterPackage(EXT); + expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); + }); + it('CONTROL unregisterPackage of the extender leaves the environment\'s object the bridge rewrote, and of another package nothing moves', async () => { for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); const m = await bootPass(); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index 78dbd8b9dd9..10289254339 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -186,15 +186,6 @@ function isPackageMember(item: unknown, packageId: string): boolean { return meta?.packageId === packageId || meta?.package === packageId || meta?._packageId === packageId; } -/** - * [#32986, #33003] Whether `item` names `packageId` by the `_packageId` stamp - * alone: neither its own `packageId` nor the legacy `package` key names it. - */ -function namesPackageByStampAlone(item: object, packageId: string): boolean { - const meta = item as { packageId?: unknown; package?: unknown; _packageId?: unknown }; - return meta._packageId === packageId && meta.packageId !== packageId && meta.package !== packageId; -} - /** * [#33003] The body {@link MetadataManager.register} stores for an environment * row the boot pass stamped with `stamp`: `data` without that stamp, at the top @@ -691,7 +682,9 @@ export class MetadataManager implements IMetadataService { * the host's declared package (`_packageId`), and the stamp stays — ObjectQL * registers such an `object` as the host package's contribution — but the * row is not the package's item, so {@link unregisterPackage} leaves it - * ({@link isStampedEnvironmentRow}). + * ({@link isStampedEnvironmentRow}). [#33003] A copy that replaces one + * joins the set ({@link rewritesEnvironmentRow}), and {@link register} + * stores a member without the stamp. */ private readonly storedEnvironmentRows = new WeakSet(); /** @@ -1352,7 +1345,7 @@ export class MetadataManager implements IMetadataService { this.storedRowsOverOwnItems.add(data); } } - // [#33003] A copy of an environment row the boot pass stamped, still stamped alone, is that row. + // [#33003] A copy of an environment row the boot pass stamped, still carrying the stamp, is that row. if (this.rewritesEnvironmentRow(typeStore.get(key), data)) this.storedEnvironmentRows.add(data as object); for (const replaced of replaces) typeStore.delete(replaced); typeStore.set(key, data); @@ -2771,7 +2764,8 @@ export class MetadataManager implements IMetadataService { */ private isStampedEnvironmentRow(data: unknown, packageId: string): boolean { if (data === null || typeof data !== 'object' || !this.storedEnvironmentRows.has(data)) return false; - return namesPackageByStampAlone(data, packageId); + const meta = data as { packageId?: unknown; package?: unknown; _packageId?: unknown }; + return meta._packageId === packageId && meta.packageId !== packageId && meta.package !== packageId; } /** @@ -2787,20 +2781,22 @@ export class MetadataManager implements IMetadataService { /** * [#33003] Whether writing `data` over `before` rewrites an environment row * the boot pass stamped: `before` is such a row ({@link environmentRowStamp}), - * and `data` is a copy no loader handed out that still names that package by - * the stamp alone. Every writer that registers such a copy reaches this — - * ObjectQL's late-manifest bridge (the `ownPreviousCopy` re-register and - * `restoreExtendedObjectCopies`) and its object-copy follow - * (`registerInMemory`), `publishPackage` / `revertPackage` over - * {@link collectPackageMembers}, and `importMetadata`'s merge — so the copy - * keeps the row's mark instead of the mark riding the replaced object. An - * item a loader handed out (a file's, a stored row's) is that loader's - * item, never a copy: a stored row is marked by {@link loadMany} itself. + * and `data` is a copy no loader handed out that still carries that stamp (a + * copy that also names the package by its own key stays the package's item: + * {@link isStampedEnvironmentRow} reads every key at each use). Every writer + * that registers such a copy reaches this — ObjectQL's late-manifest bridge + * (the `ownPreviousCopy` re-register and `restoreExtendedObjectCopies`) and + * its object-copy follow (`registerInMemory`), `publishPackage` / + * `revertPackage` over {@link collectPackageMembers}, and `importMetadata`'s + * merge — so the copy keeps the row's mark instead of the mark riding the + * replaced object. An item a loader handed out (a file's, a stored row's) is + * that loader's item, never a copy: a stored row is marked by + * {@link loadMany} itself. */ private rewritesEnvironmentRow(before: unknown, data: unknown): boolean { if (data === null || typeof data !== 'object' || data === before || this.loadedFrom.has(data)) return false; const stamp = this.environmentRowStamp(before); - return stamp !== undefined && namesPackageByStampAlone(data, stamp); + return stamp !== undefined && (data as { _packageId?: unknown })._packageId === stamp; } /** From 4bfa8c2f3028d5fbc13c25bddc352dda9e6ecc81 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:20:11 +0000 Subject: [PATCH 7/9] test(objectql): the late-manifest bridge and its restore rewrite the environment's object, and unregistering the host keeps it Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz4sWiJgVrx7vhMJSf --- ...3003-environment-row-rewrite-keeps-mark.md | 12 + ...plugin-late-bridge-environment-row.test.ts | 229 ++++++++++++++++++ 2 files changed, 241 insertions(+) create mode 100644 .changeset/33003-environment-row-rewrite-keeps-mark.md create mode 100644 packages/objectql/src/plugin-late-bridge-environment-row.test.ts diff --git a/.changeset/33003-environment-row-rewrite-keeps-mark.md b/.changeset/33003-environment-row-rewrite-keeps-mark.md new file mode 100644 index 00000000000..7dbcae757ee --- /dev/null +++ b/.changeset/33003-environment-row-rewrite-keeps-mark.md @@ -0,0 +1,12 @@ +--- +'@objectstack/metadata': patch +--- + +fix(metadata): a write that rewrites an environment row the boot pass stamped with the host keeps it the environment's, so unregistering the host package keeps it in this process and after a restart + +Clause-②: no — no released answer moves: `@objectstack/metadata@18.3.0`'s `unregisterPackage` never removed an item named only by the `_packageId` stamp, so these rows were kept there too; #32198 (unreleased) is what turned the rewrite into a deletion. The registry entry keeps the stamp, so the ObjectQL owner of such an object does not move. +Metadata-protocol: none + +On a host that declares its package and stores metadata in a database, the boot pass stamps each stored row that names no package with the host's package, and `unregisterPackage(host)` leaves such a row (#32986). That held only until something rewrote the row: a write that registered a copy still stamped with the host dropped the mark and stored the stamp in the row's body, so the row then read as the host's own, in that process and after a restart, and `unregisterPackage(host)` deleted it. The writers that do this: ObjectQL's late-manifest bridge when another package extends the environment's object (and its restore when that package is withdrawn), ObjectQL's object-copy follow, `publishPackage` and `revertPackage` of the host, and `importMetadata` with `conflictResolution: 'merge'`. + +Now a copy that replaces such a row and still carries the host's stamp keeps the row's mark, and the row is stored without the host stamp (at the top and in the publish envelope's `metadata` body), so the next boot reads it as the environment's own again. The host's own rows, a copy that names the host by its own `packageId` or `package` key, a copy stamped with another package, and a stored row another writer re-saved naming the host are removed as before. A `draft` row is treated like an `active` one. Types stored per `(package, name)` are unchanged here. diff --git a/packages/objectql/src/plugin-late-bridge-environment-row.test.ts b/packages/objectql/src/plugin-late-bridge-environment-row.test.ts new file mode 100644 index 00000000000..6113ffb518d --- /dev/null +++ b/packages/objectql/src/plugin-late-bridge-environment-row.test.ts @@ -0,0 +1,229 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33003] The late-manifest bridge rewrites an environment row the boot pass + * stamped with the host, and the row stays the environment's. + * + * ## The defect + * + * On a host that declares its package and stores metadata in a database, the + * metadata boot pass stamps each stored row naming no package with the host + * (`_packageId`), and ObjectQL owns such an object as the host's. When another + * package extends it, {@link ObjectQLPlugin}'s late-manifest bridge sees the + * metadata service's copy stamped with the owner and re-registers the merged + * object (`ownPreviousCopy`); withdrawing the extender puts the owner's body + * back the same way (`restoreExtendedObjectCopies`). Each write replaced the + * object the boot pass had marked as the environment's own row and stored the + * host stamp in the row's body, so `unregisterPackage(host)` deleted the + * environment's object, in that process and after a restart. + * + * ## Why these parts are real + * + * The bridge and its restore are this plugin's own methods, run over a real + * `ObjectQL` registry (the extender's merge, the owner's stamp) into a real + * `MetadataManager` whose rows a real `DatabaseLoader` reads and writes, primed + * by `MetadataPlugin`'s real boot pass; a second pass over the same store is + * the restart. The metadata-level pins of every writer live in + * `packages/metadata/src/loaders/database-loader.test.ts` (`[#33003]`). + */ + +import { describe, expect, it, vi } from 'vitest'; +import { randomUUID } from 'node:crypto'; +import { DatabaseLoader, MetadataPlugin, type MetadataManager } from '@objectstack/metadata'; +import { ObjectQL } from './engine.js'; +import { ObjectQLPlugin } from './plugin.js'; + +type Stores = Map>>; + +/** In-memory driver, copied from `protocol-delete-boot-hydrated-object-heal.test.ts`; equality-only WHERE. */ +function makeMemoryDriver(stores: Stores) { + const storeFor = (obj: string) => { + let s = stores.get(obj); + if (!s) { s = new Map(); stores.set(obj, s); } + return s; + }; + const matchesWhere = (row: Record, where: any): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where)) { + if (k === '$and' && Array.isArray(v)) { + if (!v.every((w: any) => matchesWhere(row, w))) return false; + continue; + } + if (k === '$or' && Array.isArray(v)) { + if (!v.some((w: any) => matchesWhere(row, w))) return false; + continue; + } + if (k.startsWith('$')) continue; + const rowVal = row[k]; + const expected = (v && typeof v === 'object' && '$eq' in (v as any)) ? (v as any).$eq : v; + const a = rowVal === undefined ? null : rowVal; + const b = expected === undefined ? null : expected; + if (a !== b) return false; + } + return true; + }; + const driver: any = { + name: 'memory', version: '0.0.0', supports: {} as any, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, + async syncSchema() {}, + async execute() { return null; }, + async find(object: string, ast: any) { + const rows = Array.from(storeFor(object).values()).filter((r) => matchesWhere(r, ast?.where)); + // The caller's bound, after the filter, by presence (`check:objectql-double-limit`). + return typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + }, + async findOne(object: string, ast: any) { + for (const r of storeFor(object).values()) if (matchesWhere(r, ast?.where)) return r; + return null; + }, + async create(object: string, data: Record) { + const id = (data.id as string) ?? `r_${randomUUID()}`; + const row = { ...data, id }; + storeFor(object).set(id, row); + return row; + }, + async update(object: string, id: string, data: Record) { + const s = storeFor(object); + const cur = s.get(id); + if (!cur) throw new Error(`not found: ${object}/${id}`); + const updated = { ...cur, ...data, id }; + s.set(id, updated); + return updated; + }, + async upsert(object: string, data: Record) { + const id = data.id as string | undefined; + if (id && storeFor(object).has(id)) return this.update(object, id, data); + return this.create(object, data); + }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count(object: string, ast: any) { return (await this.find(object, ast)).length; }, + async bulkCreate(object: string, rows: Record[]) { + return Promise.all(rows.map((r) => this.create(object, r))); + }, + async bulkUpdate() { return []; }, async bulkDelete() {}, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, async rollback() {}, + async dropTable(object: string) { stores.delete(object); }, + }; + return driver; +} + +const HOST = 'com.host.app'; +const EXT = 'com.ext.score'; +const OBJECT = 'env_account'; + +/** An extender whose only content is a field on the environment's object. */ +const extender = () => ({ + id: EXT, + name: EXT, + version: '1.0.0', + type: 'app', + objectExtensions: [{ extend: OBJECT, fields: { ext_score: { name: 'ext_score', label: 'Score', type: 'number' } } }], +}); + +const logger = () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }); + +/** The metadata boot pass over the store, on a host that declares `HOST`. */ +async function bootPass(stores: Stores): Promise { + const plugin = new MetadataPlugin({ packageId: HOST, watch: false, config: { bootstrap: 'eager' } }); + const m = (plugin as any).manager as MetadataManager; + (m as any).loaders.clear(); + m.registerLoader(new DatabaseLoader({ driver: makeMemoryDriver(stores) })); + await (plugin as any)._loadFromFileSystem({ logger: logger() }); + return m; +} + +/** A stored row naming no package, as the environment saved it; `body` may name the host (CONTROL). */ +function seed(stores: Stores, name: string, body: Record = {}) { + const table = new Map>(stores.get('sys_metadata') ?? []); + table.set(`object_${name}`, { + id: `object_${name}`, type: 'object', name, state: 'active', version: 1, checksum: name, source: 'database', + package_id: null, metadata: JSON.stringify({ name, label: 'env', fields: { name: { name: 'name', type: 'text', label: 'Name' } }, ...body }), + }); + stores.set('sys_metadata', table); +} + +/** + * The ObjectQL side: the registry owns each object as the metadata copy's + * stamp names it (ObjectQL registers a copy under `_packageId`), the extender + * is installed, and the bridge and its restore are the plugin's own. + */ +function objectql(m: MetadataManager, names: readonly string[]) { + const engine = new ObjectQL(); + for (const name of names) { + const copy = (m as any).registry.get('object').get(name) as Record; + const { _packageId, ...schema } = copy; + engine.registry.registerObject(schema as any, _packageId as string); + } + engine.registerApp(extender()); + const plugin = new ObjectQLPlugin({ ql: engine }); + (plugin as any).bridgeLateManifests = true; + const ctx = { logger: logger(), getService: (name: string) => { if (name === 'metadata') return m; throw new Error(name); } }; + return { + engine, + bridge: () => (plugin as any).bridgeManifestObjectsToMetadataService(ctx, extender()) as Promise, + restore: async () => { + engine.registry.uninstallPackage(EXT); + await (plugin as any).restoreExtendedObjectCopies(ctx, EXT); + }, + }; +} + +/** Per object: the registry's stamp, its served field names, and how many stored rows it has. */ +async function state(m: MetadataManager, stores: Stores, names: readonly string[]) { + const out: unknown[] = []; + for (const name of names) { + const held = (m as any).registry.get('object')?.get(name) as { _packageId?: string; fields?: object } | undefined; + const rows = [...(stores.get('sys_metadata')?.values() ?? [])].filter((r) => r.type === 'object' && r.name === name); + out.push([name, held?._packageId ?? null, held ? Object.keys(held.fields ?? {}).includes('ext_score') : null, rows.length]); + } + return out; +} + +describe('[#33003] the late-manifest bridge rewrites the environment\'s object the boot pass stamped with the host: unregisterPackage(host) keeps it', () => { + it('the extender bridged (ownPreviousCopy): unregisterPackage(host) keeps the object in this process and after a restart (BEFORE: deleted)', async () => { + const stores: Stores = new Map(); + seed(stores, OBJECT); + const m = await bootPass(stores); + const { bridge } = objectql(m, [OBJECT]); + await bridge(); + // Identity: the bridge rewrote the copy with the merged body, stamped with the owner. + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, HOST, true, 1]]); + + const rebooted = await bootPass(stores); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted, stores, [OBJECT])).toEqual([[OBJECT, HOST, true, 1]]); + await m.unregisterPackage(HOST); + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, HOST, true, 1]]); + }); + + it('the extender withdrawn (restoreExtendedObjectCopies): unregisterPackage(host) keeps the restored object in this process and after a restart (BEFORE: deleted)', async () => { + const stores: Stores = new Map(); + seed(stores, OBJECT); + const m = await bootPass(stores); + const { bridge, restore } = objectql(m, [OBJECT]); + await bridge(); + await restore(); + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, HOST, false, 1]]); + + const rebooted = await bootPass(stores); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted, stores, [OBJECT])).toEqual([[OBJECT, HOST, false, 1]]); + await m.unregisterPackage(HOST); + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, HOST, false, 1]]); + }); + + it('CONTROL the host\'s own object (its stored body carries the host\'s stamp), bridged and restored the same way, is still removed', async () => { + const stores: Stores = new Map(); + seed(stores, OBJECT, { _packageId: HOST }); + const m = await bootPass(stores); + const { bridge, restore } = objectql(m, [OBJECT]); + await bridge(); + await restore(); + const rebooted = await bootPass(stores); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted, stores, [OBJECT])).toEqual([[OBJECT, null, null, 0]]); + await m.unregisterPackage(HOST); + expect(await state(m, stores, [OBJECT])).toEqual([[OBJECT, null, null, 0]]); + }); +}); From 82642b50ea61b1fa3130a31b51067587d188ac1f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:55:51 +0000 Subject: [PATCH 8/9] fix(metadata): a rollback over an environment row stores it without the host stamp, and an unstamped replacement keeps the row's mark and host Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz4sWiJgVrx7vhMJSf --- .../src/loaders/database-loader.test.ts | 50 ++++++++++++++ packages/metadata/src/metadata-manager.ts | 66 ++++++++++++------- 2 files changed, 94 insertions(+), 22 deletions(-) diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index b6bead2e858..d12b0b43b77 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -3227,6 +3227,56 @@ describe('[#33003] a write that rewrites an environment row the boot pass stampe expect(await state(m)).toEqual(ITEMS.map(([type, name]) => name === 'env_account' ? [type, name, null, false, 0] : [type, name, HOST, true, 1])); }); + /** + * [#33003, review S3] An unstamped replacement (an import without `merge`, + * a `bulkRegister`) keeps the row's mark and its host, so the copy ObjectQL's + * object-copy follow then writes, stamped with the registry owner (still the + * host), is the row too. + */ + for (const [writer, replace] of [ + ['importMetadata overwrite', (m: MetadataManager) => m.importMetadata({ object: [{ name: 'env_account', label: 'replaced' }] }, { conflictResolution: 'overwrite' })], + ['bulkRegister', (m: MetadataManager) => m.bulkRegister([{ type: 'object', name: 'env_account', data: { name: 'env_account', label: 'replaced' } }])], + ] as const) { + it(`an unstamped replacement (${writer}), then the object-copy follow stamped with the host: unregisterPackage(host) keeps the row (BEFORE: deleted)`, async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + await replace(m); + m.registerInMemory('object', 'env_account', { name: 'env_account', label: 'served', _packageId: HOST }); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(kept()); + }); + } + + /** + * [#33003, review S2] `rollback` persists through the loader's own rollback + * path, not `register`. A version a rewrite stored before #33003 carries the + * host stamp; restored over the environment's row, it is that row. + */ + it('rollback to a version stored with the host stamp: unregisterPackage(host) keeps the row in this process and after a reboot (BEFORE: deleted after the reboot)', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); + const m = await bootPass(); + // A version a rewrite stored before #33003: the body carries the host stamp. + await (m as any).getDatabaseLoader().save('object', 'env_account', { name: 'env_account', label: 'stamped', _packageId: HOST }); + await m.register('object', 'env_account', { name: 'env_account', label: 'later' }); + await m.rollback('object', 'env_account', 2); + const rebooted = await bootPass(); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted)).toEqual(kept()); + await m.unregisterPackage(HOST); + expect(await state(m)).toEqual(kept()); + }); + + it('CONTROL rollback of the host\'s own row to a stamped version: removed after a reboot', async () => { + for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, { _packageId: HOST }); + const m = await bootPass(); + await (m as any).getDatabaseLoader().save('object', 'env_account', { name: 'env_account', label: 'stamped', _packageId: HOST }); + await m.register('object', 'env_account', { name: 'env_account', label: 'later', _packageId: HOST }); + await m.rollback('object', 'env_account', 2); + const rebooted = await bootPass(); + await rebooted.unregisterPackage(HOST); + expect(await state(rebooted)).toEqual(gone()); + }); + it('CONTROL unregisterPackage of the extender leaves the environment\'s object the bridge rewrote, and of another package nothing moves', async () => { for (const [type, name, rowState] of ITEMS) await seed(type, name, rowState, {}); const m = await bootPass(); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index 10289254339..7e2109f1696 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -683,10 +683,16 @@ export class MetadataManager implements IMetadataService { * registers such an `object` as the host package's contribution — but the * row is not the package's item, so {@link unregisterPackage} leaves it * ({@link isStampedEnvironmentRow}). [#33003] A copy that replaces one - * joins the set ({@link rewritesEnvironmentRow}), and {@link register} + * joins the set ({@link carryEnvironmentRowMark}), and {@link register} * stores a member without the stamp. */ private readonly storedEnvironmentRows = new WeakSet(); + /** + * [#33003] The host stamp each {@link storedEnvironmentRows} member carried + * on, so an unstamped replacement passes it on to the copy after it + * ({@link carryEnvironmentRowMark}). + */ + private readonly environmentRowHosts = new WeakMap(); /** * [ADR-0150 D4, #32791] The {@link storedPackagelessRows} whose registration * replaced an item no loader handed out (one registered in memory or by @@ -1345,8 +1351,8 @@ export class MetadataManager implements IMetadataService { this.storedRowsOverOwnItems.add(data); } } - // [#33003] A copy of an environment row the boot pass stamped, still carrying the stamp, is that row. - if (this.rewritesEnvironmentRow(typeStore.get(key), data)) this.storedEnvironmentRows.add(data as object); + // [#33003] A copy of an environment row the boot pass stamped, carrying its stamp or none, is that row. + this.carryEnvironmentRowMark(typeStore.get(key), data); for (const replaced of replaces) typeStore.delete(replaced); typeStore.set(key, data); recordStoreWrite(typeStore, key); @@ -2779,24 +2785,35 @@ export class MetadataManager implements IMetadataService { } /** - * [#33003] Whether writing `data` over `before` rewrites an environment row - * the boot pass stamped: `before` is such a row ({@link environmentRowStamp}), - * and `data` is a copy no loader handed out that still carries that stamp (a - * copy that also names the package by its own key stays the package's item: - * {@link isStampedEnvironmentRow} reads every key at each use). Every writer - * that registers such a copy reaches this — ObjectQL's late-manifest bridge - * (the `ownPreviousCopy` re-register and `restoreExtendedObjectCopies`) and - * its object-copy follow (`registerInMemory`), `publishPackage` / - * `revertPackage` over {@link collectPackageMembers}, and `importMetadata`'s - * merge — so the copy keeps the row's mark instead of the mark riding the - * replaced object. An item a loader handed out (a file's, a stored row's) is - * that loader's item, never a copy: a stored row is marked by - * {@link loadMany} itself. + * [#33003] Writing `data` over `before`, where `before` is one of the + * {@link storedEnvironmentRows}: `data` is that row rewritten, and keeps its + * mark, when no loader handed it out and it carries the row's host stamp or + * none. A copy that also names the package by its own key stays the + * package's item ({@link isStampedEnvironmentRow} reads every key at each + * use); a copy stamped with another package is that package's. The host + * stamp is remembered ({@link environmentRowHosts}), so a copy stamped with + * the host after an unstamped replacement (an `importMetadata` without + * `merge`, a `bulkRegister`, a `rollback` to an authored version, then + * ObjectQL's object-copy follow) is still the row. + * + * Every writer that registers such a copy reaches this — ObjectQL's + * late-manifest bridge (the `ownPreviousCopy` re-register and + * `restoreExtendedObjectCopies`) and its object-copy follow + * (`registerInMemory`), `publishPackage` / `revertPackage` over + * {@link collectPackageMembers}, `importMetadata`, `bulkRegister` and + * {@link rollback} — so the copy keeps the row's mark instead of the mark + * riding the replaced object. An item a loader handed out (a file's, a + * stored row's) is that loader's item, never a copy: a stored row is marked + * by {@link loadMany} itself. */ - private rewritesEnvironmentRow(before: unknown, data: unknown): boolean { - if (data === null || typeof data !== 'object' || data === before || this.loadedFrom.has(data)) return false; - const stamp = this.environmentRowStamp(before); - return stamp !== undefined && (data as { _packageId?: unknown })._packageId === stamp; + private carryEnvironmentRowMark(before: unknown, data: unknown): void { + if (data === null || typeof data !== 'object' || data === before || this.loadedFrom.has(data)) return; + if (before === null || typeof before !== 'object' || !this.storedEnvironmentRows.has(before)) return; + const host = this.environmentRowHosts.get(before) ?? this.environmentRowStamp(before); + const stamp = (data as { _packageId?: unknown })._packageId; + if (stamp !== undefined && stamp !== host) return; + this.storedEnvironmentRows.add(data); + if (host !== undefined) this.environmentRowHosts.set(data, host); } /** @@ -4667,10 +4684,16 @@ export class MetadataManager implements IMetadataService { // Restore the metadata using the dedicated rollback path so that a single // 'revert' history entry is written (instead of a conflicting 'update' entry) const restoredMetadata = targetVersion.metadata; + // [#33003] A version restored over an environment row the boot pass + // stamped is that row (a version a rewrite stored before #33003 carries the + // host stamp): stored without the stamp, as {@link register} stores it. + const slotted = PACKAGE_SLOTTED_STORE_TYPES.has(type); + if (!slotted) this.carryEnvironmentRowMark(this.registry.get(type)?.get(name), restoredMetadata); + const stamp = this.environmentRowStamp(restoredMetadata); await dbLoader.registerRollback( type, name, - restoredMetadata, + stamp === undefined ? restoredMetadata : withoutEnvironmentRowStamp(restoredMetadata as Record, stamp), version, options?.changeNote, options?.recordedBy, @@ -4683,7 +4706,6 @@ export class MetadataManager implements IMetadataService { // as the row it was written to is. [S4] One restored by the environment // address is filed under the bare slot, as its row is, even when one // package holds the name (the write rule would file it under that package's). - const slotted = PACKAGE_SLOTTED_STORE_TYPES.has(type); if (slotted && isPackageCaller(address?.packageId)) { this.writeRegistryEntry(type, name, withEntryPackage({ name, data: restoredMetadata, packageId: address.packageId })); } else if (slotted && address !== undefined) { From 012671ee2799b8288fd7b51df4b2152b526e0c58 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 05:57:28 +0000 Subject: [PATCH 9/9] docs(changeset): name the rollback writer, the unstamped-replacement carry, and the rows already stored stamped Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_016WV4cz4sWiJgVrx7vhMJSf --- .changeset/33003-environment-row-rewrite-keeps-mark.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.changeset/33003-environment-row-rewrite-keeps-mark.md b/.changeset/33003-environment-row-rewrite-keeps-mark.md index 7dbcae757ee..4d7da86e2b9 100644 --- a/.changeset/33003-environment-row-rewrite-keeps-mark.md +++ b/.changeset/33003-environment-row-rewrite-keeps-mark.md @@ -7,6 +7,8 @@ fix(metadata): a write that rewrites an environment row the boot pass stamped wi Clause-②: no — no released answer moves: `@objectstack/metadata@18.3.0`'s `unregisterPackage` never removed an item named only by the `_packageId` stamp, so these rows were kept there too; #32198 (unreleased) is what turned the rewrite into a deletion. The registry entry keeps the stamp, so the ObjectQL owner of such an object does not move. Metadata-protocol: none -On a host that declares its package and stores metadata in a database, the boot pass stamps each stored row that names no package with the host's package, and `unregisterPackage(host)` leaves such a row (#32986). That held only until something rewrote the row: a write that registered a copy still stamped with the host dropped the mark and stored the stamp in the row's body, so the row then read as the host's own, in that process and after a restart, and `unregisterPackage(host)` deleted it. The writers that do this: ObjectQL's late-manifest bridge when another package extends the environment's object (and its restore when that package is withdrawn), ObjectQL's object-copy follow, `publishPackage` and `revertPackage` of the host, and `importMetadata` with `conflictResolution: 'merge'`. +On a host that declares its package and stores metadata in a database, the boot pass stamps each stored row that names no package with the host's package, and `unregisterPackage(host)` leaves such a row (#32986). That held only until something rewrote the row: a write that registered a copy still stamped with the host dropped the mark and stored the stamp in the row's body, so the row then read as the host's own, in that process and after a restart, and `unregisterPackage(host)` deleted it. The writers that do this: ObjectQL's late-manifest bridge when another package extends the environment's object (and its restore when that package is withdrawn), ObjectQL's object-copy follow, `publishPackage` and `revertPackage` of the host, `importMetadata` with `conflictResolution: 'merge'`, and `rollback` to a version stored with the host stamp. -Now a copy that replaces such a row and still carries the host's stamp keeps the row's mark, and the row is stored without the host stamp (at the top and in the publish envelope's `metadata` body), so the next boot reads it as the environment's own again. The host's own rows, a copy that names the host by its own `packageId` or `package` key, a copy stamped with another package, and a stored row another writer re-saved naming the host are removed as before. A `draft` row is treated like an `active` one. Types stored per `(package, name)` are unchanged here. +Now a copy that replaces such a row and carries the host's stamp, or no stamp, keeps the row's mark (so a copy stamped with the host after an unstamped replacement is still the row), and the row is stored without the host stamp (at the top and in the publish envelope's `metadata` body, on `register` and on `rollback`), so the next boot reads it as the environment's own again. The host's own rows, a copy that names the host by its own `packageId` or `package` key, a copy stamped with another package, and a stored row another writer re-saved naming the host are removed as before. A `draft` row is treated like an `active` one. Types stored per `(package, name)` are unchanged here. + +A row whose stored body already carries the host stamp (one a boot pass of 18.3.0 or earlier stored, or a write stored before this change) reads as the host's own row and is still removed with it: no boot rule can tell it from a row the host seeded. Its upgrade path is #33043.