diff --git a/.changeset/37604-platform-record-followups.md b/.changeset/37604-platform-record-followups.md new file mode 100644 index 00000000000..6a3f2f49417 --- /dev/null +++ b/.changeset/37604-platform-record-followups.md @@ -0,0 +1,25 @@ +--- +'@objectstack/metadata': patch +'@objectstack/metadata-protocol': patch +--- + +fix(metadata)!: a version the platform registered is never restored into a package's row, and adopting orphans leaves the platform's own record where the platform keeps it + +Clause-②: yes (narrowing) +Metadata-protocol: none +Skills-docs: none — no `skills/` page teaches restoring a platform-registered version, adopting orphans over the platform's record, or `listPackageBindings` + + + +**BREAKING**, in two places, each a write that happened before and is now refused or left out: + +- **A version the platform registered is never restored into a package's row**, at all three restore doors: the metadata service's `rollback`, and the metadata protocol's `rollbackMetaItem` and the restore limb of `revertCommit`. Refused with `409 RESOURCE_CONFLICT`, naming the fix, nothing written (`revertCommit` reports the item in `failed[]` and still reverts the commit's other items). Before, once the platform had withdrawn its record of a name, the name's one remaining holder was a package, a version attributed to the environment counted as that package's, and a rollback (naming the package or bare) wrote the platform's body into the package's row; `revertCommit` of a package's commit did the same wherever the commit's version was one the platform registered. + What to do: to make that body the package's item, save it again naming the package. +- **`POST /api/v1/packages/:id/adopt-orphans` (`reassignOrphanedMetadata`) leaves the platform's own record**, the package-less row whose body carries the platform's mark: it is the record the platform registers at every boot, not an orphan. Before, the adoption rebound it to the target package, mark and all. Every other orphan is adopted as before. + What to do: nothing. + +Also in `@objectstack/metadata`: + +- `isPlatformRecordRow(row)` is exported: the one reader of whether a stored row is the platform's own record (its package column names no package, its body carries the platform's mark and names none), asked by `refusePlatformRecordRestore`, the metadata protocol's overlay census and its adoption of orphans, so they cannot disagree. `refusePlatformRecordRestore` now reads a row bound to a package by its column as that package's, whatever its body keeps, and takes an optional fourth argument, the version a restore would write and the package whose row it writes. +- The refusal of a restore whose row is the platform's own record now says that re-saving a version's body as the environment's own item holds until the platform's next registration at boot writes its record back. +- `listPackageBindings` names a loader that the read lost once in `errors`, and does not read that loader's rows a second time. diff --git a/packages/metadata-protocol/src/protocol-diff-delete-load.ts b/packages/metadata-protocol/src/protocol-diff-delete-load.ts index 1c2294d6482..004202b71c3 100644 --- a/packages/metadata-protocol/src/protocol-diff-delete-load.ts +++ b/packages/metadata-protocol/src/protocol-diff-delete-load.ts @@ -67,7 +67,7 @@ import { captureStoredExpressionChange, fillStoredExpressionChange } from './pro import type { RuntimeAuthoringIssue } from './runtime-authoring-gate.js'; import type { ProtocolHost } from './protocol-host.js'; import { packagelessHolderRefusal, packagelessRowHeldBaseAddress } from './protocol-save.js'; -import { isPlatformOrigin } from '@objectstack/metadata'; +import { isPlatformRecordRow } from '@objectstack/metadata'; /** * [#33308] The row slot a `sys_metadata` row is: its bound package, or `null` @@ -1857,22 +1857,3 @@ export class ProtocolDiffDeleteLoadFacet { return { references: out }; } } - -/** - * [#37013] Whether a stored `sys_metadata` row is the platform's own record: - * bound to no package by its column, and its body carries the platform's mark - * where the metadata service reads it (`isPlatformOrigin`, - * `@objectstack/metadata`). A body that does not parse is not. - */ -function isPlatformRecordRow(record: { package_id?: unknown; metadata?: unknown }): boolean { - if (typeof record.package_id === 'string' && record.package_id !== '') return false; - let body: unknown = record.metadata; - if (typeof body === 'string') { - try { - body = JSON.parse(body); - } catch { - return false; - } - } - return isPlatformOrigin(body); -} diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 2fc997ab52c..cbe3e23f1be 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -34,6 +34,7 @@ import { packageScopedRowWhere } from './sys-metadata-repository.js'; import { overlayMemberWhere } from './migrations/overlay-index.js'; import type { SysMetadataRepository } from './sys-metadata-repository.js'; import { ConflictError, assertProtocolCompat } from '@objectstack/metadata-core'; +import { isPlatformRecordRow } from '@objectstack/metadata'; import { planUnmanagedImport, UNMANAGED_SEED_TYPE, @@ -897,7 +898,13 @@ export class ProtocolPackageCommitsFacet { (r) => (r?.package_id == null || r.package_id === '' || r.package_id === 'sys_metadata') // [#23198] An overlay of an artifact item keeps its binding // (ADR-0070); see the header. The type folds as the save's does. - && !host.isArtifactBacked(PLURAL_TO_SINGULAR[r.type] ?? r.type, String(r.name)), + && !host.isArtifactBacked(PLURAL_TO_SINGULAR[r.type] ?? r.type, String(r.name)) + // [#37604] …nor the platform's own record: the package-less row + // the platform registers at every boot is no orphan an author + // left behind, and rebound it would become the target's item, + // mark and all (`isPlatformRecordRow`, `@objectstack/metadata`, + // the one reader the restore refusal and the overlay census ask). + && !isPlatformRecordRow(r), ); // [ADR-0029 D9.9, ADR-0086 D3, #28776] ⭐ THE OWNER JUDGES, in the save diff --git a/packages/metadata-protocol/src/protocol.adopt-orphans-platform-record.test.ts b/packages/metadata-protocol/src/protocol.adopt-orphans-platform-record.test.ts new file mode 100644 index 00000000000..5d76871bfc9 --- /dev/null +++ b/packages/metadata-protocol/src/protocol.adopt-orphans-platform-record.test.ts @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#37604 item 2] `reassignOrphanedMetadata` (`POST /api/v1/packages/:id/adopt-orphans`) + * never rebinds the platform's own record: a package-less row whose body + * carries the platform's mark is the record the platform registers at every + * boot, not an orphan an author left behind. The one reader of that fact is + * `isPlatformRecordRow` (`@objectstack/metadata`), the reader the restore + * refusal and the overlay census ask. + * + * BASE (main 4e10d4bf): the adoption rebound that row to the target package, + * so the platform's record became the package's item, mark and all. + */ + +import { describe, expect, it } from 'vitest'; +import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from './protocol.js'; +// Pay the source's dynamic `@objectstack/lint` load during collection, never inside a case. +import '@objectstack/lint'; + +type Row = { id: string; type: string; name: string; state: string; package_id: string | null; metadata: string }; + +/** `sys_metadata` alone, the empty filter the adoption reads with, the producer's own update dispatch. */ +function makeEngine(rows: Row[]) { + const store = new Map(rows.map((r) => [r.id, { ...r }])); + const engine = { + async find(table: string, opts?: { where?: Record; limit?: number }) { + if (table !== 'sys_metadata') return []; + if (opts?.limit !== undefined || Object.keys(opts?.where ?? {}).length !== 0) { + throw new Error(`fake engine: unsupported read ${JSON.stringify(opts)}`); + } + return [...store.values()]; + }, + async update(_table: string, data: Record, opts: { where: Record }) { + assertEngineUpdateDispatch(data, opts); + const row = store.get(String(opts.where.id)); + if (!row) return { id: null }; + Object.assign(row, data); + return { id: row.id }; + }, + }; + return { engine, store }; +} + +const skillRow = (id: string, name: string, body: Record, packageId: string | null = null): Row => ({ + id, type: 'skill', name, state: 'active', package_id: packageId, + metadata: JSON.stringify({ name, label: name, instructions: 'help', ...body }), +}); + +describe('[#37604] adopt-orphans leaves the platform\'s own record where the platform keeps it', () => { + it('the platform\'s package-less row is not rebound; the environment\'s own orphan beside it is (BASE: both rebound)', async () => { + const { engine, store } = makeEngine([ + skillRow('platform', 'helper', { _provenance: 'platform' }), + skillRow('orphan', 'notes', {}), + ]); + const protocol = new ObjectStackProtocolImplementation(engine as never); + + const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); + + expect(store.get('platform')!.package_id).toBeNull(); + expect(store.get('orphan')!.package_id).toBe('app.base'); + expect(res.reassigned).toEqual([{ type: 'skill', name: 'notes' }]); + expect(res.reassignedCount).toBe(1); + }); + + it('control: a package-less row whose body names a package is no platform record, and is adopted', async () => { + const { engine, store } = makeEngine([ + skillRow('named', 'helper', { _provenance: 'platform', _packageId: 'com.acme.crm' }), + ]); + const protocol = new ObjectStackProtocolImplementation(engine as never); + + const res = await protocol.reassignOrphanedMetadata({ targetPackageId: 'app.base' }); + + expect(store.get('named')!.package_id).toBe('app.base'); + expect(res.reassignedCount).toBe(1); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts b/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts index 08b0e430f04..5d99140bddd 100644 --- a/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts +++ b/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts @@ -222,3 +222,82 @@ describe('[#37130] the protocol\'s restore doors refuse a restore whose row is t expect(((await primed.getPlatformItem('skill', 'helper')) as { label?: string } | undefined)?.label).toBe('platform v2'); }); }); + +/** + * [#37604 item 1] After the platform withdraws its own record of a name (its + * package-less row is gone, its versions stay in history attributed to the + * environment), the name's one remaining holder is a package, and a version + * attributed to the environment is that sole slot's (`isVersionOf`). A + * version the platform registered is still never restored into the + * package's row: `409 RESOURCE_CONFLICT`, nothing written. + * + * BASE (main 4e10d4bf): the rollback wrote the platform's v1 into the + * package's row, so a read naming the package answered the platform's body. + */ +describe('[#37604] a version the platform registered is never restored into a package\'s row', () => { + const PKG = 'com.acme.crm'; + + /** The platform's record (v1, v2), the package's own row (v3), then the platform's withdrawal. */ + async function withdrawnPlatformRecord() { + const harness = makeEngine(); + const protocol = new ObjectStackProtocolImplementation(harness.engine); + await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('platform v1') }); + await protocol.saveMetaItem({ type: 'skill', name: 'helper', item: skill('platform v2') }); + const mark = (row: Row) => { row.metadata = JSON.stringify({ ...JSON.parse(String(row.metadata)), _provenance: 'platform' }); }; + for (const row of harness.historyRows.filter((r) => r.name === 'helper')) mark(row); + // The withdrawal: the platform's package-less row is deleted, its history stays. + harness.rows.splice(harness.rows.findIndex((r) => r.name === 'helper'), 1); + const pkgBody = JSON.stringify({ ...skill('package rules'), _packageId: PKG }); + harness.rows.push({ + id: 'row_pkg', type: 'skill', name: 'helper', state: 'active', organization_id: null, package_id: PKG, + version: 3, checksum: 'pkg', source: 'database', metadata: pkgBody, + }); + harness.historyRows.push({ + id: 'hist_pkg', type: 'skill', name: 'helper', version: 3, organization_id: null, package_id: PKG, + operation_type: 'update', checksum: 'pkg', metadata: pkgBody, + }); + return { ...harness, protocol }; + } + + for (const [door, request] of [ + ['naming the package', { packageId: PKG }], + ['naming no package (the name\'s one holder)', {}], + ] as const) { + it(`rollbackMetaItem ${door}: refused 409 RESOURCE_CONFLICT, the package's row byte-identical (BASE: the platform's v1 written into it)`, async () => { + const { protocol, rows } = await withdrawnPlatformRecord(); + const before = JSON.stringify(rows); + + const refused = await protocol.rollbackMetaItem({ type: 'skill', name: 'helper', toVersion: 1, ...request }).catch((error) => error); + + expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); + expect(String(refused.message)).toContain('the platform registered'); + expect(JSON.stringify(rows)).toBe(before); + }); + } + + // [#37604 N2] The commit names its package, as `recordPackageCommit` always writes it: the restore limb + // reads that package's row, so the scenario is reachable through `revertCommit` too. + it('revertCommit of a commit that names its package: the platform\'s version lands in failed[] 409-coded, the package\'s row byte-identical (BASE: written into it)', async () => { + const { protocol, rows, serveCommit } = await withdrawnPlatformRecord(); + const before = JSON.stringify(rows); + serveCommit({ + id: 'c1', commit_id: 'c1', organization_id: null, package_id: PKG, operation: 'apply', message: 'the package\'s commit under revert', created_at: '2026-01-01T00:00:00Z', + items: JSON.stringify([{ type: 'skill', name: 'helper', existedBefore: true, prevVersion: 1 }]), + }); + + const res = await protocol.revertCommit({ commitId: 'c1' }); + + expect(res.failed).toHaveLength(1); + expect(res.failed[0]).toMatchObject({ type: 'skill', name: 'helper', code: 'RESOURCE_CONFLICT' }); + expect(res.failed[0]!.error).toContain('the platform registered'); + expect(res.revertedCount).toBe(0); + expect(JSON.stringify(rows)).toBe(before); + }); + + it('control: the package\'s own version is restored into its row', async () => { + const { protocol, rows } = await withdrawnPlatformRecord(); + await protocol.rollbackMetaItem({ type: 'skill', name: 'helper', toVersion: 3, packageId: PKG }); + const stored = JSON.parse(String(rows.find((r) => r.package_id === PKG)!.metadata)); + expect(stored.label).toBe('package rules'); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index f6903727c6f..0e0763e31b9 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -10658,6 +10658,14 @@ export class ObjectStackProtocolImplementation implements * real orphan object, and whether an adoption refuses, renames or leaves * the prefix unjudged is the maintainer's question (#28776's ruling). A * draft is judged by both owner judges when it is promoted. + * + * ## [#37604] The platform's own record is no orphan + * + * A package-less row whose body carries the platform's mark is the record + * the platform registers at every boot (`isPlatformRecordRow`, + * `@objectstack/metadata`), kept beside a package's item of the name in a + * slot of its own. It is left as it is stored, as an artifact-backed + * overlay is: rebound, it would become the target's item, mark and all. */ async reassignOrphanedMetadata(request: { targetPackageId: string; diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 5630f38952f..d5e38354920 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -1944,7 +1944,8 @@ export class SysMetadataRepository implements MetadataRepository { * platform's own record (`refusePlatformRecordRestore`, * `@objectstack/metadata`: `409 RESOURCE_CONFLICT`, the metadata * service's `rollback` prescription), read where the write reads it, - * before anything is written. The protocol's two restore doors + * before anything is written. [#37604] So is a version the platform + * registered, restored into a package's row. The protocol's two restore doors * (`rollbackMetaItem`, the restore limb of `revertCommit`) state it. * Omitted → no such check: an undo write puts back what the same * operation found, byte for byte. @@ -2022,8 +2023,16 @@ export class SysMetadataRepository implements MetadataRepository { where: this.whereFor(ref, 'active', 'packageId' in opts ? (opts.packageId ?? null) : undefined, member), context: { isSystem: true }, }); - // [#37130] The row this restore writes, judged before the write. - if (opts.refusePlatformRecord === true) refusePlatformRecordRestore(ref.type, ref.name, activeRow as Record | null); + // [#37130] The row this restore writes, judged before the write. [#37604] + // …and the version it writes: one the platform registered is never + // written into a package's row. + if (opts.refusePlatformRecord === true) { + refusePlatformRecordRestore(ref.type, ref.name, activeRow as Record | null, { + historyRow: row as Record, + version: targetVersion, + intoPackageId: 'packageId' in opts ? (opts.packageId ?? null) : ((activeRow as { package_id?: string | null } | null)?.package_id ?? null), + }); + } const activePackageId = (activeRow as { package_id?: string | null } | null)?.package_id ?? null; const currentActive = activeRow ? this.rowToItem(ref, activeRow) : null; diff --git a/packages/metadata/src/index.ts b/packages/metadata/src/index.ts index ab69741f457..cb316fc456f 100644 --- a/packages/metadata/src/index.ts +++ b/packages/metadata/src/index.ts @@ -29,6 +29,10 @@ export { // [#37130] The platform's record is never restored: the one refusal the // metadata service's rollback and the metadata protocol's restore doors ask. refusePlatformRecordRestore, + // [#37604 N5] …and the one reader of whether a stored row is the platform's + // own record, which that refusal, the protocol's overlay census and its + // adoption of orphans ask. + isPlatformRecordRow, type DatabaseLoaderOptions, type MetadataHistoryAddress, } from './loaders/database-loader.js'; diff --git a/packages/metadata/src/loaders/database-loader.test.ts b/packages/metadata/src/loaders/database-loader.test.ts index 975076a0a5d..afea903e606 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -1,7 +1,7 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { DatabaseLoader } from './database-loader.js'; +import { DatabaseLoader, ENVIRONMENT_HISTORY_MARK, isPlatformRecordRow, refusePlatformRecordRestore } from './database-loader.js'; import type { MetadataLoader } from './loader-interface.js'; import type { IDataDriver } from '@objectstack/spec/contracts'; import { MetadataManager } from '../metadata-manager.js'; @@ -4269,6 +4269,26 @@ describe('[#37013] a platform-registered skill and a package\'s same-named skill expect(JSON.stringify(await rowOf(PKG))).toBe(before); }); + // [#37604 item 1] After the withdrawal the package is the name's one holder, so a version attributed + // to the environment is its slot's (M1); the version the platform registered is still never restored + // into the package's row. + for (const [door, address] of [['naming the package', { packageId: PKG }], ['naming no package (the name\'s one holder)', {}]] as const) { + it(`after the platform withdraws its record, rollback ${door} of the version the platform registered: refused 409 RESOURCE_CONFLICT, the package's row byte-identical (BASE: the platform's version written into the package's row)`, async () => { + const manager = await platformThenPackage(); + await manager.unregister('skill', NAME, { notify: false, origin: 'platform' }); + const history = (await driver.find('sys_metadata_history', { where: { type: 'skill', name: NAME } })) as Array>; + const platformVersion = Number(history.find((row) => String(row.metadata).includes('platform v1'))!.version); + const before = JSON.stringify(await rowOf(PKG)); + + const refused: any = await manager.rollback('skill', NAME, platformVersion, address).catch((error) => error); + + expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); + expect(String(refused.message)).toContain('the platform registered'); + expect(JSON.stringify(await rowOf(PKG))).toBe(before); + expect(((await manager.get('skill', NAME, PKG)) as any)?.instructions).toBe('package rules'); + }); + } + it('the platform withdrawing its record leaves the environment\'s own item of the name', async () => { const manager = managerOver(); await manager.register('skill', NAME, platformSkill('platform v1'), { notify: false, origin: 'platform' }); @@ -4900,6 +4920,31 @@ describe('[#37039] a stored row\'s package binding is read from its package colu expect((await memory.listPackageBindings('skill')).degraded).toBe(false); }); + /** + * [#37604] A loader that cannot be read at all loses both walks of one + * `listPackageBindings` read: it is named once in `errors`, and its rows + * are not read a second time. BEFORE: `errors` named it twice, and the + * failure was reported twice for one read. + */ + it('[#37604] listPackageBindings over a loader the list walk lost names it once and does not read its rows again (BEFORE: named twice)', async () => { + const rowBindingReads = vi.fn(async () => { throw new Error('sys_metadata unreachable'); }); + const unreachable: MetadataLoader = { + contract: { name: 'down', protocol: 'datasource:', capabilities: { read: true, write: false, watch: false, list: true } }, + async load() { throw new Error('sys_metadata unreachable'); }, + async loadMany() { throw new Error('sys_metadata unreachable'); }, + async list() { throw new Error('sys_metadata unreachable'); }, + async exists() { return false; }, + async stat() { return null; }, + loadRowBindings: rowBindingReads, + } as unknown as MetadataLoader; + const manager = new MetadataManager({ formats: ['json'], loaders: [] }); + manager.registerLoader(unreachable); + const read = await manager.listPackageBindings('skill'); + expect(read.degraded).toBe(true); + expect(read.errors.filter((error) => error.startsWith('down:'))).toHaveLength(1); + expect(rowBindingReads).not.toHaveBeenCalled(); + }); + /** * [#37130 N7] Two nodes over the same rows, on a first boot: both read the * legacy agent row with its column empty, and the first node's priming pass @@ -4946,3 +4991,32 @@ describe('[#37039] a stored row\'s package binding is read from its package colu expect(await manager.list('skill')).toContainEqual({ name: 'normal', label: 'normal', instructions: 'normal' }); }); }); + +// ---------- [#37604 N5] one reader of the platform's own record ---------- + +describe('[#37604 N5] isPlatformRecordRow is the one reader, and the restore refusal asks it', () => { + const marked = JSON.stringify({ name: 'helper', instructions: 'x', _provenance: 'platform' }); + + it('a package-less row whose body carries the mark is the platform\'s record: the restore is refused with the envelope', () => { + const row = { package_id: null, metadata: marked }; + expect(isPlatformRecordRow(row)).toBe(true); + let refused: any; + try { refusePlatformRecordRestore('skill', 'helper', row); } catch (error) { refused = error; } + expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); + expect(String(refused.message)).toContain('platform\'s own record'); + expect(String(refused.message)).toContain('until the platform\'s next registration at boot'); + }); + + it('a row bound to a package by its column is that package\'s, whatever its body keeps: not refused (BEFORE: refused, prescribing to name the package already named)', () => { + const row = { package_id: 'com.acme.crm', metadata: marked }; + expect(isPlatformRecordRow(row)).toBe(false); + expect(() => refusePlatformRecordRestore('skill', 'helper', row)).not.toThrow(); + }); + + it('a history row attributed to the environment reads as a version the platform registered; one attributed to a package does not', () => { + expect(isPlatformRecordRow({ package_id: ENVIRONMENT_HISTORY_MARK, metadata: marked })).toBe(true); + expect(isPlatformRecordRow({ package_id: 'com.acme.crm', metadata: marked })).toBe(false); + expect(isPlatformRecordRow({ package_id: null, metadata: JSON.stringify({ name: 'helper', _provenance: 'platform', _packageId: 'com.acme.crm' }) })).toBe(false); + expect(isPlatformRecordRow({ package_id: null, metadata: '{not json' })).toBe(false); + }); +}); diff --git a/packages/metadata/src/loaders/database-loader.ts b/packages/metadata/src/loaders/database-loader.ts index 2b7703b4a48..ce468d2066f 100644 --- a/packages/metadata/src/loaders/database-loader.ts +++ b/packages/metadata/src/loaders/database-loader.ts @@ -1929,7 +1929,14 @@ export class DatabaseLoader implements MetadataLoader { // registration alone: a rollback never restores it (a restored body is // written without the platform's mark, so the row would stop being the // platform's record). Refused before anything is written. - refusePlatformRecordRestore(type, name, existing); + // [#37604] …nor writes a version the platform registered into a package's + // row: the row this rollback writes is the slot's (or, for any other type, + // the name's row), and the version is judged by its history row. + refusePlatformRecordRestore(type, name, existing, { + historyRow: slot ? slot.recorded : await this.historyVersionRow(type, name, targetVersion), + version: targetVersion, + intoPackageId: slot ? slot.packageId : (existing ? storedRowColumnPackageId(existing) : null), + }); if (restoresBinding) { // [#32540 C8] Refused before any write: an object the column cannot // store, or an object-less binding whose place an unnameable row holds. @@ -2039,7 +2046,7 @@ export class DatabaseLoader implements MetadataLoader { targetVersion: number, restoredData: unknown, packageId: string | null | undefined, - ): Promise<{ rows: Array>; packageId?: string } | undefined> { + ): Promise<{ rows: Array>; packageId?: string; recorded?: Record } | undefined> { const bySlot = await this.rowSlots(type, name); if (bySlot.size === 0) return { rows: [] }; let key: string; @@ -2072,7 +2079,7 @@ export class DatabaseLoader implements MetadataLoader { } refuseSlotNotHeld(bySlot, type, name, versionOwner); } - return { rows: bySlot.get(key) ?? [], packageId: slotPackage }; + return { rows: bySlot.get(key) ?? [], packageId: slotPackage, recorded }; } /** @@ -2689,27 +2696,70 @@ function generateId(): string { return `meta_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`; } +/** + * [#37013, #37604 N5] Whether a stored row is the platform's own record: its + * `package_id` column names no package (empty, or the environment's history + * mark), and its stored body carries the platform's mark and names no package + * ({@link isPlatformOrigin}). Read off a `sys_metadata` row, it says whether + * the row is the record the platform's registration writes; off a + * `sys_metadata_history` row, whether the version is one the platform + * registered. A row bound to a package by its column is that package's, + * whatever its body keeps. The one reader of the fact: the restore refusal + * ({@link refusePlatformRecordRestore}), the metadata protocol's overlay + * census and its adoption of orphans ask it, so they cannot disagree. + */ +export function isPlatformRecordRow(row: Record | null | undefined): boolean { + if (!row || storedRowColumnPackageId(row) !== null) return false; + return isPlatformOrigin(storedRowBodyOf(row)); +} + /** * [#37013, #37130] Refuse a rollback or restore whose target `row` (a - * `sys_metadata` row, its body read with {@link storedRowBodyOf}) is the - * platform's own record: `409 RESOURCE_CONFLICT`, naming the fix, before - * anything is written. Only the platform's registration writes that record; a - * rollback restores a package's or the environment's item. The one rule the - * metadata service's `rollback` ({@link DatabaseLoader.registerRollback}) and - * the metadata protocol's restore doors (`rollbackMetaItem` and the restore - * limb of `revertCommit`, through `SysMetadataRepository.restoreVersion`) - * share: a row the platform's record does not hold passes. + * `sys_metadata` row) is the platform's own record ({@link isPlatformRecordRow}): + * `409 RESOURCE_CONFLICT`, naming the fix, before anything is written. Only + * the platform's registration writes that record; a rollback restores a + * package's or the environment's item. The one rule the metadata service's + * `rollback` ({@link DatabaseLoader.registerRollback}) and the metadata + * protocol's restore doors (`rollbackMetaItem` and the restore limb of + * `revertCommit`, through `SysMetadataRepository.restoreVersion`) share: a + * row the platform's record does not hold passes. + * + * [#37604] `restored`, when stated, is the version the restore would write: + * its history row, its number, and the package whose row it writes (`null`: + * the package-less row). A version the platform registered (its history row + * read by {@link isPlatformRecordRow}) is never written into a package's row, + * refused with the same envelope: after the platform withdraws its record, + * a name's one remaining holder may be a package, whose slot the + * environment's versions then belong to, and the platform's body would + * become that package's item. */ -export function refusePlatformRecordRestore(type: string, name: string, row: Record | null | undefined): void { - if (!row || !isPlatformOrigin(storedRowBodyOf(row))) return; - const err = new Error( - `${type}/${name}: the row this rollback would restore is the platform's own record, which only the platform's registration writes. ` + - 'It is not rolled back: the platform registers it again at its next boot. To restore an earlier version of a package\'s item of the name, name that package; ' + - 'to make an earlier version the environment\'s own item of the name, save that version\'s body again.', - ) as Error & { code?: string; status?: number }; +export function refusePlatformRecordRestore( + type: string, + name: string, + row: Record | null | undefined, + restored?: { historyRow: Record | null | undefined; version: number; intoPackageId: string | null | undefined }, +): void { + if (isPlatformRecordRow(row)) { + throw platformRecordConflict( + `${type}/${name}: the row this rollback would restore is the platform's own record, which only the platform's registration writes. ` + + 'It is not rolled back: the platform registers it again at its next boot. To restore an earlier version of a package\'s item of the name, name that package; ' + + 'to make an earlier version the environment\'s own item of the name, save that version\'s body again, which holds until the platform\'s next registration at boot writes its record back.', + ); + } + const into = restored?.intoPackageId; + if (restored && typeof into === 'string' && into !== '' && isPlatformRecordRow(restored.historyRow)) { + throw platformRecordConflict( + `${type}/${name}: version ${restored.version} is a version the platform registered, and this rollback would write it into package '${into}''s row. ` + + `It is not restored: a package's rollback restores that package's own versions. To make that body package '${into}''s item, save it again naming the package.`, + ); + } +} + +function platformRecordConflict(message: string): Error { + const err = new Error(message) as Error & { code?: string; status?: number }; err.code = 'RESOURCE_CONFLICT'; err.status = 409; - throw err; + return err; } /** diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index c56b60e9f7d..0e7ed80d167 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -1827,7 +1827,8 @@ export class MetadataManager implements IMetadataService { * reads it. * * Uncached: it walks the loaders as {@link list} does, then once more for - * the rows. A row loader that cannot be read is reported as {@link list} + * the rows, skipping a loader the first walk lost (named once in `errors`). + * A row loader that cannot be read is reported as {@link list} * reports a loader, and makes the answer `degraded`. [#37130 N2] So does a * loader of stored rows (`datasource:`) that offers no * {@link MetadataLoader.loadRowBindings}, named in `errors`: its items @@ -1835,11 +1836,15 @@ export class MetadataManager implements IMetadataService { */ async listPackageBindings(type: string): Promise<{ items: MetadataPackageBinding[]; degraded: boolean; errors: string[] }> { const canonical = canonicalMetadataServiceType(type); - const { items, degraded: listDegraded, errors } = await this.readListKeyed(canonical); + const { items, degraded: listDegraded, errors, lostLoaders } = await this.readListKeyed(canonical); const slotted = PACKAGE_SLOTTED_STORE_TYPES.has(canonical); const rowColumns = new Map(); let degraded = listDegraded; for (const loader of this.loaders.values()) { + // [#37604] A loader the list walk above already lost is named once in + // `errors` and reported once: none of its items is listed, so its rows' + // columns bind nothing, and it is not read a second time. + if (lostLoaders.has(loader.contract.name)) continue; if (typeof loader.loadRowBindings !== 'function') { // [#37130 N2] A loader of stored rows that reads no package column // leaves every item it holds answering its registration's binding: @@ -2144,7 +2149,7 @@ export class MetadataManager implements IMetadataService { * item {@link list} answers, under the key the store holds it by, in store * order (the registry's, then each loader's in loader order). */ - private async readListKeyed(type: string): Promise<{ items: Map; degraded: boolean; errors: string[] }> { + private async readListKeyed(type: string): Promise<{ items: Map; degraded: boolean; errors: string[]; lostLoaders: Set }> { const items = new Map(); // From in-memory registry @@ -2167,6 +2172,9 @@ export class MetadataManager implements IMetadataService { // alongside the set. let degraded = false; const errors: string[] = []; + // [#37604] The loaders this read lost, by name: `listPackageBindings` + // walks the loaders again and names each lost one only once. + const lostLoaders = new Set(); for (const loader of this.loaders.values()) { try { await this.admitLoaderItems(loader, type, items); @@ -2182,12 +2190,13 @@ export class MetadataManager implements IMetadataService { throw e; } degraded = true; + lostLoaders.add(loader.contract.name); errors.push(`${loader.contract.name}: ${e instanceof Error ? e.message : String(e)}`); this.reportLoaderReadFailure(loader.contract.name, type, e); } } - return { items, degraded, errors }; + return { items, degraded, errors, lostLoaders }; } /** diff --git a/packages/metadata/src/package-slotted-store.ts b/packages/metadata/src/package-slotted-store.ts index 1a8abbd39c5..1c719c78965 100644 --- a/packages/metadata/src/package-slotted-store.ts +++ b/packages/metadata/src/package-slotted-store.ts @@ -885,7 +885,8 @@ export function storeRowWriteKey( * platform's own record is refused, never written, at all three restore * doors: the metadata service's `rollback`, and the protocol's * `rollbackMetaItem` and the restore limb of `revertCommit` - * (`refusePlatformRecordRestore`). Two undo writes of the metadata protocol + * (`refusePlatformRecordRestore`), and so is a restore of a version the + * platform registered into a package's row. Two undo writes of the metadata protocol * put a row back as the same operation found it, byte for byte: the undo of a * refused batch publish's landed promotions (`undoLandedPromotions`) and the * undo of a batch row the registry refused (`undoBatchRowWrite`); the mark diff --git a/packages/spec/src/contracts/metadata-service.ts b/packages/spec/src/contracts/metadata-service.ts index 0ddf2bc0295..6bd31f39c1d 100644 --- a/packages/spec/src/contracts/metadata-service.ts +++ b/packages/spec/src/contracts/metadata-service.ts @@ -459,7 +459,9 @@ export interface IMetadataService { * not be read leaves the set partial. A row loader whose rows could not be * read leaves an item it holds answering `'registration'` unless the item * is a copy the registry primed from that loader's rows, which still - * answers `'row'` and the column it was read with. Either way a consumer + * answers `'row'` and its row's column as the registry last knew it: the + * column the boot priming pass wrote when that pass bound the row, else + * the column it was read with. Either way a consumer * that gates on the binding treats a degraded answer as unknown. * * Optional, like {@link listDiagnosed}: a service without it cannot tell a