diff --git a/.changeset/37013-platform-skill-own-slot.md b/.changeset/37013-platform-skill-own-slot.md index dd1cc60f9c5..3239a88d7c4 100644 --- a/.changeset/37013-platform-skill-own-slot.md +++ b/.changeset/37013-platform-skill-own-slot.md @@ -21,7 +21,7 @@ For every type stored per `(package, name)` (`skill`, `agent`, `tool` and the re - The readers that rebuild the store from loaders and rows keep both records: the plural read (`loadMany`, `loadManyKeyed`) gives the platform's entry a key of its own, `list` keeps a loader's platform row beside a package's slot and a loader's package item beside a platform slot, and a read naming a package is never answered from the platform's record. - `MetadataManager.unregister(type, name, { origin: 'platform' })` withdraws the platform's record only, from the registry, every loader (`MetadataLoaderDeleteOptions.platformOnly`) and every cluster peer. A package's item of the name and the environment's own item are never taken, for any type, and nothing is refused however many packages hold the name. Before, a removal naming no package took every slot of a name one package held. On a host that declares a package id, the boot pass leaves the platform's stored record without the host's package, for every type, so the withdrawal takes the registry's copy too. - `MetadataManager.getPlatformItem(type, name)` reads the platform's record only, never a package's item and never the environment's own. -- No other write carries the platform stamp. `register` without `origin: 'platform'`, `registerInMemory`, `save` and `rollback` store the body without it, and so do the metadata protocol's save door and its restore doors (`rollbackMetaItem` and the restore limb of `revertCommit`); a stored row the boot pass re-registers keeps it only when the row held it as read. `rollback` whose row is the platform's own record is refused (`409 RESOURCE_CONFLICT`, naming the fix), with nothing written. The metadata protocol's two undo writes, of a refused batch publish's landed promotions and of a failed batch row write, put a row back as the same operation found it, byte for byte, so the mark comes back only where the row held it. A body served from a loader other than a `datasource:` one is served without it; `getPublished` serves it on the answer's top level only when the stored item carries it there, and never inside a publish snapshot; and the artifact door refuses an item that carries it, with or without a manifest id (`VALIDATION_ERROR` at `_provenance`, naming the fix). A `_provenance` key nested in the body (an authored `metadata` record, for one) is the author's data: it is kept as written and never read as the mark. A body that names a package is that package's item, whatever `_provenance` it carries. +- No other write carries the platform stamp. `register` without `origin: 'platform'`, `registerInMemory`, `save` and `rollback` store the body without it, and so do the metadata protocol's save door and its restore doors (`rollbackMetaItem` and the restore limb of `revertCommit`) on every restore whose row is not the platform's own record; a stored row the boot pass re-registers keeps it only when the row held it as read. A restore whose row is the platform's own record is refused (`409 RESOURCE_CONFLICT`, naming the fix), with nothing written, at all three restore doors: `rollback`, and the metadata protocol's `rollbackMetaItem` and the restore limb of `revertCommit`. The metadata protocol's two undo writes, of a refused batch publish's landed promotions and of a failed batch row write, put a row back as the same operation found it, byte for byte, so the mark comes back only where the row held it. A body served from a loader other than a `datasource:` one is served without it; `getPublished` serves it on the answer's top level only when the stored item carries it there (the platform's own record's publish snapshot, served as the answer, keeps the mark it carries at its top), and never on a snapshot nested inside the answer; and the artifact door refuses an item that carries it, with or without a manifest id (`VALIDATION_ERROR` at `_provenance`, naming the fix). A `_provenance` key nested in the body (an authored `metadata` record, for one) is the author's data: it is kept as written and never read as the mark. A body that names a package is that package's item, whatever `_provenance` it carries. - `@objectstack/metadata` exports the mark's one definition (`PLATFORM_PROVENANCE`, `carriesPlatformStamp`, `isPlatformOrigin`, `withoutPlatformOrigin`); the artifact door and the metadata protocol's doors read it. - `@objectstack/metadata-protocol`: the boot census `metadata_sealed_overlay_unserved` no longer names the platform's own row beside a package that ships the name, nor prescribes deleting it. - Reads naming no package, and every removal and write without the option, keep their rules. diff --git a/.changeset/37130-platform-record-restore-doors.md b/.changeset/37130-platform-record-restore-doors.md new file mode 100644 index 00000000000..39426cda48f --- /dev/null +++ b/.changeset/37130-platform-record-restore-doors.md @@ -0,0 +1,30 @@ +--- +'@objectstack/metadata': patch +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol)!: the protocol's restore doors refuse a restore whose row is the platform's own record, and the history selector never addresses the package-less row for a package that neither holds nor ships the name + +Clause-②: yes (narrowing) +Metadata-protocol: none +Skills-docs: none — no `skills/` page teaches the protocol's restore doors, the history `?package=` selector or `listPackageBindings` + + + +**BREAKING**, in two places, each a refusal of a request that was answered before: + +- **The metadata protocol's `rollbackMetaItem` and the restore limb of `revertCommit` refuse a restore whose row is the platform's own record** (the row `MetadataManager.register(…, { origin: 'platform' })` writes), with the refusal the metadata service's `rollback` gives: `409 RESOURCE_CONFLICT`, naming the fix, nothing written. `revertCommit` reports that item in `failed[]` and still reverts the commit's other items. Before, both doors wrote the version back without the platform's mark, so the row stopped being the platform's record, and a process primed from the rows answered a read naming the name's one package holder with the platform's old body until the platform registered again. + What to do: nothing for a package's or the environment's own item. 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. +- **The history, diff and rollback doors' `?package=` selector refuses a package that neither holds a row of the name nor ships it** with `409 RESOURCE_CONFLICT` `not-held-by-qualifier`, naming every holder, as its description states, also when the name's package-less row is stored. Before, such a package addressed the package-less row a read naming it falls back to, and read or restored that row's versions. The package-less row is a package's slot only when the package ships the name. + What to do: address the package-less row through the package that ships the name, or bare when no other row of the name is stored. + +Also in `@objectstack/metadata`: + +- `refusePlatformRecordRestore(type, name, row)` is exported: the one refusal the service's `rollback` and the protocol's two restore doors ask, so the three cannot disagree. +- `list()` lists a stored row whose body's `_packageId` stamp differs from its package column once, under the column, after the boot priming pass, where it listed the row twice (the primed copy under the stamp). A read naming the column's package answers it, as on a process that never primed it. +- `listPackageBindings` is `degraded`, naming the loader in `errors`, when a loader of stored rows (`datasource:`) offers no `loadRowBindings`: the items it holds answer their registration's binding, which is not their rows'. No such loader ships in this repository. +- A node whose boot priming pass finds a legacy row already bound by another node answers the bound package for that row's item, where it answered `null` (fail-closed) until it restarted. + +Also in `@objectstack/metadata-protocol`: + +- `SysMetadataRepository.restoreVersion` takes `refusePlatformRecord: true` to ask `refusePlatformRecordRestore` (`@objectstack/metadata`) on the row it writes; the undo writes do not pass it. diff --git a/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts b/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts index dc8f302c02e..446a081d009 100644 --- a/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts +++ b/packages/metadata-protocol/src/protocol-diff-history-slots.33308.test.ts @@ -13,9 +13,10 @@ * a named version another holder owns (or one attributed to no package, * while two hold the name) is refused `404 VERSION_NOT_FOUND` saying whose; * - `?package=` naming a package that neither holds nor ships the name is - * refused `409 not-held-by-qualifier`; the environment's slot addressed - * through a package (the read falls back to the package-less row) takes - * that row as its `to` side; + * refused `409 not-held-by-qualifier`, [#37130] beside the package-less row + * too; the environment's slot addressed through a package that ships the + * name (the read falls back to the package-less row) takes that row as its + * `to` side; * - CONTROL: a name one slot holds diffs bare as before, its whole log; * - `?package=` on a type not stored per package is refused `400`. * @@ -48,7 +49,7 @@ const ACTIVE = [ { package_id: ALPHA, version: 3, state: 'active', metadata: JSON.stringify(body('alpha r2')) }, ]; -function fakeHost(options: { candidates: string[]; unbound?: boolean; history?: unknown[]; active?: unknown[] }) { +function fakeHost(options: { candidates: string[]; unbound?: boolean; history?: unknown[]; active?: unknown[]; shippers?: string[] }) { const reads: string[] = []; const host: any = { engine: { registry: { readsByPackage: () => true, resolveItem: () => ({ status: 'resolved' }) } }, @@ -59,7 +60,7 @@ function fakeHost(options: { candidates: string[]; unbound?: boolean; history?: const row = active.find((r) => r.package_id === q.packageId) ?? active.find((r) => r.package_id === undefined); return row === undefined ? undefined : { row }; }, - shippedArtifactsOf: () => [], + shippedArtifactsOf: () => (options.shippers ?? []).map((id) => ({ _packageId: id })), resolveRowlessExpandedView: async () => undefined, rethrowUnlessMetadataStoreUnprovisioned: (error: unknown) => { throw error; }, findEnvironmentRows: async (table: string) => { @@ -157,7 +158,7 @@ describe('diffMetaItem reads one holder\'s versions of a by-package name (#33308 expect(reads).toEqual([]); }); - it('the environment\'s slot addressed through a package: the package-less row is the to side, never the bound one', async () => { + it('the environment\'s slot addressed through a package that ships the name: the package-less row is the to side, never the bound one; [#37130] one that neither holds nor ships it is refused', async () => { // Alpha's row first, so a read that picks the name's first active row picks the wrong slot. const active = [ { package_id: ALPHA, version: 3, state: 'active', metadata: JSON.stringify(body('alpha r1')) }, @@ -168,7 +169,12 @@ describe('diffMetaItem reads one holder\'s versions of a by-package name (#33308 { version: 2, package_id: ENVIRONMENT_HISTORY_MARK, metadata: JSON.stringify(body('env r2')) }, { version: 3, package_id: ALPHA, metadata: JSON.stringify(body('alpha r1')) }, ]; - const { host } = fakeHost({ candidates: [ALPHA], unbound: true, history, active }); + // [#37130] A package that neither holds nor ships the name never addresses the package-less row. + const unshipped = await refusalOf(fakeHost({ candidates: [ALPHA], unbound: true, history, active }).host + .diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: BETA })); + expect(unshipped).toBeInstanceOf(PackageScopedNameRefusedError); + expect(unshipped.refusal.reason).toBe('not-held-by-qualifier'); + const { host } = fakeHost({ candidates: [ALPHA], unbound: true, history, active, shippers: [BETA] }); const bare = await refusalOf(host.diffMetaItem({ type: 'flow', name: 'shared_flow' })); expect(bare.refusal.candidates).toEqual([{ kind: 'package', packageId: ALPHA }, { kind: 'environment' }]); const env = await host.diffMetaItem({ type: 'flow', name: 'shared_flow', packageId: BETA }); diff --git a/packages/metadata-protocol/src/protocol-history-slots.test.ts b/packages/metadata-protocol/src/protocol-history-slots.test.ts index ac0d6af51e3..66d62afeae3 100644 --- a/packages/metadata-protocol/src/protocol-history-slots.test.ts +++ b/packages/metadata-protocol/src/protocol-history-slots.test.ts @@ -4,7 +4,8 @@ * [ADR-0150 D3/D4/D5] Which row slot the history and rollback doors address * (`historySlotOf`), judged against a fake host so each arm is pinned on its * own: the served row's slot for `?package=P` (P's own, or the package-less - * row the read falls back to, whether or not P ships the name), the bare + * row the read falls back to when P ships the name; [#37130] a P that neither + * holds nor ships the name is refused, never addressed at that row), the bare * plain read's refusal counting holders in code, `?package=` refused on a * type not stored per package, and whether the addressed slot holds a row. */ @@ -67,12 +68,33 @@ describe('historySlotOf: ?package=P addresses the slot of the row a read naming expect(slot).toEqual({ owner: { packageId: null, sole: true }, addressed: true, held: true }); }); - it('P does not ship the name and the read falls back to the package-less row: the environment slot', async () => { - const slot = await historySlotOf( + it('[#37130] P neither holds nor ships the name and the read falls back to the package-less row: refused not-held-by-qualifier, never that row (BASE: the environment slot)', async () => { + const refused = await historySlotOf( fakeHost({ unbound: true, served: { package_id: null }, shippers: [] }), { type: 'flow', name: 'n', packageId: 'com.a' }, + ).catch((error) => error); + expect(refused).toBeInstanceOf(PackageScopedNameRefusedError); + expect(refused.refusal.reason).toBe('not-held-by-qualifier'); + expect(refused.refusal.callerPackageId).toBe('com.a'); + expect(refused.refusal.candidates).toEqual([{ kind: 'environment' }]); + }); + + it('[#37130] beside another package\'s row too: a P that neither holds nor ships the name is refused naming both holders (BASE: the environment slot)', async () => { + const refused = await historySlotOf( + fakeHost({ candidates: ['com.b'], unbound: true, served: { package_id: null }, shippers: ['com.b'] }), + { type: 'flow', name: 'n', packageId: 'com.a' }, + ).catch((error) => error); + expect(refused).toBeInstanceOf(PackageScopedNameRefusedError); + expect(refused.refusal.reason).toBe('not-held-by-qualifier'); + expect(refused.refusal.candidates).toEqual([{ kind: 'package', packageId: 'com.b' }, { kind: 'environment' }]); + }); + + it('CONTROL: P\'s .custom pair row that declares the override of P is P\'s address: that row\'s slot', async () => { + const slot = await historySlotOf( + fakeHost({ candidates: ['com.a.custom'], unbound: true, served: { package_id: 'com.a.custom' }, shippers: [] }), + { type: 'flow', name: 'n', packageId: 'com.a' }, ); - expect(slot).toEqual({ owner: { packageId: null, sole: true }, addressed: true, held: true }); + expect(slot).toEqual({ owner: { packageId: 'com.a.custom', sole: false }, addressed: true, held: true }); }); it("P's own row: P's slot, not sole beside the package-less row", async () => { diff --git a/packages/metadata-protocol/src/protocol-history-slots.ts b/packages/metadata-protocol/src/protocol-history-slots.ts index 8e63d8249a6..97d3e6d280e 100644 --- a/packages/metadata-protocol/src/protocol-history-slots.ts +++ b/packages/metadata-protocol/src/protocol-history-slots.ts @@ -33,7 +33,10 @@ * package-less row that read falls back to — else `P`'s own slot when `P` * ships the name in code and holds no row of it yet. A package that * neither holds a row of the name nor ships it is refused `409` naming - * every holder (`not-held-by-qualifier`). + * every holder (`not-held-by-qualifier`). [#37130] The package-less row is + * `P`'s slot only when `P` ships the name (ADR-0150 D4: that row is then + * `P`'s customization): a read naming any other package falls back to it + * too, and ⛔ such a package never addresses it. * * A version belongs to a slot by its history row's attribution * (`historyRowAttribution`, `@objectstack/metadata`). A version attributed to @@ -166,7 +169,8 @@ function refuseWhereBareReadRefuses(host: Pick, type: st * @throws {PackageScopedNameRefusedError} `ambiguous-in-environment` for a * bare request of a name two or more row slots hold (other than a row-held * base's, above), or the bare plain read's own refusal; `not-held-by-qualifier` for a package that neither - * holds a row of the name nor ships it, while another slot holds one. + * holds a row of the name nor ships it, while any slot holds one (the + * package-less row included, which such a package never addresses). */ export async function historySlotOf( host: Pick, @@ -196,7 +200,11 @@ export async function historySlotOf( const slot: string | null = served === undefined ? packageId : typeof binding === 'string' && binding !== '' ? binding : null; - if (!slots.includes(slot) && slots.length > 0 + // [#37130] `P` holds the slot it addresses by a row bound to it (its own, + // its pair's declared override); the package-less row the read falls back + // to is held by no package, and is `P`'s only when `P` ships the name. + const holdsSlot = slot !== null && slots.includes(slot); + if (!holdsSlot && slots.length > 0 && !shippingPackageIds(host.shippedArtifactsOf(type, name, undefined, member)).has(packageId)) { throw slotRefusal(type, name, 'not-held-by-qualifier', packageId, slots); } diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index b6236849abc..2fc997ab52c 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -1725,6 +1725,11 @@ export class ProtocolPackageCommitsFacet { // [ADR-0146 D2] …and, for the pair's row, the override write gate. deriveRestoredBody, ...memberOption(member), + // [#37130] The platform's own record is never restored: + // refused into `failed[]` as {@link rollbackMetaItem} + // refuses it, nothing written; the commit's other items + // still revert (ADR-0067 D3). + refusePlatformRecord: true, }); rowWritten = `its row was restored to the body of version ${restoreToVersion}`; revertPlan.push({ @@ -2258,6 +2263,9 @@ export class ProtocolPackageCommitsFacet { packageId: rollbackPackageId, // [#32905] …and only a version of that row's slot. ...(slot?.addressed ? { versionOf: slot.owner } : {}), + // [#37130] The platform's own record is never restored: refused + // as the metadata service's `rollback` refuses it, nothing written. + refusePlatformRecord: true, }); // #4521 — a rollback is a live write like any other: the restored // body must be the one the runtime dispatches on immediately, not 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 8d20b2071f1..08b0e430f04 100644 --- a/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts +++ b/packages/metadata-protocol/src/protocol.platform-mark-rollback.test.ts @@ -13,6 +13,7 @@ import { assertEngineFindOnePredicate, assertEngineUpdateDispatch, } from '@objectstack/metadata-core'; +import { DatabaseLoader, MetadataManager } from '@objectstack/metadata'; import { ObjectStackProtocolImplementation } from './protocol.js'; // Pay the source's dynamic `@objectstack/lint` load during collection, never inside a case. import '@objectstack/lint'; @@ -134,3 +135,90 @@ describe('[#37013] the protocol\'s save and restore doors write a body without t expect(stored._provenance).not.toBe('platform'); }); }); + +/** + * [#37130] A restore whose row is the platform's own record is refused at the + * protocol's two restore doors, as the metadata service's `rollback` refuses + * it (`refusePlatformRecordRestore`, `@objectstack/metadata`): `409 + * RESOURCE_CONFLICT`, nothing written. `revertCommit` reports the item in + * `failed[]` and reverts the commit's other items (ADR-0067 D3). + * + * BASE (main 5bf72422): both doors wrote the platform's row back without the + * mark, so the row stopped being the platform's record, and a process primed + * from the rows answered a read naming the name's one holder with the + * platform's old body (ADR-0150 D4: a package-less row at a held name is its + * one holder's customization) until the platform registered again. + */ +describe('[#37130] the protocol\'s restore doors refuse a restore whose row is the platform\'s own record', () => { + const PKG = 'com.acme.crm'; + + /** The name's package-less row as the platform's registration wrote it: v1 and v2 in history, v2 the row. */ + async function platformRecord(name = 'helper') { + const harness = makeEngine(); + const protocol = new ObjectStackProtocolImplementation(harness.engine); + await protocol.saveMetaItem({ type: 'skill', name, item: { ...skill('platform v1'), name } }); + await protocol.saveMetaItem({ type: 'skill', name, item: { ...skill('platform v2'), name } }); + 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 === name)) mark(row); + mark(harness.rows.find((r) => r.name === name)!); + return { ...harness, protocol }; + } + + it('rollbackMetaItem: refused 409 RESOURCE_CONFLICT, the row byte-identical (BASE: the platform\'s row was written back without the mark)', async () => { + const { protocol, rows } = await platformRecord(); + const before = JSON.stringify(rows); + + const refused = await protocol.rollbackMetaItem({ type: 'skill', name: 'helper', toVersion: 1 }).catch((error) => error); + + expect(refused).toMatchObject({ code: 'RESOURCE_CONFLICT', status: 409 }); + expect(String(refused.message)).toContain('platform\'s own record'); + expect(JSON.stringify(rows)).toBe(before); + }); + + it('revertCommit\'s restore limb: the item lands in failed[] 409-coded, nothing written, and the commit\'s other item still reverts (BASE: written back without the mark)', async () => { + const { protocol, rows, serveCommit } = await platformRecord(); + await protocol.saveMetaItem({ type: 'skill', name: 'other', item: { ...skill('other v1'), name: 'other' } }); + await protocol.saveMetaItem({ type: 'skill', name: 'other', item: { ...skill('other v2'), name: 'other' } }); + const helperBefore = JSON.stringify(rows.find((r) => r.name === 'helper')); + serveCommit({ + id: 'c1', commit_id: 'c1', organization_id: null, operation: 'apply', message: 'the commit under revert', created_at: '2026-01-01T00:00:00Z', + items: JSON.stringify([ + { type: 'skill', name: 'helper', existedBefore: true, prevVersion: 1 }, + { type: 'skill', name: 'other', 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('platform\'s own record'); + expect(res.reverted.map((entry: { name: string }) => entry.name)).toEqual(['other']); + expect(JSON.stringify(rows.find((r) => r.name === 'helper'))).toBe(helperBefore); + expect(JSON.parse(String(rows.find((r) => r.name === 'other')!.metadata)).label).toBe('other v1'); + }); + + it('RESTART: a process primed from the rows answers a read naming the name\'s one holder with that holder\'s item, never the platform\'s old body (BASE: the platform\'s v1)', async () => { + const { protocol, engine, rows, serveCommit } = await platformRecord(); + // The name's one package holder, its row bound by the package column as the protocol binds it, read + // first: a package-less row the boot pass registers after it is folded into its slot (ADR-0150 D4). + rows.unshift({ + id: 'row_pkg', type: 'skill', name: 'helper', state: 'active', organization_id: null, package_id: PKG, + version: 3, checksum: 'pkg', source: 'database', + metadata: JSON.stringify({ ...skill('package rules'), _packageId: PKG }), + }); + serveCommit({ + id: 'c1', commit_id: 'c1', organization_id: null, operation: 'apply', message: 'the commit under revert', created_at: '2026-01-01T00:00:00Z', + items: JSON.stringify([{ type: 'skill', name: 'helper', existedBefore: true, prevVersion: 1 }]), + }); + await protocol.revertCommit({ commitId: 'c1' }); + + // A process that starts over the rows, primed as the boot pass primes it (`MetadataPlugin`). + const primed = new MetadataManager({ formats: ['json'], loaders: [new DatabaseLoader({ engine })] }); + for (const item of await primed.loadMany>('skill')) { + await primed.register('skill', item.name as string, item, { notify: false, skipSourceLoader: true }); + } + expect(((await primed.get('skill', 'helper', PKG)) as { label?: string } | undefined)?.label).toBe('package rules'); + expect(((await primed.getPlatformItem('skill', 'helper')) as { label?: string } | undefined)?.label).toBe('platform v2'); + }); +}); diff --git a/packages/metadata-protocol/src/sys-metadata-repository.ts b/packages/metadata-protocol/src/sys-metadata-repository.ts index 89b850ce07f..5630f38952f 100644 --- a/packages/metadata-protocol/src/sys-metadata-repository.ts +++ b/packages/metadata-protocol/src/sys-metadata-repository.ts @@ -67,7 +67,7 @@ import { boundObjectOf } from '@objectstack/metadata/stored-item-package'; // [ruling 6677709817 (c)] The snapshot body both history writers store: the // written body without what the type's redactor marks not carried forward. import { historySnapshotBody } from '@objectstack/metadata/history-snapshot'; -import { ENVIRONMENT_HISTORY_MARK, PACKAGE_SLOTTED_STORE_TYPES, historyRowAttribution } from '@objectstack/metadata'; +import { ENVIRONMENT_HISTORY_MARK, PACKAGE_SLOTTED_STORE_TYPES, historyRowAttribution, refusePlatformRecordRestore } from '@objectstack/metadata'; import { readEnvWithDeprecation } from '@objectstack/types'; import type { MetadataRepository, @@ -1939,6 +1939,17 @@ export class SysMetadataRepository implements MetadataRepository { * version of the name, as before. */ versionOf?: HistoryVersionOwner; + /** + * [#37130] Refuse the restore when the active row it would write is the + * 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 + * (`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. + */ + refusePlatformRecord?: boolean; }, ): Promise<{ version: string; seq: number; item: MetadataItem }> { this.assertOpen(); @@ -2011,6 +2022,8 @@ 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); 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 122e1d2d1f4..ab69741f457 100644 --- a/packages/metadata/src/index.ts +++ b/packages/metadata/src/index.ts @@ -26,6 +26,9 @@ export { DatabaseLoader, ENVIRONMENT_HISTORY_MARK, historyRowAttribution, + // [#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, 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 2aed9b26c20..975076a0a5d 100644 --- a/packages/metadata/src/loaders/database-loader.test.ts +++ b/packages/metadata/src/loaders/database-loader.test.ts @@ -4800,13 +4800,12 @@ describe('[#37039] a stored row\'s package binding is read from its package colu await manager.register('skill', 'code_only', { name: 'code_only', label: 'code_only', instructions: 'x', _packageId: ALPHA }, { notify: false }); await manager.register('skill', 'platform_only', { name: 'platform_only', label: 'p', instructions: 'p' }, { notify: false, origin: 'platform' }); // `code_only` and `platform_only` were written through to the row loader by their register: the store - // recorded each one's column. `differs` is listed twice, as `list` lists it: the registry's primed copy - // (keyed by its body's BETA stamp) and the row (keyed by its ALPHA column). Both are the row's item and - // answer its column (BEFORE: the copy's only readable binding was BETA). + // recorded each one's column. [#37130] `differs` is listed once, as `list` lists it: the registry's primed + // copy is filed under the row's ALPHA column, the key the row loader lists it by (BEFORE #37130: twice, + // the copy keyed by its body's BETA stamp beside the row; before #37039 the copy answered BETA). expect(await bindingsOf(manager)).toEqual([ ['code_only', ALPHA, 'row'], ['differs', ALPHA, 'row'], - ['differs', ALPHA, 'row'], ['legacy', null, 'row'], ['neither', null, 'row'], ['platform_only', null, 'row'], @@ -4819,6 +4818,19 @@ describe('[#37039] a stored row\'s package binding is read from its package colu expect((read.items.find((entry) => entry.name === 'legacy')!.data as { _packageId?: string })._packageId).toBe(BETA); }); + it('[#37130] list() after the boot pass lists a row whose body stamp differs from its column once, under its column: a read naming the column\'s package answers it, the stamp\'s answers nothing (BASE: listed twice, the primed copy under the stamp)', async () => { + await seed('differs', ALPHA, BETA); + const manager = await booted(); + const listed = (await manager.list('skill')) as Array<{ name?: string; _packageId?: string }>; + expect(listed.map((item) => [item.name, item._packageId])).toEqual([['differs', BETA]]); + expect(((await manager.get('skill', 'differs', ALPHA)) as { label?: string } | undefined)?.label).toBe('differs'); + expect(await manager.get('skill', 'differs', BETA)).toBeUndefined(); + // CONTROL: an unprimed process over the same rows answers the same: the loader keys the row by its column. + const cold = new MetadataManager({ formats: ['json'], loaders: [new DatabaseLoader({ driver })] }); + expect(((await cold.list('skill')) as unknown[])).toHaveLength(1); + expect(await cold.get('skill', 'differs', BETA)).toBeUndefined(); + }); + it('listPackageBindings: an item no stored row holds answers its registration\'s binding, marked `registration`', async () => { const manager = new MetadataManager({ formats: ['json'], loaders: [new MemoryLoader()] }); await manager.register('skill', 'pkg_skill', { name: 'pkg_skill', label: 'a', instructions: 'a', _packageId: ALPHA }, { notify: false }); @@ -4860,6 +4872,62 @@ describe('[#37039] a stored row\'s package binding is read from its package colu expect((await new DatabaseLoader({ driver }).loadRowBindings('agent')).map((entry) => [entry.name, entry.rowPackageId])).toEqual([['helper', ALPHA]]); }); + /** + * [#37130 N2] A loader of stored rows (`datasource:`) that cannot read its + * rows' package column leaves every item it holds answering its + * registration's binding: the answer is `degraded`, naming the loader, so a + * consumer that gates on the binding treats it as unknown. BEFORE: the same + * items, `degraded: false`. No such loader ships in this repository. + */ + it('[#37130 N2] listPackageBindings over a `datasource:` loader without loadRowBindings is degraded, naming the loader (BEFORE: an undegraded `registration` answer)', async () => { + const rowsWithoutColumns: MetadataLoader = { + contract: { name: 'columnless', protocol: 'datasource:', capabilities: { read: true, write: false, watch: false, list: true } }, + async load(_type: string, name: string) { return name === 'pkg_skill' ? { data: { name, label: 'a', instructions: 'a', _packageId: ALPHA }, source: 'columnless', format: 'json', loadTime: 0 } : { data: null }; }, + async loadMany() { return [{ name: 'pkg_skill', label: 'a', instructions: 'a', _packageId: ALPHA }] as T[]; }, + async list() { return ['pkg_skill']; }, + async exists(_type: string, name: string) { return name === 'pkg_skill'; }, + async stat() { return null; }, + } as unknown as MetadataLoader; + const manager = new MetadataManager({ formats: ['json'], loaders: [] }); + manager.registerLoader(rowsWithoutColumns); + const read = await manager.listPackageBindings('skill'); + expect(read.degraded).toBe(true); + expect(read.errors.some((error) => error.startsWith('columnless:') && error.includes('loadRowBindings'))).toBe(true); + expect(read.items.map((entry) => [entry.name, entry.packageId, entry.source])).toEqual([['pkg_skill', ALPHA, 'registration']]); + // CONTROL: the same item from a loader of no rows answers `registration` undegraded. + const memory = new MetadataManager({ formats: ['json'], loaders: [new MemoryLoader()] }); + await memory.register('skill', 'pkg_skill', { name: 'pkg_skill', label: 'a', instructions: 'a', _packageId: ALPHA }, { notify: false }); + expect((await memory.listPackageBindings('skill')).degraded).toBe(false); + }); + + /** + * [#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 + * binds the column. The second node's pass finds the row already bound and + * writes nothing; its primed copy answers the column as the row now holds + * it. BEFORE: `null`, the column as it read it, until that node restarted + * (fail-closed: a gating consumer saw no binding). + */ + it('[#37130 N7] two nodes priming the same legacy row: the node that finds it already bound answers the bound package, `row` (BEFORE: null until restart)', async () => { + await driver.create('sys_metadata', { + id: 'legacy', type: 'agent', name: 'helper', state: 'active', version: 1, checksum: 'legacy', source: 'database', + package_id: null, metadata: JSON.stringify({ name: 'helper', label: 'Helper', packageId: ALPHA }), + }); + const winner = new MetadataManager({ formats: ['json'], loaders: [new DatabaseLoader({ driver })] }); + const loser = new MetadataManager({ formats: ['json'], loaders: [new DatabaseLoader({ driver })] }); + // Both read before either binds. + const winnerItems = await winner.loadMany>('agent'); + const loserItems = await loser.loadMany>('agent'); + for (const item of winnerItems) await winner.register('agent', item.name as string, item, { notify: false, skipSourceLoader: true }); + for (const item of loserItems) await loser.register('agent', item.name as string, item, { notify: false, skipSourceLoader: true }); + expect(vi.mocked(driver.update).mock.calls).toEqual([['sys_metadata', 'legacy', { package_id: ALPHA }]]); + for (const node of [winner, loser]) { + const read = await node.listPackageBindings('agent'); + expect(read.degraded).toBe(false); + expect(read.items.map((entry) => [entry.name, entry.packageId, entry.source])).toEqual([['helper', ALPHA, 'row']]); + } + }); + /** * A row whose stored body is a JSON primitive is not an object the loader can * record a column against. The plural read serves the other rows as before diff --git a/packages/metadata/src/loaders/database-loader.ts b/packages/metadata/src/loaders/database-loader.ts index bd6258bfa6f..2b7703b4a48 100644 --- a/packages/metadata/src/loaders/database-loader.ts +++ b/packages/metadata/src/loaders/database-loader.ts @@ -1334,6 +1334,14 @@ export class DatabaseLoader implements MetadataLoader { if (!read) return; const rows = await this._find(this.tableName, { where: this.baseFilter(type, name) }); const row = rows.find((candidate) => String(candidate.id) === read.id); + // [#37130 N7] The handed-out body answers the column as the row holds it now: + // another node's boot pass may have bound it since this node read it empty, + // and then nothing is written here. ⛔ Never the column as read, which this + // node would otherwise answer until it restarted. + if (row && storedRowColumnPackageId(row) !== this.readRowColumns.get(item)) { + this.recordRowColumn(item, storedRowColumnPackageId(row)); + this.invalidate(type, name); + } if (!row || row.package_id === read.packageId || storedRowPackageId(row) !== read.packageId) return; // [#32488 item 3, R8-A] The loader's own rows only, as `migrateDatabaseLoaderRowPackages` // binds them: another writer's row whose body carries a copied stamp is bound to nothing. @@ -1921,7 +1929,7 @@ 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. - if (existing && isPlatformOrigin(storedRowBodyOf(existing))) refusePlatformRecordRollback(type, name); + refusePlatformRecordRestore(type, name, existing); 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. @@ -2682,25 +2690,33 @@ function generateId(): string { } /** - * [#37013] A row's stored body as written (`metadata`, parsed when stored as - * text), for reading a stamp off it; `undefined` for a missing row or a body - * that does not parse, which is then no platform record. - */ -/** - * [#37013] Refuse a rollback whose row is the platform's own record: `409 - * RESOURCE_CONFLICT`, naming the fix. Only the platform's registration writes - * that record; a rollback restores a package's or the environment's item. + * [#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. */ -function refusePlatformRecordRollback(type: string, name: string): never { +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.', + '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 }; err.code = 'RESOURCE_CONFLICT'; err.status = 409; throw err; } +/** + * [#37013] A row's stored body as written (`metadata`, parsed when stored as + * text), for reading a stamp off it; `undefined` for a missing row or a body + * that does not parse, which is then no platform record. + */ function storedRowBodyOf(row: Record | undefined): unknown { const stored = row?.metadata; if (typeof stored !== 'string') return stored ?? undefined; diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index aca627c8bc4..c56b60e9f7d 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -1355,7 +1355,7 @@ export class MetadataManager implements IMetadataService { // Captured before the write so the event distinguishes a first // registration from an overwrite, matching the repo-watch path's // 'added' vs 'changed' split. - const existed = this.writeRegistryEntry(type, name, data); + const existed = this.writeRegistryEntry(type, name, data, this.primedRowSlot(type, name, data, options)); this.invalidateListCache(type); // [#33003] An environment row the boot pass stamped is stored as the @@ -1828,7 +1828,10 @@ export class MetadataManager implements IMetadataService { * * 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} - * reports a loader, and makes the answer `degraded`. + * 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 + * answer `registration`, which is not their rows' binding. */ async listPackageBindings(type: string): Promise<{ items: MetadataPackageBinding[]; degraded: boolean; errors: string[] }> { const canonical = canonicalMetadataServiceType(type); @@ -1837,7 +1840,17 @@ export class MetadataManager implements IMetadataService { const rowColumns = new Map(); let degraded = listDegraded; for (const loader of this.loaders.values()) { - if (typeof loader.loadRowBindings !== 'function') 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: + // the answer is partial as a row loader that could not be read leaves + // it, so a consumer that gates on the binding treats it as unknown. + if (loader.contract.protocol === 'datasource:') { + degraded = true; + errors.push(`${loader.contract.name}: a loader of stored rows that reads no package column (no loadRowBindings): the items it holds answer their registration's binding, not their rows'`); + } + continue; + } try { for (const entry of await loader.loadRowBindings(canonical)) { if (!entry || typeof entry.name !== 'string' || entry.name === '') continue; @@ -1880,6 +1893,29 @@ export class MetadataManager implements IMetadataService { return direct !== undefined ? direct : origin !== undefined ? loader.rowPackageIdOf(origin) : undefined; } + /** + * [#37130] The slot a stored row's body the boot priming pass re-registers + * (`skipSourceLoader`, a body a loader of rows handed out) is filed under, + * for a type stored per `(package, name)`: the slot of the row's package + * column ({@link readRowColumnOf}) when the body carries a package stamp of + * its own and it names another package. That is the key the row loader keys the row by + * (`loadManySlots`, the column first), so {@link list} lists the row once + * and a read naming the column's package answers it, as on a process that + * never primed it; ⛔ never the stamp's slot, under which {@link list} listed + * the row a second time. `undefined` (the write rule's key) for every other + * write, for a row with an empty column (a legacy row the loader keys by + * its body's package, `bindReadRowPackage`), and for an unstamped body (the + * plural read stamps a row's body with its column when the body names its + * row's key, so one left unstamped is not that row's item by its name). + */ + private primedRowSlot(type: string, name: string, data: unknown, options?: MetadataRegisterOptions): string | undefined { + if (options?.skipSourceLoader !== true || !PACKAGE_SLOTTED_STORE_TYPES.has(type)) return undefined; + const column = this.readRowColumnOf(data); + const stamp = indexedItemPackageId(data); + if (typeof column !== 'string' || column === '' || stamp === undefined || stamp === column) return undefined; + return storeSlotKey(type, name, column, data); + } + /** * The cached / single-flight read behind {@link list} and * {@link listDiagnosed}. diff --git a/packages/metadata/src/package-slotted-store.ts b/packages/metadata/src/package-slotted-store.ts index 21f1791325d..1a8abbd39c5 100644 --- a/packages/metadata/src/package-slotted-store.ts +++ b/packages/metadata/src/package-slotted-store.ts @@ -881,13 +881,20 @@ export function storeRowWriteKey( * with `origin: 'platform'` stamps it. Every other write the metadata service * and the metadata protocol make strips it ({@link withoutPlatformOrigin}): * `register` without the option, `registerInMemory`, `save`, `rollback`, the - * protocol's save door and its restore doors; and a `rollback` whose row is - * the platform's own record is refused, never written. Two undo writes of the - * metadata protocol put a row back as the same operation found it, byte for - * byte (`undoLandedPromotions`, `undoBatchRowWrite`): the mark comes back only - * where the row held it. A stored row the boot pass re-registers keeps it only - * when the row held it as read. A served body carries it on its top level only - * when the stored item does (`getPublished` included), never in a snapshot. + * protocol's save door and its restore doors. A restore whose row is the + * 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 + * 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 + * comes back only where the row held it. A stored row the boot pass + * re-registers keeps it only when the row held it as read. A served body + * carries it on its top level only when the stored item does (`getPublished` + * included: the platform's own record's publish snapshot, served as the + * answer, keeps the mark it carries at its top), and never on a snapshot + * nested inside the answer. */ export const PLATFORM_PROVENANCE = 'platform'; diff --git a/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts b/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts index 69094dd00ac..2d2c88224ab 100644 --- a/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts +++ b/packages/qa/dogfood/test/history-diff-two-holders-33308.dogfood.test.ts @@ -26,9 +26,9 @@ // package (M1): the environment's versions are its sole slot's; // - `?package=` naming a package that neither holds nor ships the name is // refused `409` naming the holders, in the protocol's order with their -// `kind` at the wire; the environment's slot addressed through a package -// (the read falls back to the package-less row) compares that row's -// versions alone, its own active row the `to` side; +// `kind` at the wire, [#37130] the package-less row beside a package's +// included: a read naming it falls back to that row, and it never +// addresses it; // - `?package=` on a type not stored per package is refused 400, never // accepted and dropped. @@ -167,18 +167,19 @@ describe('the /meta diff door of a flow name two packages hold (ADR-0150 D3/D4, expect(res.json.changed).toBeUndefined(); }); - it('the environment\'s slot addressed through a package: the package-less row\'s versions alone, its own active row the to side', async () => { + it('[#37130] beside the environment\'s own row, a package that neither holds nor ships the name is refused 409 at the history and diff doors, never addressed at that row', async () => { const bare = await call('GET', `/meta/flow/${ENV_BESIDE}/diff`); expect(bare.status, JSON.stringify(bare.json)).toBe(409); // The bound package first, then the environment's own row. expect(holdersOf(bare.json)).toEqual([{ kind: 'package', packageId: ALPHA_PAIR }, { kind: 'environment' }]); - // A read naming beta's pair (no row of the name, nothing shipped) falls back to the package-less row. - const env = await ownVersions(ENV_BESIDE, BETA_PAIR); - expect(env).toHaveLength(2); - const res = await call('GET', `/meta/flow/${ENV_BESIDE}/diff?package=${BETA_PAIR}`); - expect(res.status, JSON.stringify(res.json)).toBe(200); - expect([res.json.fromVersion, res.json.toVersion]).toEqual(env); - expect(diffLabel(res.json)).toEqual({ path: 'label', from: 'env beside r1', to: 'env beside r2' }); + // A read naming beta's pair (no row of the name, nothing shipped) falls back to the package-less row; + // the history family refuses it instead of addressing that row (BASE: the environment's versions, 200). + for (const door of ['history', 'diff']) { + const res = await call('GET', `/meta/flow/${ENV_BESIDE}/${door}?package=${BETA_PAIR}`); + expect(res.status, `${door}: ${JSON.stringify(res.json)}`).toBe(409); + expect(codeOf(res.json)).toBe('RESOURCE_CONFLICT'); + expect(holdersOf(res.json)).toEqual([{ kind: 'package', packageId: ALPHA_PAIR }, { kind: 'environment' }]); + } // Alpha's own slot beside it: its one version, no earlier one of its own. const [alphaOnly] = await ownVersions(ENV_BESIDE, ALPHA_PAIR); const alpha = await call('GET', `/meta/flow/${ENV_BESIDE}/diff?package=${ALPHA_PAIR}`);