From 899b5d3318c2b110a1c8037f2ca0e9991ca373a7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:23:31 +0000 Subject: [PATCH 1/9] test(metadata): pin one answer per rollback door for an addressed unattributed or environment version, and history-row attribution over the body stamp (red) Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .../metadata/src/metadata-history.test.ts | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/packages/metadata/src/metadata-history.test.ts b/packages/metadata/src/metadata-history.test.ts index 6a26dd58675..b8d37697826 100644 --- a/packages/metadata/src/metadata-history.test.ts +++ b/packages/metadata/src/metadata-history.test.ts @@ -440,6 +440,86 @@ describe('history and rollback of a type stored per package (#32351)', () => { expect((await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, 'env1']]); }); + // [#32717] One answer per rollback door: `MetadataManager.rollback` and + // `DatabaseLoader.registerRollback`, asked the same question, answer it in + // the same words. An address names whose versions are restored; a + // version its history does not hold answers "not found" at both. + const failure = (promise: Promise) => promise.then(() => undefined, (error: any) => error); + const legacyHistory = async () => { + // The table as the release before #32351 created it: no `package_id`. + const { package_id: _added, ...before } = SysMetadataHistoryObject.fields as Record; + await driver.syncSchema('sys_metadata_history', { ...SysMetadataHistoryObject, fields: before } as never); + return (version: number, data: Record) => driver.create('sys_metadata_history', { + id: `legacy_${version}`, event_seq: version, type, name: 'x', version, operation_type: 'update', + metadata: JSON.stringify(data), checksum: `c${version}`, recorded_at: `2026-01-0${version}T00:00:00.000Z`, + source: 'database-loader', + }); + }; + + for (const [holder, suffix] of [[A, `(package ${A})`], [null, '(environment)']] as const) { + it(`one row slot (${holder ?? 'the environment'}): a rollback addressing it to a version attributed to none answers "not found" at both doors, and writes nothing`, async () => { + const legacy = await legacyHistory(); + await legacy(1, body('custom')); + await loader.save(type, 'x', holder === null ? body('env2') : body('A2', holder)); + const rows = await rowsOf(type); + expect(rows.map((row) => row.package_id ?? null)).toEqual([holder]); + for (const attempt of [ + manager.rollback(type, 'x', 1, { packageId: holder }), + loader.registerRollback(type, 'x', body('custom'), 1, undefined, undefined, { packageId: holder }), + ]) { + const error = await failure(attempt); + expect(error?.message).toBe(`Version 1 not found in history for ${type}/x ${suffix}`); + expect(error?.status).toBeUndefined(); + } + expect(await rowsOf(type)).toEqual(rows); + // CONTROL: naming no package, it lands in the one row, as before. + await loader.registerRollback(type, 'x', body('custom'), 1); + expect((await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[holder, 'custom']]); + }); + } + + it('M1: one row slot a package took over: a rollback addressing that package to the environment\'s version answers "not found" at both doors, and writes nothing', async () => { + await loader.save(type, 'x', body('env1')); + await loader.save(type, 'x', body('A2', A)); + const rows = await rowsOf(type); + expect(rows.map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, 'A2']]); + for (const attempt of [ + manager.rollback(type, 'x', 1, { packageId: A }), + loader.registerRollback(type, 'x', body('env1'), 1, undefined, undefined, { packageId: A }), + ]) { + const error = await failure(attempt); + expect(error?.message).toBe(`Version 1 not found in history for ${type}/x (package ${A})`); + expect(error?.status).toBeUndefined(); + } + expect(await rowsOf(type)).toEqual(rows); + }); + + it('a version attributed to none is attributed by its history row, never by the restored body\'s package stamp', async () => { + const legacy = await legacyHistory(); + await legacy(1, body('custom')); + await loader.save(type, 'x', body('A2', A)); + // One row slot: the stamp names B, the history row nobody; naming no + // package it lands in the one row, as the unstamped body does. + await loader.registerRollback(type, 'x', body('custom', B), 1); + expect((await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, 'custom']]); + // Two row slots: refused naming both holders at both doors, whatever + // package the restored body is stamped with — ⛔ never landed in B's row. + await loader.save(type, 'x', body('B4', B)); + const rows = await rowsOf(type); + const both = { + code: 'RESOURCE_CONFLICT', + status: 409, + reason: 'ambiguous-in-environment', + callerPackageId: null, + candidates: [{ kind: 'package', packageId: A }, { kind: 'package', packageId: B }], + }; + for (const packageId of [A, B]) { + expect(await refusal(manager.rollback(type, 'x', 1, { packageId }))).toEqual(both); + expect(await refusal(loader.registerRollback(type, 'x', body('custom', B), 1, undefined, undefined, { packageId }))).toEqual(both); + } + expect(await rowsOf(type)).toEqual(rows); + }); + it('an environment version is not written into a package\'s row', async () => { await twoHolders(); await loader.save(type, 'x', body('env1')); From 701914579a57092a0764e0df4b60e4e4065b62b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:28:20 +0000 Subject: [PATCH 2/9] fix(metadata)!: an addressed loader rollback to a version its address's history does not hold answers "not found", as the manager's; an existing history row, not the body stamp, owns a version Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .../metadata/src/loaders/database-loader.ts | 89 +++++++++++++------ 1 file changed, 64 insertions(+), 25 deletions(-) diff --git a/packages/metadata/src/loaders/database-loader.ts b/packages/metadata/src/loaders/database-loader.ts index 07d227dd63e..810b209da8c 100644 --- a/packages/metadata/src/loaders/database-loader.ts +++ b/packages/metadata/src/loaders/database-loader.ts @@ -251,9 +251,10 @@ export interface MetadataHistoryAddress { /** * The package whose versions are read, or whose row a rollback writes. * `null` addresses the environment: the name's package-less row and the - * versions recorded of it (never a version attributed to none, F1). `''` and the `sys_metadata` sentinel - * name no package either, so they address the environment too (the store's - * own rule, `isPackageCaller`). Absent: no address. + * versions recorded of it (never a version attributed to none, F1). `''` + * and the `sys_metadata` sentinel name no package either, so they address + * the environment too (the store's own rule, `isPackageCaller`). Absent: no + * address. */ packageId?: string | null; } @@ -293,9 +294,11 @@ function historySnapshotPackage(slot: { packageId?: string } | undefined): strin * `package_id` column, else, for a row written before it, the package its * stored body names — {@link storedRowPackageId}), `null` for the * environment (the column holds {@link ENVIRONMENT_HISTORY_MARK}), or - * `undefined` when it is attributed to none. An addressed read never answers - * an unattributed version, and a rollback lands one only on a name a single - * row slot holds. [#32905] `SysMetadataRepository` (the `/meta` history and + * `undefined` when it is attributed to none. An addressed read or rollback + * never answers an unattributed version (#32717: "not found" while one row + * slot holds the name, refused naming every holder while several do), and a + * rollback naming no package lands one only on a name a single row slot + * holds. [#32905] `SysMetadataRepository` (the `/meta` history and * rollback doors) attributes the rows it reads by this same rule. */ export function historyRowAttribution(row: Record): string | null | undefined { @@ -303,6 +306,18 @@ export function historyRowAttribution(row: Record): string | nu return storedRowPackageId(row); } +/** + * [#32717] The "not found" of an addressed rollback to a version its address's + * history does not hold: the sentence `MetadataManager.rollback` answers after + * its addressed read (`historyAddressSuffix` there), so the two doors answer + * one request in the same words. + */ +function historyVersionNotFound(type: string, name: string, version: number, packageId: string | null): Error { + return new Error( + `Version ${version} not found in history for ${type}/${name} ${packageId === null ? '(environment)' : `(package ${packageId})`}`, + ); +} + /** [#32351] A version's owner in a sentence: `package "p"`, or the environment. */ function ownerPhrase(owner: string | null): string { return owner === null ? 'the environment' : `package "${owner}"`; @@ -1742,7 +1757,9 @@ export class DatabaseLoader implements MetadataLoader { * when it holds no row of the name, or, addressing none, the name's one row * slot (several are refused naming every holder, before any write). The * version restored must be that slot's package's: another package's version - * is refused, ⛔ never written into the remaining holder's row (S8a). Every + * is refused, ⛔ never written into the remaining holder's row (S8a). An + * addressed rollback to a version its address's history does not hold + * answers "not found", as `MetadataManager.rollback` does (#32717). Every * other type restores its name's row, as before. */ async registerRollback( @@ -1873,10 +1890,23 @@ export class DatabaseLoader implements MetadataLoader { * row, as before (M1): a package took over the package-less row, or * saved after it was removed; * - a version attributed to none (F1: a row written before the column, or - * by `SysMetadataRepository`) lands in the slot picked only when the - * name has one row slot, as before; with several it is refused naming - * every holder (`refuseSeveralSlots`), addressed or not, since nothing - * says whose it is. + * by `SysMetadataRepository` before #32905) lands in the slot picked only + * when the name has one row slot and the rollback names no package, as + * before; with several it is refused naming every holder + * (`refuseSeveralSlots`), addressed or not, since nothing says whose it + * is; + * - [#32717] addressed, a version the address's history does not hold — + * one attributed to none, or the environment's while a package's row is + * the name's one slot (M1) — answers "not found" + * ({@link historyVersionNotFound}), the words `MetadataManager.rollback` + * answers after its addressed read, before any write. The address names + * whose version is restored; attribution is what says so, and nothing + * is guessed (ADR-0150: one holder or a refusal); + * - the restored body's own package stamp stands in for the version's + * owner only when the version has no history row at all (history not + * tracked, or no row of that version): a history row that exists, even + * one attributed to none, is the version's owner, ⛔ never the stamp of + * the body a caller hands in (#32717). */ private async rollbackSlot( type: string, @@ -1896,14 +1926,24 @@ export class DatabaseLoader implements MetadataLoader { key = bySlot.keys().next().value as string; } const slotPackage = slotPackageOf(key); - const recorded = await this.historyVersionAttribution(type, name, targetVersion); - const versionOwner = recorded !== undefined ? recorded : storedItemPackageId(restoredData); - if (versionOwner === undefined || (versionOwner === null && bySlot.size === 1)) { - // Attributed to none, or (M1) the environment's own version of a name - // one row slot holds — a package took over the package-less row, or it - // was removed and a package saved since: it lands in that one row, as - // before. With several row slots it is refused naming every holder. + const recorded = await this.historyVersionRow(type, name, targetVersion); + // [#32717] Whose version it is: its history row's attribution whenever + // the row exists; the restored body's stamp only for a version with no row. + const versionOwner = recorded !== undefined ? historyRowAttribution(recorded) : storedItemPackageId(restoredData); + if (versionOwner === undefined) { + // Attributed to none (or, with no history row, a body naming no + // package): with several row slots refused naming every holder. With + // one, a rollback naming no package lands it in that row, as before; + // an addressed one does not read it, as the manager's addressed read + // does not. refuseSeveralSlots(bySlot, type, name); + if (packageId !== undefined && recorded !== undefined) throw historyVersionNotFound(type, name, targetVersion, packageId); + } else if (versionOwner === null && bySlot.size === 1 && slotPackage !== undefined) { + // M1: the environment's own version of a name a package's row is the + // one slot of (a package took over the package-less row, or saved + // after it was removed): a rollback naming no package lands it in that + // row, as before; one naming the package does not read it. + if (packageId !== undefined) throw historyVersionNotFound(type, name, targetVersion, packageId); } else if (versionOwner !== (slotPackage ?? null)) { if (bySlot.has(storeRowKey(name, versionOwner))) { throw new Error( @@ -1917,16 +1957,15 @@ export class DatabaseLoader implements MetadataLoader { } /** - * [#32351] Whose version the history row of `(type, name, version)` records - * ({@link historyRowAttribution}): a package, `null` for the environment; - * `undefined` when history is not tracked, the row is absent or it is - * attributed to none. + * [#32351, #32717] The history row of `(type, name, version)`, whose + * attribution ({@link historyRowAttribution}) says whose version it is; + * `undefined` when history is not tracked or the row is absent — never + * when the row exists and is attributed to none. */ - private async historyVersionAttribution(type: string, name: string, version: number): Promise { + private async historyVersionRow(type: string, name: string, version: number): Promise | undefined> { if (!this.trackHistory) return undefined; await this.ensureHistorySchema(); - const row = await this._findOne(this.historyTableName, { where: { type, name, version } }); - return row ? historyRowAttribution(row) : undefined; + return (await this._findOne(this.historyTableName, { where: { type, name, version } })) ?? undefined; } /** From 64bdbc71c120dbdf1b45087c0eac08c55f1cc2a2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:33:52 +0000 Subject: [PATCH 3/9] test(metadata): split the stamp pin into its two-slot refusal and its one-slot landing Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .../metadata/src/metadata-history.test.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/packages/metadata/src/metadata-history.test.ts b/packages/metadata/src/metadata-history.test.ts index b8d37697826..ea227bee33c 100644 --- a/packages/metadata/src/metadata-history.test.ts +++ b/packages/metadata/src/metadata-history.test.ts @@ -494,17 +494,11 @@ describe('history and rollback of a type stored per package (#32351)', () => { expect(await rowsOf(type)).toEqual(rows); }); - it('a version attributed to none is attributed by its history row, never by the restored body\'s package stamp', async () => { + it('two row slots: a version attributed to none is refused naming both holders at both doors, whatever package the restored body is stamped with — never landed in that package\'s row', async () => { const legacy = await legacyHistory(); await legacy(1, body('custom')); await loader.save(type, 'x', body('A2', A)); - // One row slot: the stamp names B, the history row nobody; naming no - // package it lands in the one row, as the unstamped body does. - await loader.registerRollback(type, 'x', body('custom', B), 1); - expect((await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, 'custom']]); - // Two row slots: refused naming both holders at both doors, whatever - // package the restored body is stamped with — ⛔ never landed in B's row. - await loader.save(type, 'x', body('B4', B)); + await loader.save(type, 'x', body('B3', B)); const rows = await rowsOf(type); const both = { code: 'RESOURCE_CONFLICT', @@ -520,6 +514,15 @@ describe('history and rollback of a type stored per package (#32351)', () => { expect(await rowsOf(type)).toEqual(rows); }); + it('one row slot: a version attributed to none, restored naming no package with a body stamped for another package, lands in the one row as the unstamped body does', async () => { + const legacy = await legacyHistory(); + await legacy(1, body('custom')); + await loader.save(type, 'x', body('A2', A)); + // The history row exists and names nobody; the stamp is the caller's, not the version's owner. + await loader.registerRollback(type, 'x', body('custom', B), 1); + expect((await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, 'custom']]); + }); + it('an environment version is not written into a package\'s row', async () => { await twoHolders(); await loader.save(type, 'x', body('env1')); From f333dfc360cd5c15d7bae07b38b3149b3d670a6d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:37:58 +0000 Subject: [PATCH 4/9] docs(metadata-core, metadata): a NULL history package_id is not attributed, never the environment; the manager and loader rollback docs name the one answer Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .../objects/sys-metadata-history.object.ts | 25 +++++++++++-------- .../metadata/src/loaders/database-loader.ts | 3 ++- packages/metadata/src/metadata-manager.ts | 4 ++- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/packages/metadata-core/src/objects/sys-metadata-history.object.ts b/packages/metadata-core/src/objects/sys-metadata-history.object.ts index 7efd6378238..c9aa0abdceb 100644 --- a/packages/metadata-core/src/objects/sys-metadata-history.object.ts +++ b/packages/metadata-core/src/objects/sys-metadata-history.object.ts @@ -30,9 +30,12 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; * continues incrementing instead of restarting at 1. * * • `package_id` names whose row a snapshot of a type stored per - * `(package, name)` was taken of (ADR-0150 D3/D4); such a type's - * `version` is numbered per name across its packages' rows, so the - * unique `(type, name, version)` holds. NULL on every other row. + * `(package, name)` was taken of (ADR-0150 D3/D4): a package, or the + * `sys_metadata` mark for the environment's package-less row. Such a + * type's `version` is numbered per name across its rows, so the unique + * `(type, name, version)` holds. NULL means "not attributed", never the + * environment: every other type's row, and such a type's row written + * before a writer recorded the column. * * • `metadata` / `checksum` are nullable — DELETE rows have no body or * hash. Readers must tolerate null on both columns. @@ -102,13 +105,15 @@ export const SysMetadataHistoryObject = ObjectSchema.create({ * type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`, * `@objectstack/metadata`): its versions are numbered per name across the * packages' rows, so this column, not the version, says whose version it is. - * NULL for every other type, and for a row written before the column - * existed (its package is then the one its stored body names, as for a - * `sys_metadata` row); a package-less row's snapshot carries the - * `sys_metadata` mark. [#32905] `SysMetadataRepository` (the `/meta` - * doors) records it as `DatabaseLoader` does, so the `/meta` history and - * rollback doors read whose version a row is; the rows it wrote before - * that carry NULL. Nullable: adding it rewrites no row. + * A package-less row's snapshot carries the `sys_metadata` mark. NULL + * means "not attributed", never the environment: every other type's row, + * and such a type's row written before the column existed, or before + * [#32905] `SysMetadataRepository` (the `/meta` doors) recorded it as + * `DatabaseLoader` does. Such a row is read as the package its stored + * body names (its `_packageId` stamp), if it names one, and else as + * attributed to none — in no package's history and not the environment's + * (`historyRowAttribution`, `@objectstack/metadata`). Nullable: adding it + * rewrites no row. */ package_id: Field.text({ label: 'Package ID', diff --git a/packages/metadata/src/loaders/database-loader.ts b/packages/metadata/src/loaders/database-loader.ts index 810b209da8c..0c9f0931029 100644 --- a/packages/metadata/src/loaders/database-loader.ts +++ b/packages/metadata/src/loaders/database-loader.ts @@ -1974,7 +1974,8 @@ export class DatabaseLoader implements MetadataLoader { * history row is attributed to none. An addressed read leaves such a * version out, so `MetadataManager.rollback` asks here before answering its * miss "not found": the version exists, and nothing says whose it is. A - * name one row slot holds, an absent row and every other type pass. + * name one row slot holds, an absent row and every other type pass: the + * miss is "not found", as {@link registerRollback} answers it (#32717). */ async refuseUnattributedVersion(type: string, name: string, version: number): Promise { if (!PACKAGE_SLOTTED_STORE_TYPES.has(type) || !this.trackHistory) return; diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index 8d2c68bf556..bccaf33b717 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -4599,7 +4599,9 @@ export class MetadataManager implements IMetadataService { * * [ADR-0150 D3/D4, #32351] For a type stored per `(package, name)`, * `options.packageId` names whose row is restored, and the version must be - * that package's ("not found" otherwise). Naming none, the name's one row is + * that package's ("not found" otherwise — [#32717] one attributed to none, + * or the environment's, included, in the words `DatabaseLoader.registerRollback` + * answers when called directly). Naming none, the name's one row is * restored; several are refused 409 naming every holder, and so is a version * of a package that holds no row of the name (`not-held-by-qualifier`) — * ⛔ never written into another package's row. From 868a8e534606ceedcd765379b0fe758ee4c4574d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 21:45:39 +0000 Subject: [PATCH 5/9] chore(changeset): declare the rollback door answers that move (#32717) Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .changeset/32717-rollback-door-one-answer.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 .changeset/32717-rollback-door-one-answer.md diff --git a/.changeset/32717-rollback-door-one-answer.md b/.changeset/32717-rollback-door-one-answer.md new file mode 100644 index 00000000000..fa5787da17d --- /dev/null +++ b/.changeset/32717-rollback-door-one-answer.md @@ -0,0 +1,18 @@ +--- +'@objectstack/metadata': patch +--- + +fix(metadata)!: `DatabaseLoader.registerRollback` answers an addressed rollback to a version its address's history does not hold "not found", as `MetadataManager.rollback` does, and a version's existing history row, never the restored body's package stamp, says whose version it is (#32717) + +Clause-②: yes (narrowing) — for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`; at this release `api`, `agent`, `skill`, `action`, `email_template`, `permission`, `flow`, `picklist`, `mapping`, `dataset`, `webhook`, `tool`), called directly on `DatabaseLoader.registerRollback`. Narrowed: an addressed rollback (`{ packageId }`, a package or `null` for the environment) to a version attributed to no package, on a name one row slot holds, and one addressing a package to the environment's own version while that package's row is the name's one slot (M1), wrote the version into that row and now answer `Version N not found in history for TYPE/NAME (package PKG)` (or `(environment)`), writing nothing; an addressed rollback to a version attributed to no package, on a name two row slots hold, with a restored body stamped for one of them (`_packageId`), wrote it into that package's row (addressing it) or answered that the version was that package's (addressing the other) and now answers `409 RESOURCE_CONFLICT` (`ambiguous-in-environment`, naming every holder). Widened: a rollback naming no package to a version attributed to no package, on a name one row slot holds, with a restored body stamped for a package that holds no row of the name, answered `409 RESOURCE_CONFLICT` (`not-held-by-qualifier`) and now lands in the one row, as the same version restored with an unstamped body does. `MetadataManager.rollback` answers every one of these as before. +Metadata-protocol: none + + + +**BREAKING** for a caller of `DatabaseLoader.registerRollback` that addresses a package (or the environment) and restores a version that address's history does not list. No first-party caller reaches it: `MetadataManager.rollback`, its one caller in the workspace, reads the addressed history first and already answered these requests "not found" or `409`, and the REST `/meta/:type/:name/rollback` door goes through the protocol's own repository. The fix: roll back naming no package on a name one row slot holds (`registerRollback(type, name, body, version)`), which restores such a version into that row as before, or address the package the version is attributed to (its `getHistory(type, name, { packageId })` lists it). + +ADR-0150 D3/D4: an address names whose versions a rollback restores, and only a version's history row says whose it is. The two rollback doors of the metadata service now answer one request in the same words: + +- **A version attributed to no package** (a history row written before `sys_metadata_history.package_id`, or one `SysMetadataRepository` wrote before it recorded the column), addressed: FROM written into the addressed row at `registerRollback` and "not found" at `MetadataManager.rollback`, TO "not found" at both while one row slot holds the name, and `409` naming every holder at both while several do, as before. Naming no package it lands in the name's one row at both doors, as before. +- **The environment's own version, addressing the package whose row is the name's one slot** (M1: a package took over the package-less row, or saved after it was removed): FROM written into that row at `registerRollback` and "not found" at `MetadataManager.rollback`, TO "not found" at both. Naming no package it lands in that row at both doors, as before. +- **Whose version it is.** FROM the version's history row's attribution, else the restored body's package stamp when the row was attributed to none, TO the history row's attribution whenever the row exists; the body's stamp stands in only for a version with no history row at all (history not tracked, or no row of that version). A version attributed to no package is therefore never attributed by the body a caller hands in: on a name two row slots hold it is refused `409` naming both, ⛔ never written into the row of the package the body names. From 3300a61212c6dbbb5c92499df5ab1806126c35e3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:49:54 +0000 Subject: [PATCH 6/9] chore(changeset): metadata-core ships the corrected package_id doc comment in its dist Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .changeset/32717-rollback-door-one-answer.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.changeset/32717-rollback-door-one-answer.md b/.changeset/32717-rollback-door-one-answer.md index fa5787da17d..95992c32e1a 100644 --- a/.changeset/32717-rollback-door-one-answer.md +++ b/.changeset/32717-rollback-door-one-answer.md @@ -1,5 +1,6 @@ --- '@objectstack/metadata': patch +'@objectstack/metadata-core': patch --- fix(metadata)!: `DatabaseLoader.registerRollback` answers an addressed rollback to a version its address's history does not hold "not found", as `MetadataManager.rollback` does, and a version's existing history row, never the restored body's package stamp, says whose version it is (#32717) @@ -16,3 +17,5 @@ ADR-0150 D3/D4: an address names whose versions a rollback restores, and only a - **A version attributed to no package** (a history row written before `sys_metadata_history.package_id`, or one `SysMetadataRepository` wrote before it recorded the column), addressed: FROM written into the addressed row at `registerRollback` and "not found" at `MetadataManager.rollback`, TO "not found" at both while one row slot holds the name, and `409` naming every holder at both while several do, as before. Naming no package it lands in the name's one row at both doors, as before. - **The environment's own version, addressing the package whose row is the name's one slot** (M1: a package took over the package-less row, or saved after it was removed): FROM written into that row at `registerRollback` and "not found" at `MetadataManager.rollback`, TO "not found" at both. Naming no package it lands in that row at both doors, as before. - **Whose version it is.** FROM the version's history row's attribution, else the restored body's package stamp when the row was attributed to none, TO the history row's attribution whenever the row exists; the body's stamp stands in only for a version with no history row at all (history not tracked, or no row of that version). A version attributed to no package is therefore never attributed by the body a caller hands in: on a name two row slots hold it is refused `409` naming both, ⛔ never written into the row of the package the body names. + +`@objectstack/metadata-core` ships a documentation change only: the `sys_metadata_history.package_id` doc comment (in its published `dist`) now says NULL means "not attributed", never the environment, and that a row written before the column is read as the package its stored body names, else as attributed to none. No field, type or export changes. From cfd4f28b160f7535bf717dce548eaba232456a66 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:43:37 +0000 Subject: [PATCH 7/9] =?UTF-8?q?test(metadata):=20pin=20ruling=20B=20at=20b?= =?UTF-8?q?oth=20rollback=20doors=20=E2=80=94=20sole-slot=20versions=20lan?= =?UTF-8?q?d=20addressed=20or=20not,=20and=20the=20written=20body=20is=20s?= =?UTF-8?q?tamped=20for=20its=20slot=20(red)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .../metadata/src/metadata-history.test.ts | 150 +++++++++++++----- 1 file changed, 112 insertions(+), 38 deletions(-) diff --git a/packages/metadata/src/metadata-history.test.ts b/packages/metadata/src/metadata-history.test.ts index ea227bee33c..350f89a2322 100644 --- a/packages/metadata/src/metadata-history.test.ts +++ b/packages/metadata/src/metadata-history.test.ts @@ -440,11 +440,17 @@ describe('history and rollback of a type stored per package (#32351)', () => { expect((await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, 'env1']]); }); - // [#32717] One answer per rollback door: `MetadataManager.rollback` and - // `DatabaseLoader.registerRollback`, asked the same question, answer it in - // the same words. An address names whose versions are restored; a - // version its history does not hold answers "not found" at both. - const failure = (promise: Promise) => promise.then(() => undefined, (error: any) => error); + // [#32717, seat ruling 6885958183 (amended B)] One answer per rollback + // door: `MetadataManager.rollback`, `DatabaseLoader.registerRollback` and + // `/meta` (`SysMetadataRepository.restoreVersion`'s `isVersionOf`). On a + // name one row slot holds, a version attributed to none and the + // environment's own version are that slot's (ADR-0150 D4: a package-less + // row at a held name is its one holder's customization), so they land, + // addressed or not, and an addressed history read lists exactly what an + // addressed rollback restores. On a name several row slots hold such a + // version is refused 409 naming every holder. A history row that exists + // says whose version it is, and the body the slot stores is stamped for + // that slot's owner, never for the package the restored body names. const legacyHistory = async () => { // The table as the release before #32351 created it: no `package_id`. const { package_id: _added, ...before } = SysMetadataHistoryObject.fields as Record; @@ -455,46 +461,54 @@ describe('history and rollback of a type stored per package (#32351)', () => { source: 'database-loader', }); }; + const slotsOf = async () => (await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)]); + const storedStampOf = (row: Record | undefined) => JSON.parse(String(row?.metadata))._packageId; - for (const [holder, suffix] of [[A, `(package ${A})`], [null, '(environment)']] as const) { - it(`one row slot (${holder ?? 'the environment'}): a rollback addressing it to a version attributed to none answers "not found" at both doors, and writes nothing`, async () => { + for (const holder of [A, null]) { + const save = (label: string) => loader.save(type, 'x', holder === null ? body(label) : body(label, holder)); + it(`one row slot (${holder ?? 'the environment'}): a version attributed to none is in the slot's addressed history and rolls back into the slot at both doors, addressed or not`, async () => { const legacy = await legacyHistory(); await legacy(1, body('custom')); - await loader.save(type, 'x', holder === null ? body('env2') : body('A2', holder)); - const rows = await rowsOf(type); - expect(rows.map((row) => row.package_id ?? null)).toEqual([holder]); - for (const attempt of [ - manager.rollback(type, 'x', 1, { packageId: holder }), - loader.registerRollback(type, 'x', body('custom'), 1, undefined, undefined, { packageId: holder }), - ]) { - const error = await failure(attempt); - expect(error?.message).toBe(`Version 1 not found in history for ${type}/x ${suffix}`); - expect(error?.status).toBeUndefined(); - } - expect(await rowsOf(type)).toEqual(rows); - // CONTROL: naming no package, it lands in the one row, as before. + await save('own2'); + expect((await rowsOf(type)).map((row) => row.package_id ?? null)).toEqual([holder]); + // The addressed history lists it, as the bare one does. + expect(await versions(type, { packageId: holder })).toEqual([2, 1]); + expect(await versions(type)).toEqual([2, 1]); + expect((await loader.getHistoryRecord(type, 'x', 1, { packageId: holder }))?.metadata).toEqual(body('custom')); + expect((await manager.diff(type, 'x', 1, 2, { packageId: holder })).identical).toBe(false); + // The manager's door, addressed. + await manager.rollback(type, 'x', 1, { packageId: holder }); + expect(await slotsOf()).toEqual([[holder, 'custom']]); + // The loader's door, addressed. + await save('own4'); + await loader.registerRollback(type, 'x', body('custom'), 1, undefined, undefined, { packageId: holder }); + expect(await slotsOf()).toEqual([[holder, 'custom']]); + // CONTROL: naming no package, both doors land it in the one row, as before. + await save('own6'); + await manager.rollback(type, 'x', 1); + expect(await slotsOf()).toEqual([[holder, 'custom']]); + await save('own8'); await loader.registerRollback(type, 'x', body('custom'), 1); - expect((await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[holder, 'custom']]); + expect(await slotsOf()).toEqual([[holder, 'custom']]); }); } - it('M1: one row slot a package took over: a rollback addressing that package to the environment\'s version answers "not found" at both doors, and writes nothing', async () => { + it('M1: one row slot a package took over: the environment\'s version is in that package\'s addressed history and rolls back addressing it at both doors', async () => { await loader.save(type, 'x', body('env1')); await loader.save(type, 'x', body('A2', A)); - const rows = await rowsOf(type); - expect(rows.map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, 'A2']]); - for (const attempt of [ - manager.rollback(type, 'x', 1, { packageId: A }), - loader.registerRollback(type, 'x', body('env1'), 1, undefined, undefined, { packageId: A }), - ]) { - const error = await failure(attempt); - expect(error?.message).toBe(`Version 1 not found in history for ${type}/x (package ${A})`); - expect(error?.status).toBeUndefined(); - } - expect(await rowsOf(type)).toEqual(rows); + expect(await slotsOf()).toEqual([[A, 'A2']]); + expect(await versions(type, { packageId: A })).toEqual([2, 1]); + expect((await loader.getHistoryRecord(type, 'x', 1, { packageId: A }))?.metadata).toEqual(body('env1')); + await manager.rollback(type, 'x', 1, { packageId: A }); + expect(await slotsOf()).toEqual([[A, 'env1']]); + await loader.save(type, 'x', body('A4', A)); + await loader.registerRollback(type, 'x', body('env1'), 1, undefined, undefined, { packageId: A }); + expect(await slotsOf()).toEqual([[A, 'env1']]); + // The environment holds no row of the name: addressing it is refused, as before. + expect((await refusal(manager.rollback(type, 'x', 1, { packageId: null })))?.reason).toBe('not-held-by-qualifier'); }); - it('two row slots: a version attributed to none is refused naming both holders at both doors, whatever package the restored body is stamped with — never landed in that package\'s row', async () => { + it('two row slots: a version attributed to none is in no addressed history and is refused naming both holders at both doors, whatever package the restored body is stamped with — never landed in that package\'s row', async () => { const legacy = await legacyHistory(); await legacy(1, body('custom')); await loader.save(type, 'x', body('A2', A)); @@ -508,19 +522,79 @@ describe('history and rollback of a type stored per package (#32351)', () => { candidates: [{ kind: 'package', packageId: A }, { kind: 'package', packageId: B }], }; for (const packageId of [A, B]) { + expect(await loader.getHistoryRecord(type, 'x', 1, { packageId })).toBeNull(); expect(await refusal(manager.rollback(type, 'x', 1, { packageId }))).toEqual(both); expect(await refusal(loader.registerRollback(type, 'x', body('custom', B), 1, undefined, undefined, { packageId }))).toEqual(both); } expect(await rowsOf(type)).toEqual(rows); }); - it('one row slot: a version attributed to none, restored naming no package with a body stamped for another package, lands in the one row as the unstamped body does', async () => { + it('one row slot, the environment\'s: a version restored with a body stamped for a package that holds no row is written unstamped, and the row stays the environment\'s', async () => { const legacy = await legacyHistory(); await legacy(1, body('custom')); + await loader.save(type, 'x', body('env2')); + await loader.save(type, 'x', body('env3')); + // An unattributed version (1) and the environment's own (2), restored naming no package or addressing the environment. + for (const version of [1, 2]) { + for (const options of [undefined, { packageId: null }]) { + await loader.registerRollback(type, 'x', body(`v${version}`, B), version, undefined, undefined, options); + const rows = await rowsOf(type); + expect(rows.map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[null, `v${version}`]]); + expect(storedStampOf(rows[0])).toBeUndefined(); + expect(((await loader.load(type, 'x')).data as Record | undefined)?._packageId).toBeUndefined(); + // Still the environment's slot: B holds no row of the name, and the environment's address reads its newest version. + expect(await refusal(loader.registerRollback(type, 'x', body('env3'), 3, undefined, undefined, { packageId: B }))).toMatchObject({ + status: 409, reason: 'not-held-by-qualifier', callerPackageId: B, candidates: [{ kind: 'environment' }], + }); + expect((await versions(type, { packageId: null }))[0]).toBe(Number(rows[0]!.version)); + } + } + }); + + it('one row slot, A\'s: a version restored with a body stamped for B is written stamped A, and served as A\'s', async () => { + const legacy = await legacyHistory(); + await legacy(1, body('custom')); + await loader.save(type, 'x', body('A2', A)); + // An unattributed version (1) and A's own (2), restored naming no package or addressing A. + for (const version of [1, 2]) { + for (const options of [undefined, { packageId: A }]) { + await loader.registerRollback(type, 'x', body(`v${version}`, B), version, undefined, undefined, options); + const rows = await rowsOf(type); + expect(rows.map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, `v${version}`]]); + expect(storedStampOf(rows[0])).toBe(A); + expect(((await loader.load(type, 'x')).data as Record | undefined)?._packageId).toBe(A); + // Its history snapshot is the body written. + const snapshot = await loader.getHistoryRecord(type, 'x', Number(rows[0]!.version), { packageId: A }); + expect((snapshot?.metadata as Record | undefined)?._packageId).toBe(A); + } + } + }); + + it('N1: two row slots: A\'s version restored into A\'s row with a body stamped for B is written stamped A, and B\'s row is byte-identical', async () => { + await twoHolders(); + const before = await rowOf(type, B); + await loader.registerRollback(type, 'x', body('A1', B), 1, undefined, undefined, { packageId: A }); + expect(labelOf(await rowOf(type, A))).toBe('A1'); + expect(storedStampOf(await rowOf(type, A))).toBe(A); + expect(await rowOf(type, B)).toEqual(before); + }); + + it('N1 at the manager\'s door: a recorded A version whose snapshot is stamped for B lands in A\'s row stamped A, and the registry files it as A\'s', async () => { + await driver.syncSchema('sys_metadata_history', SysMetadataHistoryObject as never); + // A snapshot recorded of A's row with B's stamp (a direct rollback before #32717 wrote one). + await driver.create('sys_metadata_history', { + id: 'residue_1', event_seq: 1, type, name: 'x', version: 1, operation_type: 'revert', package_id: A, + metadata: JSON.stringify(body('A1', B)), checksum: 'c1', recorded_at: '2026-01-01T00:00:00.000Z', source: 'database-loader', + }); await loader.save(type, 'x', body('A2', A)); - // The history row exists and names nobody; the stamp is the caller's, not the version's owner. - await loader.registerRollback(type, 'x', body('custom', B), 1); - expect((await rowsOf(type)).map((row) => [row.package_id ?? null, labelOf(row)])).toEqual([[A, 'custom']]); + for (const options of [undefined, { packageId: A }]) { + await loader.save(type, 'x', body('A9', A)); + expect(await manager.rollback(type, 'x', 1, options)).toEqual(body('A1', A)); + expect(await slotsOf()).toEqual([[A, 'A1']]); + expect(storedStampOf(await rowOf(type, A))).toBe(A); + expect(await manager.get(type, 'x', A)).toEqual(body('A1', A)); + expect(await manager.get(type, 'x', B)).toBeUndefined(); + } }); it('an environment version is not written into a package\'s row', async () => { From beeac9ccb8f65f570829d27488f83d37a18cd654 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:48:28 +0000 Subject: [PATCH 8/9] fix(metadata): a sole row slot's addressed history and rollback answer its unattributed and environment versions, and a rollback writes its body stamped for the slot (seat ruling 6885958183) Drops the two one-holder "not found" narrowings in DatabaseLoader.registerRollback and widens the manager's addressed history (getHistory, getHistoryRecord, queryHistory, diff, rollback) to the versions a rollback addressing the name's one row slot restores. The history-row-over-body-stamp attribution stays. A restored body whose package stamp names another package than the slot it is written into is re-stamped for that slot (a package's) or stripped (the environment's), so the environment's row never becomes another package's and a package's row is never served as another's. Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .../objects/sys-metadata-history.object.ts | 7 +- .../metadata/src/loaders/database-loader.ts | 155 +++++++++++------- .../metadata/src/metadata-history.test.ts | 4 +- packages/metadata/src/metadata-manager.ts | 38 +++-- .../metadata/src/package-slotted-store.ts | 33 +++- 5 files changed, 160 insertions(+), 77 deletions(-) diff --git a/packages/metadata-core/src/objects/sys-metadata-history.object.ts b/packages/metadata-core/src/objects/sys-metadata-history.object.ts index c9aa0abdceb..2faeae41f05 100644 --- a/packages/metadata-core/src/objects/sys-metadata-history.object.ts +++ b/packages/metadata-core/src/objects/sys-metadata-history.object.ts @@ -111,9 +111,10 @@ export const SysMetadataHistoryObject = ObjectSchema.create({ * [#32905] `SysMetadataRepository` (the `/meta` doors) recorded it as * `DatabaseLoader` does. Such a row is read as the package its stored * body names (its `_packageId` stamp), if it names one, and else as - * attributed to none — in no package's history and not the environment's - * (`historyRowAttribution`, `@objectstack/metadata`). Nullable: adding it - * rewrites no row. + * attributed to none (`historyRowAttribution`, `@objectstack/metadata`): + * the version of the name's one row slot, whichever package or the + * environment holds it, and of no slot while several hold the name. + * Nullable: adding it rewrites no row. */ package_id: Field.text({ label: 'Package ID', diff --git a/packages/metadata/src/loaders/database-loader.ts b/packages/metadata/src/loaders/database-loader.ts index 7dfa953e70d..912c53d2ba8 100644 --- a/packages/metadata/src/loaders/database-loader.ts +++ b/packages/metadata/src/loaders/database-loader.ts @@ -37,6 +37,7 @@ import { refuseSeveralSlots, refuseSlotNotHeld, slotPackageOf, + stampedForSlot, STORED_MEMBER_MAX_LENGTH, storedItemPackageId, storedRowMemberOf, @@ -252,9 +253,11 @@ export interface MetadataHistoryAddress { /** * The package whose versions are read, or whose row a rollback writes. * `null` addresses the environment: the name's package-less row and the - * versions recorded of it (never a version attributed to none, F1). `''` - * and the `sys_metadata` sentinel name no package either, so they address - * the environment too (the store's own rule, `isPackageCaller`). Absent: no + * versions recorded of it. A version attributed to none (F1), and on a + * package's slot the environment's own, is the addressed slot's only while + * that slot is the name's one row slot (#32717). `''` and the + * `sys_metadata` sentinel name no package either, so they address the + * environment too (the store's own rule, `isPackageCaller`). Absent: no * address. */ packageId?: string | null; @@ -295,12 +298,12 @@ function historySnapshotPackage(slot: { packageId?: string } | undefined): strin * `package_id` column, else, for a row written before it, the package its * stored body names — {@link storedRowPackageId}), `null` for the * environment (the column holds {@link ENVIRONMENT_HISTORY_MARK}), or - * `undefined` when it is attributed to none. An addressed read or rollback - * never answers an unattributed version (#32717: "not found" while one row - * slot holds the name, refused naming every holder while several do), and a - * rollback naming no package lands one only on a name a single row slot - * holds. [#32905] `SysMetadataRepository` (the `/meta` history and - * rollback doors) attributes the rows it reads by this same rule. + * `undefined` when it is attributed to none. A read or rollback, addressed or + * not, answers an unattributed version only on a name a single row slot holds + * (that slot's version, {@link isAddressedVersion}); while several do it is + * refused naming every holder. [#32905] `SysMetadataRepository` (the `/meta` + * history and rollback doors) attributes the rows it reads by this same + * rule. */ export function historyRowAttribution(row: Record): string | null | undefined { if (row.package_id === ENVIRONMENT_HISTORY_MARK) return null; @@ -308,15 +311,20 @@ export function historyRowAttribution(row: Record): string | nu } /** - * [#32717] The "not found" of an addressed rollback to a version its address's - * history does not hold: the sentence `MetadataManager.rollback` answers after - * its addressed read (`historyAddressSuffix` there), so the two doors answer - * one request in the same words. + * [#32717, seat ruling 6885958183] Whether history row `row` is a version a + * history read or a rollback addressing `packageId` (`null`: the environment) + * answers: one attributed to it ({@link historyRowAttribution}), or, when the + * address's slot is the name's one row slot (`sole`), one attributed to none + * or the environment's own (M1). Those are the versions + * `DatabaseLoader.registerRollback` lands in that slot (ADR-0150 D4: a + * package-less row at a held name is its one holder's customization), so an + * addressed read lists exactly what an addressed rollback restores — the + * `/meta` doors' rule (`isVersionOf`, `SysMetadataRepository`), on a name a + * row holds. */ -function historyVersionNotFound(type: string, name: string, version: number, packageId: string | null): Error { - return new Error( - `Version ${version} not found in history for ${type}/${name} ${packageId === null ? '(environment)' : `(package ${packageId})`}`, - ); +function isAddressedVersion(row: Record, packageId: string | null, sole: boolean): boolean { + const attributed = historyRowAttribution(row); + return attributed === packageId || (sole && (attributed === undefined || attributed === null)); } /** [#32351] A version's owner in a sentence: `package "p"`, or the environment. */ @@ -1580,8 +1588,11 @@ export class DatabaseLoader implements MetadataLoader { * * [ADR-0150 D3/D4, #32351] For a by-package type, `options.packageId` names * whose version it is (`null`: the environment's, recorded under no - * package): a version of another package answers null. With no address, a - * name more than one row slot holds is refused before the row is read + * package): a version of another package answers null. [#32717] When the + * address's slot is the name's one row slot, a version attributed to none + * and the environment's own are its versions too ({@link isAddressedVersion}), + * as a rollback addressing it restores them. With no address, a name more + * than one row slot holds is refused before the row is read * ({@link historyPackageAddress}); one holder answers as before. */ async getHistoryRecord( @@ -1605,7 +1616,8 @@ export class DatabaseLoader implements MetadataLoader { where: filter, }); if (!row) return null; - if (packageId !== undefined && historyRowAttribution(row) !== packageId) return null; + if (packageId !== undefined && historyRowAttribution(row) !== packageId + && !isAddressedVersion(row, packageId, await this.isSoleRowSlot(type, name, packageId))) return null; return { id: row.id as string, @@ -1700,12 +1712,17 @@ export class DatabaseLoader implements MetadataLoader { // `package_id` column, the sentinel for the environment's, else the // package a row written before the column names in its body) to the one // addressed, then paged — so `total` and `hasMore` count that package's - // versions, not the name's. An unattributed version is in no address's. + // versions, not the name's. [#32717] When the address's slot is the + // name's one row slot, an unattributed version and the environment's own + // are its versions too ({@link isAddressedVersion}): exactly what a + // rollback addressing it restores. With several row slots an unattributed + // version is in no address's. let historyRecords: Array>; let total: number; if (packageId !== undefined) { + const sole = await this.isSoleRowSlot(type, name, packageId); const own = (await this._find(this.historyTableName, { where, orderBy })) - .filter((row) => historyRowAttribution(row) === packageId); + .filter((row) => isAddressedVersion(row, packageId, sole)); historyRecords = own.slice(offset, offset + limit + 1); total = own.length; } else { @@ -1755,6 +1772,20 @@ export class DatabaseLoader implements MetadataLoader { * (`refuseSeveralSlots`, the rollback's refusal): its versions are several * packages' and nothing picks one. Every other type is not read here. */ + /** + * [#32717] Whether the row slot `packageId` addresses (`null`: the + * environment's package-less row) is the one row slot of `name`, a + * by-package type ({@link rowSlots}) — the slot a rollback naming no + * package writes too, whose history therefore holds the versions + * attributed to none and the environment's own ({@link isAddressedVersion}). + * A name no row holds has no such slot: a rollback finds nothing to write. + */ + private async isSoleRowSlot(type: string, name: string, packageId: string | null): Promise { + await this.ensureSchema(); + const bySlot = await this.rowSlots(type, name); + return bySlot.size === 1 && bySlot.has(storeRowKey(name, packageId)); + } + private async historyPackageAddress( type: string, name: string, @@ -1781,10 +1812,18 @@ export class DatabaseLoader implements MetadataLoader { * when it holds no row of the name, or, addressing none, the name's one row * slot (several are refused naming every holder, before any write). The * version restored must be that slot's package's: another package's version - * is refused, ⛔ never written into the remaining holder's row (S8a). An - * addressed rollback to a version its address's history does not hold - * answers "not found", as `MetadataManager.rollback` does (#32717). Every + * is refused, ⛔ never written into the remaining holder's row (S8a). On a + * name one row slot holds, a version attributed to none and the + * environment's own version are that slot's, addressed or not (#32717, + * seat ruling 6885958183). The body written is stamped for the slot it is + * written into ({@link stampedForSlot}): ⛔ never a package stamp naming + * another package than the slot's, which would hand the environment's row + * to that package or serve a package's row as another's (#32717). Every * other type restores its name's row, as before. + * + * Resolves to the body written (the restored body, re-stamped for its slot + * when it named another package), which `MetadataManager.rollback` files in + * its registry so the served item and the stored row agree. */ async registerRollback( type: string, @@ -1794,19 +1833,22 @@ export class DatabaseLoader implements MetadataLoader { changeNote?: string, recordedBy?: string, options?: MetadataHistoryAddress, - ): Promise { + ): Promise { await this.ensureSchema(); const now = new Date().toISOString(); - const metadataJson = JSON.stringify(restoredData); - // [#21828] The one stamp vocabulary of `sys_metadata` — see {@link contentHash}. - const newChecksum = contentHash(metadataJson, type); // [ADR-0150 D3, #32246 R1/R1b, #32351] The rows a by-package rollback may // write: one slot's, picked as the doc above says. const slot = PACKAGE_SLOTTED_STORE_TYPES.has(type) ? await this.rollbackSlot(type, name, targetVersion, restoredData, addressedPackage(options)) : undefined; + // [#32717] The body that slot stores: stamped for the slot's owner, never + // for another package the restored body names. + const written = slot ? stampedForSlot(restoredData, slot.packageId) : restoredData; + const metadataJson = JSON.stringify(written); + // [#21828] The one stamp vocabulary of `sys_metadata` — see {@link contentHash}. + const newChecksum = contentHash(metadataJson, type); // [#31699 R3-B] A bundled type's one slot holds a row per member: the // rollback restores the row of the member the restored body declares, @@ -1814,7 +1856,7 @@ export class DatabaseLoader implements MetadataLoader { // does an action's: its member is the object the restored body is bound // to, never another binding's row. [#32351] Both within the one row slot // picked above, never another holder's rows. - const member = slot ? storedRowMemberOf(type, restoredData) : undefined; + const member = slot ? storedRowMemberOf(type, written) : undefined; const rowsOfName = slot && member !== undefined ? slot.rows : []; const existing = member === undefined ? (slot ? slot.rows[0] ?? null : await this._findOne(this.tableName, { where: this.baseFilter(type, name) })) @@ -1863,7 +1905,7 @@ export class DatabaseLoader implements MetadataLoader { name, type, namespace: slotRow.namespace ?? 'default', - scope: (restoredData as any)?.scope ?? slotRow.scope ?? 'platform', + scope: (written as any)?.scope ?? slotRow.scope ?? 'platform', metadata: metadataJson, checksum: newChecksum, strategy: 'merge', @@ -1884,7 +1926,7 @@ export class DatabaseLoader implements MetadataLoader { type, name, newVersion, - restoredData, + written, 'revert', newChecksum, previousChecksum, @@ -1892,6 +1934,7 @@ export class DatabaseLoader implements MetadataLoader { recordedBy, historySnapshotPackage(slot), ); + return written; } /** @@ -1911,26 +1954,24 @@ export class DatabaseLoader implements MetadataLoader { * holds one (the version is that owner's), and `not-held-by-qualifier` * naming that owner when it holds none (one since removed, S8a). The * environment's own version of a name one row slot holds lands in that - * row, as before (M1): a package took over the package-less row, or - * saved after it was removed; + * row, addressed or not (M1): a package took over the package-less row, + * or saved after it was removed; * - a version attributed to none (F1: a row written before the column, or * by `SysMetadataRepository` before #32905) lands in the slot picked only - * when the name has one row slot and the rollback names no package, as - * before; with several it is refused naming every holder - * (`refuseSeveralSlots`), addressed or not, since nothing says whose it - * is; - * - [#32717] addressed, a version the address's history does not hold — - * one attributed to none, or the environment's while a package's row is - * the name's one slot (M1) — answers "not found" - * ({@link historyVersionNotFound}), the words `MetadataManager.rollback` - * answers after its addressed read, before any write. The address names - * whose version is restored; attribution is what says so, and nothing - * is guessed (ADR-0150: one holder or a refusal); + * when the name has one row slot, addressed or not; with several it is + * refused naming every holder (`refuseSeveralSlots`), addressed or not, + * since nothing says whose it is. [#32717, seat ruling 6885958183] + * ADR-0150 D4: a package-less row at a held name is its one holder's + * customization, so with one row slot the address and the bare name + * write the same row, and these are the versions that slot's addressed + * history lists ({@link isAddressedVersion}) — the `/meta` door's + * `isVersionOf` rule; * - the restored body's own package stamp stands in for the version's * owner only when the version has no history row at all (history not * tracked, or no row of that version): a history row that exists, even * one attributed to none, is the version's owner, ⛔ never the stamp of - * the body a caller hands in (#32717). + * the body a caller hands in (#32717). The body written is then stamped + * for the slot ({@link stampedForSlot}, in {@link registerRollback}). */ private async rollbackSlot( type: string, @@ -1954,20 +1995,14 @@ export class DatabaseLoader implements MetadataLoader { // [#32717] Whose version it is: its history row's attribution whenever // the row exists; the restored body's stamp only for a version with no row. const versionOwner = recorded !== undefined ? historyRowAttribution(recorded) : storedItemPackageId(restoredData); - if (versionOwner === undefined) { + if (versionOwner === undefined || (versionOwner === null && bySlot.size === 1)) { // Attributed to none (or, with no history row, a body naming no - // package): with several row slots refused naming every holder. With - // one, a rollback naming no package lands it in that row, as before; - // an addressed one does not read it, as the manager's addressed read - // does not. + // package), or (M1) the environment's own version of a name one row + // slot holds — a package took over the package-less row, or it was + // removed and a package saved since: it lands in that one row, + // addressed or not. With several row slots it is refused naming every + // holder, addressed or not. refuseSeveralSlots(bySlot, type, name); - if (packageId !== undefined && recorded !== undefined) throw historyVersionNotFound(type, name, targetVersion, packageId); - } else if (versionOwner === null && bySlot.size === 1 && slotPackage !== undefined) { - // M1: the environment's own version of a name a package's row is the - // one slot of (a package took over the package-less row, or saved - // after it was removed): a rollback naming no package lands it in that - // row, as before; one naming the package does not read it. - if (packageId !== undefined) throw historyVersionNotFound(type, name, targetVersion, packageId); } else if (versionOwner !== (slotPackage ?? null)) { if (bySlot.has(storeRowKey(name, versionOwner))) { throw new Error( @@ -1998,8 +2033,8 @@ export class DatabaseLoader implements MetadataLoader { * history row is attributed to none. An addressed read leaves such a * version out, so `MetadataManager.rollback` asks here before answering its * miss "not found": the version exists, and nothing says whose it is. A - * name one row slot holds, an absent row and every other type pass: the - * miss is "not found", as {@link registerRollback} answers it (#32717). + * name one row slot holds (whose addressed read lists such a version, + * #32717), an absent row and every other type pass. */ async refuseUnattributedVersion(type: string, name: string, version: number): Promise { if (!PACKAGE_SLOTTED_STORE_TYPES.has(type) || !this.trackHistory) return; diff --git a/packages/metadata/src/metadata-history.test.ts b/packages/metadata/src/metadata-history.test.ts index 350f89a2322..c30b8f60e13 100644 --- a/packages/metadata/src/metadata-history.test.ts +++ b/packages/metadata/src/metadata-history.test.ts @@ -365,7 +365,9 @@ describe('history and rollback of a type stored per package (#32351)', () => { [2, body('custom')], [1, body('A1', A)], ]); - expect(await versions(type, { packageId: A })).toEqual([3, 1]); + // [#32717] A's slot is the name's one row slot, so its addressed history + // lists the unattributed v2 too: a rollback addressing A restores it. + expect(await versions(type, { packageId: A })).toEqual([3, 2, 1]); // An unattributed version lands in the one holder's row, as before. await manager.rollback(type, 'x', 2); expect((await rowsOf(type)).map((row) => [row.package_id, labelOf(row), row.version])).toEqual([[A, 'custom', 4]]); diff --git a/packages/metadata/src/metadata-manager.ts b/packages/metadata/src/metadata-manager.ts index 189e9043023..773900cee12 100644 --- a/packages/metadata/src/metadata-manager.ts +++ b/packages/metadata/src/metadata-manager.ts @@ -4671,9 +4671,12 @@ export class MetadataManager implements IMetadataService { * * [ADR-0150 D3/D4, #32351] For a type stored per `(package, name)`, * `options.packageId` reads that package's versions only (`null`: the - * environment's, recorded under no package); naming none, a - * name more than one row slot holds is refused 409 naming every holder - * (`PackageScopedNameRefusedError`), and one holder answers as before. + * environment's, recorded under no package) — [#32717] with, when that + * address's slot is the name's one row slot, the versions attributed to no + * package and the environment's own, which a rollback addressing it + * restores; naming none, a name more than one row slot holds is refused 409 + * naming every holder (`PackageScopedNameRefusedError`), and one holder + * answers as before. */ async getHistory( type: string, @@ -4702,12 +4705,18 @@ export class MetadataManager implements IMetadataService { * * [ADR-0150 D3/D4, #32351] For a type stored per `(package, name)`, * `options.packageId` names whose row is restored, and the version must be - * that package's ("not found" otherwise — [#32717] one attributed to none, - * or the environment's, included, in the words `DatabaseLoader.registerRollback` - * answers when called directly). Naming none, the name's one row is - * restored; several are refused 409 naming every holder, and so is a version - * of a package that holds no row of the name (`not-held-by-qualifier`) — - * ⛔ never written into another package's row. + * one its addressed history lists ("not found" otherwise): that package's, + * and — [#32717, seat ruling 6885958183] when its slot is the name's one row + * slot — one attributed to no package or the environment's own, which land + * in that row as they do naming no package (ADR-0150 D4: a package-less row + * at a held name is its one holder's customization). Naming none, the + * name's one row is restored; several are refused 409 naming every holder, + * and so is a version attributed to none while several hold the name, + * addressed or not, and a version of a package that holds no row of the + * name (`not-held-by-qualifier`) — ⛔ never written into another package's + * row. The body stored, filed and returned is stamped for the row slot it + * is written into (`DatabaseLoader.registerRollback`), never for another + * package its snapshot names. */ async rollback( type: string, @@ -4741,22 +4750,27 @@ 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; + let 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( + const handed = stamp === undefined ? restoredMetadata : withoutEnvironmentRowStamp(restoredMetadata as Record, stamp); + const written = await dbLoader.registerRollback( type, name, - stamp === undefined ? restoredMetadata : withoutEnvironmentRowStamp(restoredMetadata as Record, stamp), + handed, version, options?.changeNote, options?.recordedBy, address, ); + // [#32717] A by-package snapshot stamped for another package than the + // slot it lands in is written re-stamped for that slot: the registry files + // the body the row stores, ⛔ never the snapshot's stamp. + if (slotted && written !== handed) restoredMetadata = written as typeof restoredMetadata; // Update in-memory registry with the restored metadata. [#32351] A // package's restored version that names no package itself (a package-less diff --git a/packages/metadata/src/package-slotted-store.ts b/packages/metadata/src/package-slotted-store.ts index 6453d0cb3cc..d64b30c7708 100644 --- a/packages/metadata/src/package-slotted-store.ts +++ b/packages/metadata/src/package-slotted-store.ts @@ -126,7 +126,7 @@ import { type PackageScopedResolvableType, } from '@objectstack/core'; import { ITEM_KEY_DISCRIMINATORS, SysMetadataObject, itemDiscriminator } from '@objectstack/metadata-core'; -import { peelStoredEnvelope } from './stored-envelope.js'; +import { peelStoredEnvelope, STORED_BODY_KEY } from './stored-envelope.js'; import { PACKAGE_SLOTTED_METADATA_TYPES } from '@objectstack/spec/api'; /** @@ -418,6 +418,37 @@ export function storedItemPackageId(item: unknown): string | undefined { return undefined; } +/** + * [#32717, ADR-0150 D3/D4] `item`, a body a by-package rollback writes into + * the row slot of `slotPackage` (`undefined`: the environment's package-less + * row), with each package stamp {@link storedItemPackageId} reads (the + * envelope's `packageId`, the body's `_packageId`) that names another package + * replaced by the slot's: re-stamped with `slotPackage`, or removed from a + * body the environment's row stores. The slot is who the row is, and a stamp + * in the body would say otherwise: a `sys_metadata` row whose column names no + * package is keyed by the package its body names, so a foreign stamp written + * into the environment's row hands the row to that package, and one written + * into a package's row is served as another package's item. A body naming no + * package, or the slot's own, is returned unchanged (the same object), so a + * version's snapshot is restored byte for byte whenever it already agrees. + */ +export function stampedForSlot(item: unknown, slotPackage: string | undefined): unknown { + const restamp = (holder: Record, key: string): Record => { + if (!isPackageCaller(holder[key] as string | undefined) || holder[key] === slotPackage) return holder; + if (slotPackage !== undefined) return { ...holder, [key]: slotPackage }; + const { [key]: _foreign, ...rest } = holder; + return rest; + }; + if (item === null || typeof item !== 'object' || Array.isArray(item)) return item; + const peeled = peelStoredEnvelope(item); + const outer = restamp(item as Record, 'packageId'); + if (!peeled.wrapped) return restamp(outer, '_packageId'); + const body = peeled.body; + if (body === null || typeof body !== 'object' || Array.isArray(body)) return outer; + const inner = restamp(body as Record, '_packageId'); + return inner === body ? outer : { ...outer, [STORED_BODY_KEY]: inner }; +} + /** * [#31699 R3-B, epic ruling 6796068023] A bundled type — one that declares an * item-key discriminator (`ITEM_KEY_DISCRIMINATORS`, `@objectstack/metadata-core`: From ed9e3a95e2f5ba85cc9a17f16e725bbc0b547b1a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 23:52:51 +0000 Subject: [PATCH 9/9] =?UTF-8?q?chore(changeset):=20re-declare=20the=20roll?= =?UTF-8?q?back=20doors'=20moved=20answers=20under=20seat=20ruling=2068859?= =?UTF-8?q?58183=20=E2=80=94=20the=20sole-slot=20widening=20at=20the=20man?= =?UTF-8?q?ager's=20door,=20the=20stamped-body=20narrowing=20on=20several?= =?UTF-8?q?=20slots,=20and=20the=20body=20stamped=20for=20its=20slot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude-Session: https://claude.ai/code/session_016WV4cyrFFk86Jqf7Mp5Rzw Co-authored-by: Claude --- .changeset/32717-rollback-door-one-answer.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.changeset/32717-rollback-door-one-answer.md b/.changeset/32717-rollback-door-one-answer.md index 95992c32e1a..f2b4f4288a8 100644 --- a/.changeset/32717-rollback-door-one-answer.md +++ b/.changeset/32717-rollback-door-one-answer.md @@ -3,19 +3,19 @@ '@objectstack/metadata-core': patch --- -fix(metadata)!: `DatabaseLoader.registerRollback` answers an addressed rollback to a version its address's history does not hold "not found", as `MetadataManager.rollback` does, and a version's existing history row, never the restored body's package stamp, says whose version it is (#32717) +fix(metadata)!: on a name one row slot holds, the manager's addressed history and rollback answer the versions attributed to no package and the environment's own as that slot's, a version's existing history row (never the restored body's package stamp) says whose version it is, and a rollback writes its body stamped for the row slot it lands in (#32717) -Clause-②: yes (narrowing) — for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`; at this release `api`, `agent`, `skill`, `action`, `email_template`, `permission`, `flow`, `picklist`, `mapping`, `dataset`, `webhook`, `tool`), called directly on `DatabaseLoader.registerRollback`. Narrowed: an addressed rollback (`{ packageId }`, a package or `null` for the environment) to a version attributed to no package, on a name one row slot holds, and one addressing a package to the environment's own version while that package's row is the name's one slot (M1), wrote the version into that row and now answer `Version N not found in history for TYPE/NAME (package PKG)` (or `(environment)`), writing nothing; an addressed rollback to a version attributed to no package, on a name two row slots hold, with a restored body stamped for one of them (`_packageId`), wrote it into that package's row (addressing it) or answered that the version was that package's (addressing the other) and now answers `409 RESOURCE_CONFLICT` (`ambiguous-in-environment`, naming every holder). Widened: a rollback naming no package to a version attributed to no package, on a name one row slot holds, with a restored body stamped for a package that holds no row of the name, answered `409 RESOURCE_CONFLICT` (`not-held-by-qualifier`) and now lands in the one row, as the same version restored with an unstamped body does. `MetadataManager.rollback` answers every one of these as before. +Clause-②: yes (narrowing) — for a type stored per `(package, name)` (`PACKAGE_SLOTTED_STORE_TYPES`; at this release `api`, `agent`, `skill`, `action`, `email_template`, `permission`, `flow`, `picklist`, `mapping`, `dataset`, `webhook`, `tool`). Widened: `MetadataManager.getHistory`, `diff` and `rollback`, and `DatabaseLoader.getHistoryRecord` and `queryHistory`, addressed (`{ packageId }`, a package or `null` for the environment) to the name's one row slot, left out a version attributed to no package, and (addressing a package) the environment's own version, answering `Version N not found in history for TYPE/NAME (package PKG)` (or `(environment)`), and now list, diff and restore it into that row, as naming no package does; a direct `DatabaseLoader.registerRollback` to a version attributed to no package, on a name one row slot holds, with a restored body stamped (`_packageId`, or the envelope's `packageId`) for a package that holds no row of the name, answered `409 RESOURCE_CONFLICT` (`not-held-by-qualifier`) and now lands in the one row. Narrowed: a direct `DatabaseLoader.registerRollback` addressing a package to a version attributed to no package, on a name two or more row slots hold, with a restored body stamped for a package, wrote it into that package's row (the address and the stamp agreeing), or answered a plain `Error` that the version was that package's, or `409 not-held-by-qualifier` naming a stamped package that holds no row, and now answers `409 RESOURCE_CONFLICT` (`ambiguous-in-environment`, naming every holder), writing nothing. Metadata-protocol: none - + -**BREAKING** for a caller of `DatabaseLoader.registerRollback` that addresses a package (or the environment) and restores a version that address's history does not list. No first-party caller reaches it: `MetadataManager.rollback`, its one caller in the workspace, reads the addressed history first and already answered these requests "not found" or `409`, and the REST `/meta/:type/:name/rollback` door goes through the protocol's own repository. The fix: roll back naming no package on a name one row slot holds (`registerRollback(type, name, body, version)`), which restores such a version into that row as before, or address the package the version is attributed to (its `getHistory(type, name, { packageId })` lists it). +**BREAKING** for a direct caller of `DatabaseLoader.registerRollback` that addresses a package and restores a version recorded with no attribution (a history row written before `sys_metadata_history.package_id`, or one `SysMetadataRepository` wrote before it recorded the column) on a name several row slots hold, relying on the restored body's package stamp to say whose version it is. Nothing records whose it is, so it is refused naming every holder, as `MetadataManager.rollback` already refused it. No first-party caller reaches it: `MetadataManager.rollback`, the one caller in the workspace, restores a history row's own body, and a row attributed to none has a body naming no package. The fix: write the body into the package's row with a save (`save(type, name, body)` with the body's `_packageId` naming that package), which records a version attributed to it. -ADR-0150 D3/D4: an address names whose versions a rollback restores, and only a version's history row says whose it is. The two rollback doors of the metadata service now answer one request in the same words: +ADR-0150 D3/D4, seat ruling 6885958183 (amended B). `MetadataManager` and `DatabaseLoader` give one answer, and on a name one row slot holds the `/meta` history and rollback doors (`SysMetadataRepository`, `isVersionOf`) give it too: -- **A version attributed to no package** (a history row written before `sys_metadata_history.package_id`, or one `SysMetadataRepository` wrote before it recorded the column), addressed: FROM written into the addressed row at `registerRollback` and "not found" at `MetadataManager.rollback`, TO "not found" at both while one row slot holds the name, and `409` naming every holder at both while several do, as before. Naming no package it lands in the name's one row at both doors, as before. -- **The environment's own version, addressing the package whose row is the name's one slot** (M1: a package took over the package-less row, or saved after it was removed): FROM written into that row at `registerRollback` and "not found" at `MetadataManager.rollback`, TO "not found" at both. Naming no package it lands in that row at both doors, as before. -- **Whose version it is.** FROM the version's history row's attribution, else the restored body's package stamp when the row was attributed to none, TO the history row's attribution whenever the row exists; the body's stamp stands in only for a version with no history row at all (history not tracked, or no row of that version). A version attributed to no package is therefore never attributed by the body a caller hands in: on a name two row slots hold it is refused `409` naming both, ⛔ never written into the row of the package the body names. +- **A sole row slot's versions.** On a name one row slot holds, a version attributed to no package and the environment's own version are that slot's, addressed or not: a package-less row at a held name is that one holder's customization (ADR-0150 D4), so the address and the bare name write the same row. An addressed history read lists exactly what an addressed rollback restores: FROM "not found" at `MetadataManager.rollback`, `diff` and the addressed `getHistory` (which left such a version out) while `DatabaseLoader.registerRollback` restored it, TO listed, diffed and restored at every door. On a name several row slots hold such a version is in no addressed history and its rollback is refused `409 ambiguous-in-environment` naming every holder, addressed or not, as before. +- **Whose version it is.** FROM the version's history row's attribution, else the restored body's package stamp when the row was attributed to none, TO the history row's attribution whenever the row exists; the body's stamp stands in only for a version with no history row at all (history not tracked, or no row of that version). +- **The body a rollback writes.** FROM the restored body as handed in, TO the body stamped for the row slot it lands in: a package stamp (`_packageId`, or the envelope's `packageId`) naming another package than the slot's is replaced by the slot's package, or removed from a body the environment's package-less row stores. A body naming no package, or the slot's own, is written byte for byte, as before. Before, a foreign stamp written into the environment's row handed that row to the stamped package (`DatabaseLoader` keys a row whose `package_id` names no package by its body's stamp), and one written into a package's row served that package's item stamped for another. `DatabaseLoader.registerRollback` now resolves to the body it wrote, and `MetadataManager.rollback` files and returns that body. -`@objectstack/metadata-core` ships a documentation change only: the `sys_metadata_history.package_id` doc comment (in its published `dist`) now says NULL means "not attributed", never the environment, and that a row written before the column is read as the package its stored body names, else as attributed to none. No field, type or export changes. +`@objectstack/metadata-core` ships a documentation change only: the `sys_metadata_history.package_id` doc comment (in its published `dist`) says NULL means "not attributed", never the environment, and that such a row is the version of the name's one row slot and of no slot while several hold the name. No field, type or export changes.