From e5723e0c78183aa057817592444ffe8adfe48f47 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:53:41 +0000 Subject: [PATCH 1/7] test(metadata-protocol): pin a reverted non-object item whose write-through faults Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- ...tocol.revert-commit-honest-outcome.test.ts | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) diff --git a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts index ff8044715a0..726778715e2 100644 --- a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts +++ b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts @@ -447,3 +447,136 @@ describe('[#33564] reverting a revert commit restores what the revert replaced', expect(storedLabel(rows)).toBe('Renamed'); }); }); + +// ═══════════════════════════════════════════════════════════════════════════ +// §3 [#33851] A non-object type's write-through fault is a failed item too +// ═══════════════════════════════════════════════════════════════════════════ +// +// The write-through's non-object branches (the overlay hydration every type +// but `object` takes, and the `object_extension` registration) caught their +// own faults and only logged them, so a revert of a `view`, a `permission` or +// an `object_extension` whose registration threw answered `success: true`. +// The revert now asks those branches for the fault and reports it as §1 +// reports an object's refusal. Save and publish do not ask: under the same +// fault they answer what they answered before (the controls below). +// +// The kernel is one whose registry takes this kernel's stored rows +// (`storeHydratedIntoRegistry`), so the non-object branch reaches the +// registry at all; on the plain `env_prod` kernel above it returns before it. + +/** One stored item of a non-object type, saved twice: version 1 'First', version 2 (served) 'Renamed'. */ +const NON_OBJECT_CASES = [ + { + type: 'view', + name: 'ticket_grid', + body: (label: string) => ({ name: 'ticket_grid', label, object: 'ticket' }), + }, + { + type: 'permission', + name: 'ticket_reader', + body: (label: string) => ({ name: 'ticket_reader', label, objects: {} }), + }, +] as const; + +type NonObjectCase = (typeof NON_OBJECT_CASES)[number]; + +/** The stored active row's label for the case's item. */ +const storedLabelOf = (rows: Map, c: { type: string; name: string }): string | undefined => { + for (const r of rows.values()) { + if (r.type === c.type && r.name === c.name && r.state === 'active') return JSON.parse(r.metadata).label; + } + return undefined; +}; + +/** A kernel whose registry takes its stored rows, so the non-object write-through registers. */ +function makeHydratingProtocol() { + const rig = makeProtocol(); + rig.protocol.storeHydratedIntoRegistry = true; + const registered: Array<{ type: string; name: unknown }> = []; + rig.engine.registry.registerItem = (type: string, item: any) => { registered.push({ type, name: item?.name }); }; + return { ...rig, registered }; +} + +async function nonObjectEditedTwice(c: NonObjectCase) { + const rig = makeHydratingProtocol(); + await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('Renamed'), packageId: PKG }); + recordApply(rig.commits, 'c1', [{ type: c.type, name: c.name, existedBefore: true, prevVersion: 1 }]); + return rig; +} + +/** The registry throwing on every registration of `type`, with a declared client refusal. */ +function registryRefuses(engine: any, type: string) { + engine.registry.registerItem = (t: string) => { + if (t === type) { + throw Object.assign(new Error(`The registry is sealed for ${type} entries.`), { code: 'NOT_OVERRIDABLE', status: 403 }); + } + }; +} + +describe('[#33851] revertCommit reports a non-object write-through fault in failed[]', () => { + for (const c of NON_OBJECT_CASES) { + it(`control: a clean restore of a ${c.type} reverts it, registers the restored body and answers success`, async () => { + const { protocol, rows, registered } = await nonObjectEditedTwice(c); + registered.length = 0; + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res).toMatchObject({ success: true, revertedCount: 1, failedCount: 0, failed: [] }); + expect(res.reverted).toEqual([{ type: c.type, name: c.name, action: 'restored' }]); + expect(storedLabelOf(rows, c)).toBe('First'); + // Non-vacuity: the restored body went through the registry. + expect(registered.some((r) => r.type === c.type && r.name === c.name)).toBe(true); + }); + + it(`a ${c.type} whose write-through throws: failed[], row state and code named, success false`, async () => { + const { protocol, rows, commits, engine } = await nonObjectEditedTwice(c); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + registryRefuses(engine, c.type); + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res.success).toBe(false); + expect(res.reverted).toEqual([]); + expect(res.failedCount).toBe(1); + expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); + expect(res.failed[0].error).toContain('its row was restored to the body of version 1'); + expect(res.failed[0].error).toContain(`The registry is sealed for ${c.type} entries.`); + // The row change happened, and the revert's own commit records it. + expect(storedLabelOf(rows, c)).toBe('First'); + const [revert] = revertsOf(commits, 'c1'); + expect(JSON.parse(revert.items).map((i: any) => [i.type, i.name])).toEqual([[c.type, c.name]]); + }); + + it(`control: a save of a ${c.type} under the same fault answers as before, the fault only logged`, async () => { + const { protocol, rows, engine } = makeHydratingProtocol(); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + registryRefuses(engine, c.type); + + const res = await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + + expect(res.success).toBe(true); + expect(res.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('First'); + expect(warn.mock.calls.map((a) => String(a[0]))).toContain( + `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`, + ); + }); + + it(`control: a publish of a ${c.type} draft under the same fault answers as before, the fault only logged`, async () => { + const { protocol, rows, engine } = makeHydratingProtocol(); + await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG, mode: 'draft' }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + registryRefuses(engine, c.type); + + const res = await protocol.publishMetaItem({ type: c.type, name: c.name, packageId: PKG }); + + expect(res.success).toBe(true); + expect(res.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('First'); + expect(warn.mock.calls.map((a) => String(a[0]))).toContain( + `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`, + ); + }); + } +}); From b406a57bfcc8f5939127fc68e59c8a8753ddb540 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 13:59:02 +0000 Subject: [PATCH 2/7] fix(metadata-protocol): revertCommit reports a non-object item whose registry write-through faults The write-through's non-object branches (the overlay hydration and the object_extension registration) answer their fault to a caller that asks (answerFaults); revertCommit asks, so the item lands in failed[] with its row state named, as an object's refusal does. Save and publish do not ask and keep their answers. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../src/protocol-package-commits.ts | 13 +- .../src/protocol-registry-hydration.ts | 64 ++++-- ...tocol.revert-commit-honest-outcome.test.ts | 204 ++++++++++-------- 3 files changed, 179 insertions(+), 102 deletions(-) diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 663eec162dc..391a4740d06 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -94,6 +94,7 @@ import type { RollbackMetaItemRequest } from './protocol-door-requests.js'; import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './protocol-history-slots.js'; import { withRefusalAudit } from './protocol-refusal-audit.js'; import type { ProtocolHost } from './protocol-host.js'; +import type { RegistryWriteThroughRequest } from './protocol-registry-hydration.js'; import type { ImportUnmanagedPackageAnswer, InstallPackageStoredRowHook, StoredPackageRow } from './protocol-package-install.js'; /** @@ -1744,7 +1745,13 @@ export class ProtocolPackageCommitsFacet { // [#33563] The registry's refusal of the restored object is // this item's outcome, not a line on stderr: the row holds // the pre-commit body and the registry does not serve it. - const registryRefusal = await host.applyRegistryWriteThrough({ + // [#33851] …and so is a fault of any other type's branch + // (the overlay hydration, the `object_extension` + // registration), which the write-through answers only to a + // caller that asks (`answerFaults`). The request is handed + // whole through the class's forwarder, so it is built as the + // write-through's own request type. + const writeThrough: RegistryWriteThroughRequest = { type: PLURAL_TO_SINGULAR[it.type] ?? it.type, name: it.name, item: restored.item.body, @@ -1757,7 +1764,9 @@ export class ProtocolPackageCommitsFacet { // said "the row's OWN scope" while passing the REQUEST's // org; the resolution above is what makes the comment true. organizationId: null, - }); + answerFaults: true, + }; + const registryRefusal = await host.applyRegistryWriteThrough(writeThrough); if (registryRefusal) { notApplied.push( 'the runtime registry refused to serve the restored body (' diff --git a/packages/metadata-protocol/src/protocol-registry-hydration.ts b/packages/metadata-protocol/src/protocol-registry-hydration.ts index 4f9d7c44397..af04986d8be 100644 --- a/packages/metadata-protocol/src/protocol-registry-hydration.ts +++ b/packages/metadata-protocol/src/protocol-registry-hydration.ts @@ -1458,21 +1458,14 @@ export class ProtocolRegistryHydrationFacet { * The orphan adoption ({@link reassignOrphanedMetadata}) calls it for each * view row it rebinds, with `reboundFrom`, and [#23646] for each object * row, once {@link releaseAdoptedObjectOwner} has handed it the name. + * + * [#33851] What it answers: the registry's refusal of an object (the + * object branch, #33005), and nothing else unless the caller asks + * ({@link RegistryWriteThroughRequest.answerFaults}). A non-object branch + * that throws logs the fault at `warn` and, for a caller that asked, + * answers it in the same shape. */ - static async applyRegistryWriteThrough(host: Pick, request: { - type: string; - name: string; - item?: any; - packageId?: string | null; - /** The row's org scope — `null` for an env-wide row. [#6602] */ - organizationId: string | null; - /** - * [#23198] The binding the write moved the row from, when it moved it - * (an orphan adoption): `null` for the package-less row. See - * {@link HydrationOptions}. - */ - reboundFrom?: { readonly packageId: string | null }; - }): Promise { + static async applyRegistryWriteThrough(host: Pick, request: RegistryWriteThroughRequest): Promise { // [#8862] The `|| request.type === 'objects'` limb is GONE — this // branch admitted the plural that {@link applyObjectRegistryMutation} // then consumed. All four call sites of this method fold at their @@ -1527,6 +1520,8 @@ export class ProtocolRegistryHydrationFacet { console.warn( `[Protocol] registry write-through failed for ${request.type}/${request.name}: ${err?.message ?? err}`, ); + // [#33851] …and answered, to a caller that asked. + if (request.answerFaults === true) return { error: err }; } return undefined; } @@ -1546,6 +1541,10 @@ export class ProtocolRegistryHydrationFacet { console.warn( `[Protocol] registry write-through failed for ${request.type}/${request.name}: ${err?.message ?? err}`, ); + // [#33851] …and answered, to a caller that asked: the write is + // still not failed here, the caller decides what the fault means + // for its own answer. + if (request.answerFaults === true) return { error: err }; } return undefined; } @@ -2473,11 +2472,48 @@ export function objectStorageSyncRefusedNotice(name: string, err: unknown): Runt * answers when the registry refused the object it was asked to register: the * thrown value, whole. The row is already persisted; this is the one fact the * write-through used to keep to a `warn` line. + * + * [#33851] The write-through answers a non-object branch's fault in this + * shape too, to a caller that asked ({@link RegistryWriteThroughRequest.answerFaults}). */ export interface ObjectRegistryRefusal { readonly error: unknown; } +/** + * What {@link ProtocolRegistryHydrationFacet.applyRegistryWriteThrough} is + * asked to make live: the row's type, name and body, its binding and scope. + */ +export interface RegistryWriteThroughRequest { + type: string; + name: string; + item?: any; + packageId?: string | null; + /** The row's org scope — `null` for an env-wide row. [#6602] */ + organizationId: string | null; + /** + * [#23198] The binding the write moved the row from, when it moved it + * (an orphan adoption): `null` for the package-less row. See + * {@link HydrationOptions}. + */ + reboundFrom?: { readonly packageId: string | null }; + /** + * [#33851] `true`: a non-object branch whose registration throws (the + * `object_extension` registration, the overlay hydration) answers the + * fault as the object branch answers the registry's refusal, beside the + * `warn` line it logs. `revertCommit` asks, so a revert whose restored + * body the registry does not serve answers the item in `failed[]` + * (ADR-0067 D3, the method's docblock: a revert that answers success is + * one the running process has acted on). + * + * Left unset, the fault is only logged and the answer is `undefined`, as + * before. The save and publish doors leave it unset: they report a + * returned refusal as an object's (`object-registry-refused`), and their + * answers for every other type do not change. + */ + answerFaults?: boolean; +} + /** * [#33005] The rule id of the advisory a publish answers with when the runtime * registry refused an object the publish made live. Stable across releases, diff --git a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts index 726778715e2..f57c571eff8 100644 --- a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts +++ b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts @@ -453,130 +453,162 @@ describe('[#33564] reverting a revert commit restores what the revert replaced', // ═══════════════════════════════════════════════════════════════════════════ // // The write-through's non-object branches (the overlay hydration every type -// but `object` takes, and the `object_extension` registration) caught their -// own faults and only logged them, so a revert of a `view`, a `permission` or -// an `object_extension` whose registration threw answered `success: true`. -// The revert now asks those branches for the fault and reports it as §1 -// reports an object's refusal. Save and publish do not ask: under the same -// fault they answer what they answered before (the controls below). +// but `object` and `object_extension` takes, and the `object_extension` +// registration) caught their own faults and only logged them, so a revert of +// a `view`, a `permission` or an `object_extension` whose registration threw +// answered `success: true`. Measured on this harness before the fix: each +// fault case below answered `{ success: true, reverted: [{ …, action: +// 'restored' }], failed: [] }`. The revert now asks those branches for the +// fault and reports it as §1 reports an object's refusal. Save and publish do +// not ask: under the same fault they answer what they answered before, and +// the fault stays a `warn` line (the controls below, green before the fix too). // // The kernel is one whose registry takes this kernel's stored rows -// (`storeHydratedIntoRegistry`), so the non-object branch reaches the -// registry at all; on the plain `env_prod` kernel above it returns before it. +// (`storeHydratedIntoRegistry`), so the overlay branch reaches the registry at +// all; on the plain `env_prod` kernel of §1 it returns before it. + +const REFUSAL = (type: string) => + Object.assign(new Error(`The registry is sealed for ${type} entries.`), { code: 'NOT_OVERRIDABLE', status: 403 }); + +interface NonObjectCase { + readonly type: string; + readonly name: string; + readonly body: (label: string) => Record; + /** The label a stored body carries. */ + readonly labelOf: (body: any) => unknown; + /** The registry verb this type's write-through branch registers through. */ + readonly verb: 'registerItem' | 'registerObjectExtension'; +} -/** One stored item of a non-object type, saved twice: version 1 'First', version 2 (served) 'Renamed'. */ -const NON_OBJECT_CASES = [ +const NON_OBJECT_CASES: readonly NonObjectCase[] = [ { + // The overlay hydration branch. type: 'view', - name: 'ticket_grid', - body: (label: string) => ({ name: 'ticket_grid', label, object: 'ticket' }), + name: 'ticket.grid', + body: (label) => ({ + name: 'ticket.grid', label, object: 'ticket', viewKind: 'list', + config: { type: 'grid', data: { provider: 'object', object: 'ticket' }, columns: ['title'] }, + }), + labelOf: (body) => body.label, + verb: 'registerItem', }, { + // The overlay hydration branch, a type with no container. type: 'permission', name: 'ticket_reader', - body: (label: string) => ({ name: 'ticket_reader', label, objects: {} }), + body: (label) => ({ name: 'ticket_reader', label, objects: {} }), + labelOf: (body) => body.label, + verb: 'registerItem', }, -] as const; - -type NonObjectCase = (typeof NON_OBJECT_CASES)[number]; + { + // The `object_extension` branch. + type: 'object_extension', + name: 'ticket', + body: (label) => ({ extend: 'ticket', fields: { tier: { type: 'text', label } } }), + labelOf: (body) => body.fields?.tier?.label, + verb: 'registerObjectExtension', + }, +]; /** The stored active row's label for the case's item. */ -const storedLabelOf = (rows: Map, c: { type: string; name: string }): string | undefined => { +const storedLabelOf = (rows: Map, c: NonObjectCase): unknown => { for (const r of rows.values()) { - if (r.type === c.type && r.name === c.name && r.state === 'active') return JSON.parse(r.metadata).label; + if (r.type === c.type && r.name === c.name && r.state === 'active') return c.labelOf(JSON.parse(r.metadata)); } return undefined; }; -/** A kernel whose registry takes its stored rows, so the non-object write-through registers. */ -function makeHydratingProtocol() { +/** + * A kernel whose registry takes its stored rows, so the non-object + * write-through registers, with the object the view and the extension read + * already saved. `registered` records each registration of the case's verb. + */ +async function makeHydratingProtocol(c: NonObjectCase) { const rig = makeProtocol(); rig.protocol.storeHydratedIntoRegistry = true; - const registered: Array<{ type: string; name: unknown }> = []; - rig.engine.registry.registerItem = (type: string, item: any) => { registered.push({ type, name: item?.name }); }; - return { ...rig, registered }; + await rig.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: objectBody('Ticket'), packageId: PKG }); + // The stub registry keeps no objects: served here, for the extension's `extend`. + rig.engine.registry.getObject = (name: string) => (name === 'ticket' ? objectBody('Ticket') : undefined); + const registered: unknown[] = []; + rig.engine.registry[c.verb] = (...args: unknown[]) => { registered.push(args); }; + /** Make the case's verb throw from now on. */ + const refuse = () => { rig.engine.registry[c.verb] = () => { throw REFUSAL(c.type); }; }; + return { ...rig, registered, refuse }; } async function nonObjectEditedTwice(c: NonObjectCase) { - const rig = makeHydratingProtocol(); + const rig = await makeHydratingProtocol(c); await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('Renamed'), packageId: PKG }); recordApply(rig.commits, 'c1', [{ type: c.type, name: c.name, existedBefore: true, prevVersion: 1 }]); return rig; } -/** The registry throwing on every registration of `type`, with a declared client refusal. */ -function registryRefuses(engine: any, type: string) { - engine.registry.registerItem = (t: string) => { - if (t === type) { - throw Object.assign(new Error(`The registry is sealed for ${type} entries.`), { code: 'NOT_OVERRIDABLE', status: 403 }); - } - }; -} +/** The `warn` line the write-through's non-object branch logs for a fault. */ +const writeThroughWarnLine = (c: NonObjectCase) => + `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`; describe('[#33851] revertCommit reports a non-object write-through fault in failed[]', () => { for (const c of NON_OBJECT_CASES) { - it(`control: a clean restore of a ${c.type} reverts it, registers the restored body and answers success`, async () => { - const { protocol, rows, registered } = await nonObjectEditedTwice(c); - registered.length = 0; - - const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); - - expect(res).toMatchObject({ success: true, revertedCount: 1, failedCount: 0, failed: [] }); - expect(res.reverted).toEqual([{ type: c.type, name: c.name, action: 'restored' }]); - expect(storedLabelOf(rows, c)).toBe('First'); - // Non-vacuity: the restored body went through the registry. - expect(registered.some((r) => r.type === c.type && r.name === c.name)).toBe(true); - }); + describe(c.type, () => { + it('control: a clean restore reverts it, registers the restored body and answers success', async () => { + const { protocol, rows, registered } = await nonObjectEditedTwice(c); + registered.length = 0; + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res).toMatchObject({ success: true, revertedCount: 1, failedCount: 0, failed: [] }); + expect(res.reverted).toEqual([{ type: c.type, name: c.name, action: 'restored' }]); + expect(storedLabelOf(rows, c)).toBe('First'); + // Non-vacuity: the restore reached the branch's registry verb. + expect(registered.length).toBeGreaterThan(0); + }); - it(`a ${c.type} whose write-through throws: failed[], row state and code named, success false`, async () => { - const { protocol, rows, commits, engine } = await nonObjectEditedTwice(c); - vi.spyOn(console, 'warn').mockImplementation(() => {}); - registryRefuses(engine, c.type); - - const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); - - expect(res.success).toBe(false); - expect(res.reverted).toEqual([]); - expect(res.failedCount).toBe(1); - expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); - expect(res.failed[0].error).toContain('its row was restored to the body of version 1'); - expect(res.failed[0].error).toContain(`The registry is sealed for ${c.type} entries.`); - // The row change happened, and the revert's own commit records it. - expect(storedLabelOf(rows, c)).toBe('First'); - const [revert] = revertsOf(commits, 'c1'); - expect(JSON.parse(revert.items).map((i: any) => [i.type, i.name])).toEqual([[c.type, c.name]]); - }); + it('a write-through that throws: failed[], row state and code named, success false', async () => { + const { protocol, rows, commits, refuse } = await nonObjectEditedTwice(c); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res.success).toBe(false); + expect(res.reverted).toEqual([]); + expect(res.failedCount).toBe(1); + expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); + expect(res.failed[0].error).toContain('its row was restored to the body of version 1'); + expect(res.failed[0].error).toContain(`The registry is sealed for ${c.type} entries.`); + // The row change happened, and the revert's own commit records it. + expect(storedLabelOf(rows, c)).toBe('First'); + const [revert] = revertsOf(commits, 'c1'); + expect(JSON.parse(revert.items).map((i: any) => [i.type, i.name])).toEqual([[c.type, c.name]]); + }); - it(`control: a save of a ${c.type} under the same fault answers as before, the fault only logged`, async () => { - const { protocol, rows, engine } = makeHydratingProtocol(); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - registryRefuses(engine, c.type); + it('control: a save under the same fault answers as before, the fault only logged', async () => { + const { protocol, rows, refuse } = await makeHydratingProtocol(c); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); - const res = await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + const res = await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); - expect(res.success).toBe(true); - expect(res.advisories ?? []).toEqual([]); - expect(storedLabelOf(rows, c)).toBe('First'); - expect(warn.mock.calls.map((a) => String(a[0]))).toContain( - `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`, - ); - }); + expect(res.success).toBe(true); + expect(res.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('First'); + expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); + }); - it(`control: a publish of a ${c.type} draft under the same fault answers as before, the fault only logged`, async () => { - const { protocol, rows, engine } = makeHydratingProtocol(); - await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG, mode: 'draft' }); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - registryRefuses(engine, c.type); + it('control: a publish of a draft under the same fault answers as before, the fault only logged', async () => { + const { protocol, rows, refuse } = await makeHydratingProtocol(c); + await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG, mode: 'draft' }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); - const res = await protocol.publishMetaItem({ type: c.type, name: c.name, packageId: PKG }); + const res = await protocol.publishMetaItem({ type: c.type, name: c.name, packageId: PKG }); - expect(res.success).toBe(true); - expect(res.advisories ?? []).toEqual([]); - expect(storedLabelOf(rows, c)).toBe('First'); - expect(warn.mock.calls.map((a) => String(a[0]))).toContain( - `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`, - ); + expect(res.success).toBe(true); + expect(res.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('First'); + expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); + }); }); } }); From 8831b8f37ce4db929e072227e158f20ac8a8be8a Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 14:17:03 +0000 Subject: [PATCH 3/7] chore(changeset): revertCommit reports a non-object write-through fault Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- ...3851-revert-non-object-write-through-fault.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .changeset/33851-revert-non-object-write-through-fault.md diff --git a/.changeset/33851-revert-non-object-write-through-fault.md b/.changeset/33851-revert-non-object-write-through-fault.md new file mode 100644 index 00000000000..fcd6fbe3042 --- /dev/null +++ b/.changeset/33851-revert-non-object-write-through-fault.md @@ -0,0 +1,16 @@ +--- +'@objectstack/metadata-protocol': patch +--- + +fix(metadata-protocol): `revertCommit` reports a restored item of any type whose registry write-through faults + +Clause-②: no +Metadata-protocol: none + +`revertCommit` now puts a restored `view`, `permission`, `object_extension` or other non-object item into `failed[]` when the runtime registry write-through for its restored body throws, and the answer's `success` is `false`. The entry names the row state ("its row was restored to the body of version N") beside the registry's reason, and carries the reason's `code` where it declares one, the same way a refused `object` has been reported since the previous change to this door. Before, the write-through's non-object branches (the overlay hydration, and the `object_extension` registration) only logged the fault at `warn`, so such a revert answered `success: true` with the item in `reverted[]`, while the process kept serving the body the revert replaced. `rollbackToPackageCommit` carries each such item into its own `failed[]` and answers `success: false`. + +This replaces, for the restore limb, the line in the note on the previous change to this door that says such a fault "is still not seen by the revert". + +Save and publish do not change. They do not ask the write-through for these faults: under the same fault, `saveMetaItem` and `publishMetaItem` of a non-object item still answer success with no advisory, and the fault is still the same `warn` line in the server log. + +Not changed: on the soft-remove limb (an item the reverted commit created), a stop of the registry heal is still only logged at `error`, and the item is still reported as `removed`. From 9591c194afe9495f3e86c463cc93b0a36620b877 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:02:52 +0000 Subject: [PATCH 4/7] test(metadata-protocol): move the non-object write-through revert pins into their own file Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- ...tocol.revert-commit-honest-outcome.test.ts | 165 -------- ...mit-non-object-write-through-33851.test.ts | 389 ++++++++++++++++++ scripts/engine-double-contract.pinned.json | 15 + 3 files changed, 404 insertions(+), 165 deletions(-) create mode 100644 packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts diff --git a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts index f57c571eff8..ff8044715a0 100644 --- a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts +++ b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts @@ -447,168 +447,3 @@ describe('[#33564] reverting a revert commit restores what the revert replaced', expect(storedLabel(rows)).toBe('Renamed'); }); }); - -// ═══════════════════════════════════════════════════════════════════════════ -// §3 [#33851] A non-object type's write-through fault is a failed item too -// ═══════════════════════════════════════════════════════════════════════════ -// -// The write-through's non-object branches (the overlay hydration every type -// but `object` and `object_extension` takes, and the `object_extension` -// registration) caught their own faults and only logged them, so a revert of -// a `view`, a `permission` or an `object_extension` whose registration threw -// answered `success: true`. Measured on this harness before the fix: each -// fault case below answered `{ success: true, reverted: [{ …, action: -// 'restored' }], failed: [] }`. The revert now asks those branches for the -// fault and reports it as §1 reports an object's refusal. Save and publish do -// not ask: under the same fault they answer what they answered before, and -// the fault stays a `warn` line (the controls below, green before the fix too). -// -// The kernel is one whose registry takes this kernel's stored rows -// (`storeHydratedIntoRegistry`), so the overlay branch reaches the registry at -// all; on the plain `env_prod` kernel of §1 it returns before it. - -const REFUSAL = (type: string) => - Object.assign(new Error(`The registry is sealed for ${type} entries.`), { code: 'NOT_OVERRIDABLE', status: 403 }); - -interface NonObjectCase { - readonly type: string; - readonly name: string; - readonly body: (label: string) => Record; - /** The label a stored body carries. */ - readonly labelOf: (body: any) => unknown; - /** The registry verb this type's write-through branch registers through. */ - readonly verb: 'registerItem' | 'registerObjectExtension'; -} - -const NON_OBJECT_CASES: readonly NonObjectCase[] = [ - { - // The overlay hydration branch. - type: 'view', - name: 'ticket.grid', - body: (label) => ({ - name: 'ticket.grid', label, object: 'ticket', viewKind: 'list', - config: { type: 'grid', data: { provider: 'object', object: 'ticket' }, columns: ['title'] }, - }), - labelOf: (body) => body.label, - verb: 'registerItem', - }, - { - // The overlay hydration branch, a type with no container. - type: 'permission', - name: 'ticket_reader', - body: (label) => ({ name: 'ticket_reader', label, objects: {} }), - labelOf: (body) => body.label, - verb: 'registerItem', - }, - { - // The `object_extension` branch. - type: 'object_extension', - name: 'ticket', - body: (label) => ({ extend: 'ticket', fields: { tier: { type: 'text', label } } }), - labelOf: (body) => body.fields?.tier?.label, - verb: 'registerObjectExtension', - }, -]; - -/** The stored active row's label for the case's item. */ -const storedLabelOf = (rows: Map, c: NonObjectCase): unknown => { - for (const r of rows.values()) { - if (r.type === c.type && r.name === c.name && r.state === 'active') return c.labelOf(JSON.parse(r.metadata)); - } - return undefined; -}; - -/** - * A kernel whose registry takes its stored rows, so the non-object - * write-through registers, with the object the view and the extension read - * already saved. `registered` records each registration of the case's verb. - */ -async function makeHydratingProtocol(c: NonObjectCase) { - const rig = makeProtocol(); - rig.protocol.storeHydratedIntoRegistry = true; - await rig.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: objectBody('Ticket'), packageId: PKG }); - // The stub registry keeps no objects: served here, for the extension's `extend`. - rig.engine.registry.getObject = (name: string) => (name === 'ticket' ? objectBody('Ticket') : undefined); - const registered: unknown[] = []; - rig.engine.registry[c.verb] = (...args: unknown[]) => { registered.push(args); }; - /** Make the case's verb throw from now on. */ - const refuse = () => { rig.engine.registry[c.verb] = () => { throw REFUSAL(c.type); }; }; - return { ...rig, registered, refuse }; -} - -async function nonObjectEditedTwice(c: NonObjectCase) { - const rig = await makeHydratingProtocol(c); - await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); - await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('Renamed'), packageId: PKG }); - recordApply(rig.commits, 'c1', [{ type: c.type, name: c.name, existedBefore: true, prevVersion: 1 }]); - return rig; -} - -/** The `warn` line the write-through's non-object branch logs for a fault. */ -const writeThroughWarnLine = (c: NonObjectCase) => - `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`; - -describe('[#33851] revertCommit reports a non-object write-through fault in failed[]', () => { - for (const c of NON_OBJECT_CASES) { - describe(c.type, () => { - it('control: a clean restore reverts it, registers the restored body and answers success', async () => { - const { protocol, rows, registered } = await nonObjectEditedTwice(c); - registered.length = 0; - - const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); - - expect(res).toMatchObject({ success: true, revertedCount: 1, failedCount: 0, failed: [] }); - expect(res.reverted).toEqual([{ type: c.type, name: c.name, action: 'restored' }]); - expect(storedLabelOf(rows, c)).toBe('First'); - // Non-vacuity: the restore reached the branch's registry verb. - expect(registered.length).toBeGreaterThan(0); - }); - - it('a write-through that throws: failed[], row state and code named, success false', async () => { - const { protocol, rows, commits, refuse } = await nonObjectEditedTwice(c); - vi.spyOn(console, 'warn').mockImplementation(() => {}); - refuse(); - - const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); - - expect(res.success).toBe(false); - expect(res.reverted).toEqual([]); - expect(res.failedCount).toBe(1); - expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); - expect(res.failed[0].error).toContain('its row was restored to the body of version 1'); - expect(res.failed[0].error).toContain(`The registry is sealed for ${c.type} entries.`); - // The row change happened, and the revert's own commit records it. - expect(storedLabelOf(rows, c)).toBe('First'); - const [revert] = revertsOf(commits, 'c1'); - expect(JSON.parse(revert.items).map((i: any) => [i.type, i.name])).toEqual([[c.type, c.name]]); - }); - - it('control: a save under the same fault answers as before, the fault only logged', async () => { - const { protocol, rows, refuse } = await makeHydratingProtocol(c); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - refuse(); - - const res = await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); - - expect(res.success).toBe(true); - expect(res.advisories ?? []).toEqual([]); - expect(storedLabelOf(rows, c)).toBe('First'); - expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); - }); - - it('control: a publish of a draft under the same fault answers as before, the fault only logged', async () => { - const { protocol, rows, refuse } = await makeHydratingProtocol(c); - await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG, mode: 'draft' }); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - refuse(); - - const res = await protocol.publishMetaItem({ type: c.type, name: c.name, packageId: PKG }); - - expect(res.success).toBe(true); - expect(res.advisories ?? []).toEqual([]); - expect(storedLabelOf(rows, c)).toBe('First'); - expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); - }); - }); - } -}); diff --git a/packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts b/packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts new file mode 100644 index 00000000000..fd874288852 --- /dev/null +++ b/packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts @@ -0,0 +1,389 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#33851] `revertCommit` reports a restored non-object item whose registry + * write-through faults, and save and publish keep their answers. + * + * The governing text is `revertCommit`'s docblock on `protocol.ts` — "a revert + * that answers `success: true` is one the running process has already acted + * on" — and ADR-0067 D3. The object half is pinned in + * `protocol.revert-commit-honest-outcome.test.ts` (#33563); this file pins the + * non-object branches of the write-through, on a copy of that file's harness: + * an in-memory stub engine under the real `SysMetadataRepository`, with a + * commit store that keeps every commit the protocol records. The import is the + * same-package relative `./protocol.js`, so vitest compiles the source itself: + * no rebuild between an ablation and its run. + */ + +import { describe, expect, it, vi, afterEach } from 'vitest'; +import { + assertEngineDeleteDispatch, + assertEngineUpdateDispatch, + assertEngineFindOnePredicate, +} from '@objectstack/metadata-core'; +import { ObjectStackProtocolImplementation } from './protocol.js'; +// The object plane reaches `@objectstack/lint` only through a dynamic import; paid +// here at module scope so the first load lands during collection, not inside a +// clocked window (`pnpm check:test-source-alias`). +import '@objectstack/lint'; + +const PKG = 'app.demo'; +const INSTALLED_PACKAGES: ReadonlySet = new Set([PKG]); +const installedPackage = (id: string) => (INSTALLED_PACKAGES.has(id) ? { manifest: { id } } : undefined); + +interface Row { + id: string; + type: string; + name: string; + organization_id: string | null; + package_id: string | null; + state: string; + metadata: string; + checksum?: string; + version?: number; +} + +interface HistoryRow { + id: string; + type: string; + name: string; + version: number; + organization_id: string | null; + operation_type: string; + metadata?: string | null; +} + +interface CommitRow { + id: string; + package_id: string; + operation: 'apply' | 'revert'; + parent_commit_id?: string; + items: string; + created_at?: string; + [k: string]: unknown; +} + +/** ADR-0048 overlay key — (type, name, org, state, package_id). */ +const keyOf = (w: Record) => + `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; + +function matchesWhere(r: Row, where: Record): boolean { + for (const [k, v] of Object.entries(where)) { + if (k === '$or') { + const clauses = v as Array>; + if (!clauses.some((c) => matchesWhere(r, c))) return false; + continue; + } + if (v === undefined) continue; + if ((r as unknown as Record)[k] !== v) return false; + } + return true; +} + +function makeStubEngine() { + const rows = new Map(); + const historyRows: HistoryRow[] = []; + const commits: CommitRow[] = []; + let nextId = 0; + + const findRow = (w: Record): { key: string; row: Row } | null => { + if (w.id !== undefined) { + for (const [k, r] of rows) if (r.id === w.id) return { key: k, row: r }; + return null; + } + if (w.package_id !== undefined) { + const k = keyOf(w); + const r = rows.get(k); + if (r) return { key: k, row: r }; + } + for (const [k, r] of rows) if (matchesWhere(r, w)) return { key: k, row: r }; + return null; + }; + + const matchesHistory = (h: HistoryRow, w: Record): boolean => { + if (w.organization_id !== undefined && h.organization_id !== w.organization_id) return false; + if (w.type !== undefined && h.type !== w.type) return false; + if (w.name !== undefined && h.name !== w.name) return false; + if (w.version !== undefined && h.version !== w.version) return false; + if (w.operation_type !== undefined && h.operation_type !== w.operation_type) return false; + return true; + }; + + const engine: any = { + async findOne(table: string, opts: { where: Record }) { + assertEngineFindOnePredicate(table, opts); + if (table === 'sys_metadata_commit') return commits.find((c) => c.id === opts.where.id) ?? null; + if (table === 'sys_metadata_history') { + return historyRows.find((h) => matchesHistory(h, opts.where)) ?? null; + } + if (table !== 'sys_metadata') return null; + return findRow(opts.where)?.row ?? null; + }, + async find(table: string, opts?: { where?: Record; limit?: number }) { + const bound = (all: T[]): T[] => + typeof opts?.limit === 'number' ? all.slice(0, opts.limit) : all; + if (table === 'sys_metadata_commit') { + return bound(commits.filter((c) => opts?.where?.package_id === undefined || c.package_id === opts.where.package_id)); + } + if (table === 'sys_metadata_history') { + return bound(historyRows.filter((h) => matchesHistory(h, opts?.where ?? {}))); + } + if (table !== 'sys_metadata') return []; + return bound(Array.from(rows.values()).filter((r) => matchesWhere(r, opts?.where ?? {}))); + }, + async insert(table: string, data: Record) { + if (table === 'sys_metadata_commit') { + commits.push({ ...(data as unknown as CommitRow) }); + return { id: data.id }; + } + if (table === 'sys_metadata_audit') return { id: 'audit_skip' }; + if (table === 'sys_metadata_history') { + nextId += 1; + const h = { ...(data as unknown as HistoryRow), id: `h_${nextId}` }; + historyRows.push(h); + return { id: h.id }; + } + if (table !== 'sys_metadata') return { id: 'side_effect_skip' }; + nextId += 1; + const row = { ...(data as unknown as Row), id: `r_${nextId}` }; + rows.set(keyOf(data), row); + return { id: row.id }; + }, + async update(_t: string, data: Record, opts: { where: Record }) { + assertEngineUpdateDispatch(data, opts); + const found = findRow(opts.where); + if (!found) return { id: null }; + const merged = { ...found.row, ...(data as unknown as Row) }; + rows.delete(found.key); + rows.set(keyOf(merged), merged); + return { id: found.row.id }; + }, + async delete(_t: string, opts: { where: Record }) { + assertEngineDeleteDispatch(opts); + const found = findRow(opts.where); + if (!found) return { deleted: 0 }; + rows.delete(found.key); + return { deleted: 1 }; + }, + async count() { return 0; }, + async transaction(cb: (ctx: unknown, info: { owned: boolean }) => Promise): Promise { + return cb(undefined, { owned: true }); + }, + async syncObjectSchema() { return true; }, + async dropObjectSchema() { return true; }, + registry: { + registerItem: () => {}, + registerObject: () => {}, + unregisterObject: () => true, + removeObjectOverlay: () => {}, + removeRuntimeShadow: () => false, + removeOverlayEntry: () => true, + listItems: () => [], + getItem: () => undefined, + getObject: () => undefined, + getPackage: installedPackage, + getArtifactItem: () => undefined, + }, + }; + return { engine, rows, commits }; +} + +function makeProtocol() { + const h = makeStubEngine(); + const protocol = new ObjectStackProtocolImplementation(h.engine, () => new Map(), 'env_prod') as any; + ObjectStackProtocolImplementation.resetEnvWritableCache(); + /** Set to make the next projector call fail, the way a projector that throws does. */ + const projector = { fail: false, calls: 0 }; + protocol.registerMutationProjector('object', async () => { + projector.calls += 1; + if (projector.fail) throw new Error('SQLITE_ERROR: no such table: sys_permission_set'); + }); + return { protocol, projector, ...h }; +} + +/** An `apply` commit of `PKG`, recorded directly in the commit store. */ +function recordApply(commits: CommitRow[], id: string, items: unknown[]) { + commits.push({ + id, + commit_id: id, + package_id: PKG, + organization_id: null, + operation: 'apply', + message: `the commit ${id}`, + created_at: '2026-01-01T00:00:00Z', + items: JSON.stringify(items), + }); +} + +const objectBody = (label: string) => ({ + name: 'ticket', + label, + sharingModel: 'private', + fields: { title: { type: 'text', label: 'Title' } }, +}); + +const revertsOf = (commits: CommitRow[], parent: string) => + commits.filter((c) => c.operation === 'revert' && c.parent_commit_id === parent); + +afterEach(() => { vi.restoreAllMocks(); }); + +// The write-through's non-object branches (the overlay hydration every type +// but `object` and `object_extension` takes, and the `object_extension` +// registration) caught their own faults and only logged them, so a revert of +// a `view`, a `permission` or an `object_extension` whose registration threw +// answered `success: true`. Measured on this harness before the fix: each +// fault case below answered `{ success: true, reverted: [{ …, action: +// 'restored' }], failed: [] }`. The revert now asks those branches for the +// fault and reports it as it reports an object's refusal. Save and publish do +// not ask: under the same fault they answer what they answered before, and +// the fault stays a `warn` line (the controls below, green before the fix too). +// +// The kernel is one whose registry takes this kernel's stored rows +// (`storeHydratedIntoRegistry`), so the overlay branch reaches the registry at +// all; on the plain `env_prod` kernel it returns before it. + +const REFUSAL = (type: string) => + Object.assign(new Error(`The registry is sealed for ${type} entries.`), { code: 'NOT_OVERRIDABLE', status: 403 }); + +interface NonObjectCase { + readonly type: string; + readonly name: string; + readonly body: (label: string) => Record; + /** The label a stored body carries. */ + readonly labelOf: (body: any) => unknown; + /** The registry verb this type's write-through branch registers through. */ + readonly verb: 'registerItem' | 'registerObjectExtension'; +} + +const NON_OBJECT_CASES: readonly NonObjectCase[] = [ + { + // The overlay hydration branch. + type: 'view', + name: 'ticket.grid', + body: (label) => ({ + name: 'ticket.grid', label, object: 'ticket', viewKind: 'list', + config: { type: 'grid', data: { provider: 'object', object: 'ticket' }, columns: ['title'] }, + }), + labelOf: (body) => body.label, + verb: 'registerItem', + }, + { + // The overlay hydration branch, a type with no container. + type: 'permission', + name: 'ticket_reader', + body: (label) => ({ name: 'ticket_reader', label, objects: {} }), + labelOf: (body) => body.label, + verb: 'registerItem', + }, + { + // The `object_extension` branch. + type: 'object_extension', + name: 'ticket', + body: (label) => ({ extend: 'ticket', fields: { tier: { type: 'text', label } } }), + labelOf: (body) => body.fields?.tier?.label, + verb: 'registerObjectExtension', + }, +]; + +/** The stored active row's label for the case's item. */ +const storedLabelOf = (rows: Map, c: NonObjectCase): unknown => { + for (const r of rows.values()) { + if (r.type === c.type && r.name === c.name && r.state === 'active') return c.labelOf(JSON.parse(r.metadata)); + } + return undefined; +}; + +/** + * A kernel whose registry takes its stored rows, so the non-object + * write-through registers, with the object the view and the extension read + * already saved. `registered` records each registration of the case's verb. + */ +async function makeHydratingProtocol(c: NonObjectCase) { + const rig = makeProtocol(); + rig.protocol.storeHydratedIntoRegistry = true; + await rig.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: objectBody('Ticket'), packageId: PKG }); + // The stub registry keeps no objects: served here, for the extension's `extend`. + rig.engine.registry.getObject = (name: string) => (name === 'ticket' ? objectBody('Ticket') : undefined); + const registered: unknown[] = []; + rig.engine.registry[c.verb] = (...args: unknown[]) => { registered.push(args); }; + /** Make the case's verb throw from now on. */ + const refuse = () => { rig.engine.registry[c.verb] = () => { throw REFUSAL(c.type); }; }; + return { ...rig, registered, refuse }; +} + +async function nonObjectEditedTwice(c: NonObjectCase) { + const rig = await makeHydratingProtocol(c); + await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('Renamed'), packageId: PKG }); + recordApply(rig.commits, 'c1', [{ type: c.type, name: c.name, existedBefore: true, prevVersion: 1 }]); + return rig; +} + +/** The `warn` line the write-through's non-object branch logs for a fault. */ +const writeThroughWarnLine = (c: NonObjectCase) => + `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`; + +describe('[#33851] revertCommit reports a non-object write-through fault in failed[]', () => { + for (const c of NON_OBJECT_CASES) { + describe(c.type, () => { + it('control: a clean restore reverts it, registers the restored body and answers success', async () => { + const { protocol, rows, registered } = await nonObjectEditedTwice(c); + registered.length = 0; + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res).toMatchObject({ success: true, revertedCount: 1, failedCount: 0, failed: [] }); + expect(res.reverted).toEqual([{ type: c.type, name: c.name, action: 'restored' }]); + expect(storedLabelOf(rows, c)).toBe('First'); + // Non-vacuity: the restore reached the branch's registry verb. + expect(registered.length).toBeGreaterThan(0); + }); + + it('a write-through that throws: failed[], row state and code named, success false', async () => { + const { protocol, rows, commits, refuse } = await nonObjectEditedTwice(c); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res.success).toBe(false); + expect(res.reverted).toEqual([]); + expect(res.failedCount).toBe(1); + expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); + expect(res.failed[0].error).toContain('its row was restored to the body of version 1'); + expect(res.failed[0].error).toContain(`The registry is sealed for ${c.type} entries.`); + // The row change happened, and the revert's own commit records it. + expect(storedLabelOf(rows, c)).toBe('First'); + const [revert] = revertsOf(commits, 'c1'); + expect(JSON.parse(revert.items).map((i: any) => [i.type, i.name])).toEqual([[c.type, c.name]]); + }); + + it('control: a save under the same fault answers as before, the fault only logged', async () => { + const { protocol, rows, refuse } = await makeHydratingProtocol(c); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); + + const res = await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + + expect(res.success).toBe(true); + expect(res.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('First'); + expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); + }); + + it('control: a publish of a draft under the same fault answers as before, the fault only logged', async () => { + const { protocol, rows, refuse } = await makeHydratingProtocol(c); + await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG, mode: 'draft' }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); + + const res = await protocol.publishMetaItem({ type: c.type, name: c.name, packageId: PKG }); + + expect(res.success).toBe(true); + expect(res.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('First'); + expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); + }); + }); + } +}); diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 7013c2223f8..3dfff427bd9 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -1936,6 +1936,21 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts", + "verb": "delete", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts", + "verb": "findOne", + "pinned": 1 + }, + { + "file": "packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts", + "verb": "update", + "pinned": 1 + }, { "file": "packages/metadata-protocol/src/protocol.revert-stored-type-canonical.test.ts", "verb": "delete", From 132336df9cc9212d4e67a94451ba035a56e4c937 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:12:46 +0000 Subject: [PATCH 5/7] test(metadata-protocol): keep the non-object write-through revert pins in the revert harness file Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- ...tocol.revert-commit-honest-outcome.test.ts | 169 ++++++++ ...mit-non-object-write-through-33851.test.ts | 389 ------------------ scripts/engine-double-contract.pinned.json | 15 - 3 files changed, 169 insertions(+), 404 deletions(-) delete mode 100644 packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts diff --git a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts index ff8044715a0..324e6fdc3e1 100644 --- a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts +++ b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts @@ -17,6 +17,10 @@ * `{ success: true, reverted: [{ …, action: 'restored' | 'removed' }], * failed: [] }`, and the only trace was a `warn` line on stderr. * + * §3 [#33851] …and so does a restored non-object item (`view`, `permission`, + * `object_extension`) whose registry write-through throws, while save and + * publish under the same fault keep their answers. + * * The harness is an in-memory stub engine under the real * `SysMetadataRepository` (the pattern of * `protocol.recovery-doors-mutation-projector.test.ts`), with a commit store @@ -447,3 +451,168 @@ describe('[#33564] reverting a revert commit restores what the revert replaced', expect(storedLabel(rows)).toBe('Renamed'); }); }); + +// ═══════════════════════════════════════════════════════════════════════════ +// §3 [#33851] A non-object type's write-through fault is a failed item too +// ═══════════════════════════════════════════════════════════════════════════ +// +// The write-through's non-object branches (the overlay hydration every type +// but `object` and `object_extension` takes, and the `object_extension` +// registration) caught their own faults and only logged them, so a revert of +// a `view`, a `permission` or an `object_extension` whose registration threw +// answered `success: true`. Measured on this harness before the fix: each +// fault case below answered `{ success: true, reverted: [{ …, action: +// 'restored' }], failed: [] }`. The revert now asks those branches for the +// fault and reports it as §1 reports an object's refusal. Save and publish do +// not ask: under the same fault they answer what they answered before, and +// the fault stays a `warn` line (the controls below, green before the fix too). +// +// The kernel is one whose registry takes this kernel's stored rows +// (`storeHydratedIntoRegistry`), so the overlay branch reaches the registry at +// all; on the plain `env_prod` kernel of §1 it returns before it. + +const REFUSAL = (type: string) => + Object.assign(new Error(`The registry is sealed for ${type} entries.`), { code: 'NOT_OVERRIDABLE', status: 403 }); + +interface NonObjectCase { + readonly type: string; + readonly name: string; + readonly body: (label: string) => Record; + /** The label a stored body carries. */ + readonly labelOf: (body: any) => unknown; + /** The registry verb this type's write-through branch registers through. */ + readonly verb: 'registerItem' | 'registerObjectExtension'; +} + +const NON_OBJECT_CASES: readonly NonObjectCase[] = [ + { + // The overlay hydration branch. + type: 'view', + name: 'ticket.grid', + body: (label) => ({ + name: 'ticket.grid', label, object: 'ticket', viewKind: 'list', + config: { type: 'grid', data: { provider: 'object', object: 'ticket' }, columns: ['title'] }, + }), + labelOf: (body) => body.label, + verb: 'registerItem', + }, + { + // The overlay hydration branch, a type with no container. + type: 'permission', + name: 'ticket_reader', + body: (label) => ({ name: 'ticket_reader', label, objects: {} }), + labelOf: (body) => body.label, + verb: 'registerItem', + }, + { + // The `object_extension` branch. + type: 'object_extension', + name: 'ticket', + body: (label) => ({ extend: 'ticket', fields: { tier: { type: 'text', label } } }), + labelOf: (body) => body.fields?.tier?.label, + verb: 'registerObjectExtension', + }, +]; + +/** The stored active row's label for the case's item. */ +const storedLabelOf = (rows: Map, c: NonObjectCase): unknown => { + for (const r of rows.values()) { + if (r.type === c.type && r.name === c.name && r.state === 'active') return c.labelOf(JSON.parse(r.metadata)); + } + return undefined; +}; + +/** + * A kernel whose registry takes its stored rows, so the non-object + * write-through registers, with the object the view and the extension read + * already saved. `registered` records each registration of the case's verb. + */ +async function makeHydratingProtocol(c: NonObjectCase) { + const rig = makeProtocol(); + rig.protocol.storeHydratedIntoRegistry = true; + await rig.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: objectBody('Ticket'), packageId: PKG }); + // The stub registry keeps no objects: served here, for the extension's `extend`. + rig.engine.registry.getObject = (name: string) => (name === 'ticket' ? objectBody('Ticket') : undefined); + const registered: unknown[] = []; + rig.engine.registry[c.verb] = (...args: unknown[]) => { registered.push(args); }; + /** Make the case's verb throw from now on. */ + const refuse = () => { rig.engine.registry[c.verb] = () => { throw REFUSAL(c.type); }; }; + return { ...rig, registered, refuse }; +} + +async function nonObjectEditedTwice(c: NonObjectCase) { + const rig = await makeHydratingProtocol(c); + await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('Renamed'), packageId: PKG }); + recordApply(rig.commits, 'c1', [{ type: c.type, name: c.name, existedBefore: true, prevVersion: 1 }]); + return rig; +} + +/** The `warn` line the write-through's non-object branch logs for a fault. */ +const writeThroughWarnLine = (c: NonObjectCase) => + `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`; + +describe('[#33851] revertCommit reports a non-object write-through fault in failed[]', () => { + for (const c of NON_OBJECT_CASES) { + describe(c.type, () => { + it('control: a clean restore reverts it, registers the restored body and answers success', async () => { + const { protocol, rows, registered } = await nonObjectEditedTwice(c); + registered.length = 0; + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res).toMatchObject({ success: true, revertedCount: 1, failedCount: 0, failed: [] }); + expect(res.reverted).toEqual([{ type: c.type, name: c.name, action: 'restored' }]); + expect(storedLabelOf(rows, c)).toBe('First'); + // Non-vacuity: the restore reached the branch's registry verb. + expect(registered.length).toBeGreaterThan(0); + }); + + it('a write-through that throws: failed[], row state and code named, success false', async () => { + const { protocol, rows, commits, refuse } = await nonObjectEditedTwice(c); + vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res.success).toBe(false); + expect(res.reverted).toEqual([]); + expect(res.failedCount).toBe(1); + expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); + expect(res.failed[0].error).toContain('its row was restored to the body of version 1'); + expect(res.failed[0].error).toContain(`The registry is sealed for ${c.type} entries.`); + // The row change happened, and the revert's own commit records it. + expect(storedLabelOf(rows, c)).toBe('First'); + const [revert] = revertsOf(commits, 'c1'); + expect(JSON.parse(revert.items).map((i: any) => [i.type, i.name])).toEqual([[c.type, c.name]]); + }); + + it('control: a save under the same fault answers as before, the fault only logged', async () => { + const { protocol, rows, refuse } = await makeHydratingProtocol(c); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); + + const res = await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + + expect(res.success).toBe(true); + expect(res.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('First'); + expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); + }); + + it('control: a publish of a draft under the same fault answers as before, the fault only logged', async () => { + const { protocol, rows, refuse } = await makeHydratingProtocol(c); + await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG, mode: 'draft' }); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + refuse(); + + const res = await protocol.publishMetaItem({ type: c.type, name: c.name, packageId: PKG }); + + expect(res.success).toBe(true); + expect(res.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('First'); + expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); + }); + }); + } +}); diff --git a/packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts b/packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts deleted file mode 100644 index fd874288852..00000000000 --- a/packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -/** - * [#33851] `revertCommit` reports a restored non-object item whose registry - * write-through faults, and save and publish keep their answers. - * - * The governing text is `revertCommit`'s docblock on `protocol.ts` — "a revert - * that answers `success: true` is one the running process has already acted - * on" — and ADR-0067 D3. The object half is pinned in - * `protocol.revert-commit-honest-outcome.test.ts` (#33563); this file pins the - * non-object branches of the write-through, on a copy of that file's harness: - * an in-memory stub engine under the real `SysMetadataRepository`, with a - * commit store that keeps every commit the protocol records. The import is the - * same-package relative `./protocol.js`, so vitest compiles the source itself: - * no rebuild between an ablation and its run. - */ - -import { describe, expect, it, vi, afterEach } from 'vitest'; -import { - assertEngineDeleteDispatch, - assertEngineUpdateDispatch, - assertEngineFindOnePredicate, -} from '@objectstack/metadata-core'; -import { ObjectStackProtocolImplementation } from './protocol.js'; -// The object plane reaches `@objectstack/lint` only through a dynamic import; paid -// here at module scope so the first load lands during collection, not inside a -// clocked window (`pnpm check:test-source-alias`). -import '@objectstack/lint'; - -const PKG = 'app.demo'; -const INSTALLED_PACKAGES: ReadonlySet = new Set([PKG]); -const installedPackage = (id: string) => (INSTALLED_PACKAGES.has(id) ? { manifest: { id } } : undefined); - -interface Row { - id: string; - type: string; - name: string; - organization_id: string | null; - package_id: string | null; - state: string; - metadata: string; - checksum?: string; - version?: number; -} - -interface HistoryRow { - id: string; - type: string; - name: string; - version: number; - organization_id: string | null; - operation_type: string; - metadata?: string | null; -} - -interface CommitRow { - id: string; - package_id: string; - operation: 'apply' | 'revert'; - parent_commit_id?: string; - items: string; - created_at?: string; - [k: string]: unknown; -} - -/** ADR-0048 overlay key — (type, name, org, state, package_id). */ -const keyOf = (w: Record) => - `${w.type}|${w.name}|${w.organization_id ?? '__env__'}|${w.state ?? 'active'}|${w.package_id ?? '__nopkg__'}`; - -function matchesWhere(r: Row, where: Record): boolean { - for (const [k, v] of Object.entries(where)) { - if (k === '$or') { - const clauses = v as Array>; - if (!clauses.some((c) => matchesWhere(r, c))) return false; - continue; - } - if (v === undefined) continue; - if ((r as unknown as Record)[k] !== v) return false; - } - return true; -} - -function makeStubEngine() { - const rows = new Map(); - const historyRows: HistoryRow[] = []; - const commits: CommitRow[] = []; - let nextId = 0; - - const findRow = (w: Record): { key: string; row: Row } | null => { - if (w.id !== undefined) { - for (const [k, r] of rows) if (r.id === w.id) return { key: k, row: r }; - return null; - } - if (w.package_id !== undefined) { - const k = keyOf(w); - const r = rows.get(k); - if (r) return { key: k, row: r }; - } - for (const [k, r] of rows) if (matchesWhere(r, w)) return { key: k, row: r }; - return null; - }; - - const matchesHistory = (h: HistoryRow, w: Record): boolean => { - if (w.organization_id !== undefined && h.organization_id !== w.organization_id) return false; - if (w.type !== undefined && h.type !== w.type) return false; - if (w.name !== undefined && h.name !== w.name) return false; - if (w.version !== undefined && h.version !== w.version) return false; - if (w.operation_type !== undefined && h.operation_type !== w.operation_type) return false; - return true; - }; - - const engine: any = { - async findOne(table: string, opts: { where: Record }) { - assertEngineFindOnePredicate(table, opts); - if (table === 'sys_metadata_commit') return commits.find((c) => c.id === opts.where.id) ?? null; - if (table === 'sys_metadata_history') { - return historyRows.find((h) => matchesHistory(h, opts.where)) ?? null; - } - if (table !== 'sys_metadata') return null; - return findRow(opts.where)?.row ?? null; - }, - async find(table: string, opts?: { where?: Record; limit?: number }) { - const bound = (all: T[]): T[] => - typeof opts?.limit === 'number' ? all.slice(0, opts.limit) : all; - if (table === 'sys_metadata_commit') { - return bound(commits.filter((c) => opts?.where?.package_id === undefined || c.package_id === opts.where.package_id)); - } - if (table === 'sys_metadata_history') { - return bound(historyRows.filter((h) => matchesHistory(h, opts?.where ?? {}))); - } - if (table !== 'sys_metadata') return []; - return bound(Array.from(rows.values()).filter((r) => matchesWhere(r, opts?.where ?? {}))); - }, - async insert(table: string, data: Record) { - if (table === 'sys_metadata_commit') { - commits.push({ ...(data as unknown as CommitRow) }); - return { id: data.id }; - } - if (table === 'sys_metadata_audit') return { id: 'audit_skip' }; - if (table === 'sys_metadata_history') { - nextId += 1; - const h = { ...(data as unknown as HistoryRow), id: `h_${nextId}` }; - historyRows.push(h); - return { id: h.id }; - } - if (table !== 'sys_metadata') return { id: 'side_effect_skip' }; - nextId += 1; - const row = { ...(data as unknown as Row), id: `r_${nextId}` }; - rows.set(keyOf(data), row); - return { id: row.id }; - }, - async update(_t: string, data: Record, opts: { where: Record }) { - assertEngineUpdateDispatch(data, opts); - const found = findRow(opts.where); - if (!found) return { id: null }; - const merged = { ...found.row, ...(data as unknown as Row) }; - rows.delete(found.key); - rows.set(keyOf(merged), merged); - return { id: found.row.id }; - }, - async delete(_t: string, opts: { where: Record }) { - assertEngineDeleteDispatch(opts); - const found = findRow(opts.where); - if (!found) return { deleted: 0 }; - rows.delete(found.key); - return { deleted: 1 }; - }, - async count() { return 0; }, - async transaction(cb: (ctx: unknown, info: { owned: boolean }) => Promise): Promise { - return cb(undefined, { owned: true }); - }, - async syncObjectSchema() { return true; }, - async dropObjectSchema() { return true; }, - registry: { - registerItem: () => {}, - registerObject: () => {}, - unregisterObject: () => true, - removeObjectOverlay: () => {}, - removeRuntimeShadow: () => false, - removeOverlayEntry: () => true, - listItems: () => [], - getItem: () => undefined, - getObject: () => undefined, - getPackage: installedPackage, - getArtifactItem: () => undefined, - }, - }; - return { engine, rows, commits }; -} - -function makeProtocol() { - const h = makeStubEngine(); - const protocol = new ObjectStackProtocolImplementation(h.engine, () => new Map(), 'env_prod') as any; - ObjectStackProtocolImplementation.resetEnvWritableCache(); - /** Set to make the next projector call fail, the way a projector that throws does. */ - const projector = { fail: false, calls: 0 }; - protocol.registerMutationProjector('object', async () => { - projector.calls += 1; - if (projector.fail) throw new Error('SQLITE_ERROR: no such table: sys_permission_set'); - }); - return { protocol, projector, ...h }; -} - -/** An `apply` commit of `PKG`, recorded directly in the commit store. */ -function recordApply(commits: CommitRow[], id: string, items: unknown[]) { - commits.push({ - id, - commit_id: id, - package_id: PKG, - organization_id: null, - operation: 'apply', - message: `the commit ${id}`, - created_at: '2026-01-01T00:00:00Z', - items: JSON.stringify(items), - }); -} - -const objectBody = (label: string) => ({ - name: 'ticket', - label, - sharingModel: 'private', - fields: { title: { type: 'text', label: 'Title' } }, -}); - -const revertsOf = (commits: CommitRow[], parent: string) => - commits.filter((c) => c.operation === 'revert' && c.parent_commit_id === parent); - -afterEach(() => { vi.restoreAllMocks(); }); - -// The write-through's non-object branches (the overlay hydration every type -// but `object` and `object_extension` takes, and the `object_extension` -// registration) caught their own faults and only logged them, so a revert of -// a `view`, a `permission` or an `object_extension` whose registration threw -// answered `success: true`. Measured on this harness before the fix: each -// fault case below answered `{ success: true, reverted: [{ …, action: -// 'restored' }], failed: [] }`. The revert now asks those branches for the -// fault and reports it as it reports an object's refusal. Save and publish do -// not ask: under the same fault they answer what they answered before, and -// the fault stays a `warn` line (the controls below, green before the fix too). -// -// The kernel is one whose registry takes this kernel's stored rows -// (`storeHydratedIntoRegistry`), so the overlay branch reaches the registry at -// all; on the plain `env_prod` kernel it returns before it. - -const REFUSAL = (type: string) => - Object.assign(new Error(`The registry is sealed for ${type} entries.`), { code: 'NOT_OVERRIDABLE', status: 403 }); - -interface NonObjectCase { - readonly type: string; - readonly name: string; - readonly body: (label: string) => Record; - /** The label a stored body carries. */ - readonly labelOf: (body: any) => unknown; - /** The registry verb this type's write-through branch registers through. */ - readonly verb: 'registerItem' | 'registerObjectExtension'; -} - -const NON_OBJECT_CASES: readonly NonObjectCase[] = [ - { - // The overlay hydration branch. - type: 'view', - name: 'ticket.grid', - body: (label) => ({ - name: 'ticket.grid', label, object: 'ticket', viewKind: 'list', - config: { type: 'grid', data: { provider: 'object', object: 'ticket' }, columns: ['title'] }, - }), - labelOf: (body) => body.label, - verb: 'registerItem', - }, - { - // The overlay hydration branch, a type with no container. - type: 'permission', - name: 'ticket_reader', - body: (label) => ({ name: 'ticket_reader', label, objects: {} }), - labelOf: (body) => body.label, - verb: 'registerItem', - }, - { - // The `object_extension` branch. - type: 'object_extension', - name: 'ticket', - body: (label) => ({ extend: 'ticket', fields: { tier: { type: 'text', label } } }), - labelOf: (body) => body.fields?.tier?.label, - verb: 'registerObjectExtension', - }, -]; - -/** The stored active row's label for the case's item. */ -const storedLabelOf = (rows: Map, c: NonObjectCase): unknown => { - for (const r of rows.values()) { - if (r.type === c.type && r.name === c.name && r.state === 'active') return c.labelOf(JSON.parse(r.metadata)); - } - return undefined; -}; - -/** - * A kernel whose registry takes its stored rows, so the non-object - * write-through registers, with the object the view and the extension read - * already saved. `registered` records each registration of the case's verb. - */ -async function makeHydratingProtocol(c: NonObjectCase) { - const rig = makeProtocol(); - rig.protocol.storeHydratedIntoRegistry = true; - await rig.protocol.saveMetaItem({ type: 'object', name: 'ticket', item: objectBody('Ticket'), packageId: PKG }); - // The stub registry keeps no objects: served here, for the extension's `extend`. - rig.engine.registry.getObject = (name: string) => (name === 'ticket' ? objectBody('Ticket') : undefined); - const registered: unknown[] = []; - rig.engine.registry[c.verb] = (...args: unknown[]) => { registered.push(args); }; - /** Make the case's verb throw from now on. */ - const refuse = () => { rig.engine.registry[c.verb] = () => { throw REFUSAL(c.type); }; }; - return { ...rig, registered, refuse }; -} - -async function nonObjectEditedTwice(c: NonObjectCase) { - const rig = await makeHydratingProtocol(c); - await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); - await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('Renamed'), packageId: PKG }); - recordApply(rig.commits, 'c1', [{ type: c.type, name: c.name, existedBefore: true, prevVersion: 1 }]); - return rig; -} - -/** The `warn` line the write-through's non-object branch logs for a fault. */ -const writeThroughWarnLine = (c: NonObjectCase) => - `[Protocol] registry write-through failed for ${c.type}/${c.name}: The registry is sealed for ${c.type} entries.`; - -describe('[#33851] revertCommit reports a non-object write-through fault in failed[]', () => { - for (const c of NON_OBJECT_CASES) { - describe(c.type, () => { - it('control: a clean restore reverts it, registers the restored body and answers success', async () => { - const { protocol, rows, registered } = await nonObjectEditedTwice(c); - registered.length = 0; - - const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); - - expect(res).toMatchObject({ success: true, revertedCount: 1, failedCount: 0, failed: [] }); - expect(res.reverted).toEqual([{ type: c.type, name: c.name, action: 'restored' }]); - expect(storedLabelOf(rows, c)).toBe('First'); - // Non-vacuity: the restore reached the branch's registry verb. - expect(registered.length).toBeGreaterThan(0); - }); - - it('a write-through that throws: failed[], row state and code named, success false', async () => { - const { protocol, rows, commits, refuse } = await nonObjectEditedTwice(c); - vi.spyOn(console, 'warn').mockImplementation(() => {}); - refuse(); - - const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); - - expect(res.success).toBe(false); - expect(res.reverted).toEqual([]); - expect(res.failedCount).toBe(1); - expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); - expect(res.failed[0].error).toContain('its row was restored to the body of version 1'); - expect(res.failed[0].error).toContain(`The registry is sealed for ${c.type} entries.`); - // The row change happened, and the revert's own commit records it. - expect(storedLabelOf(rows, c)).toBe('First'); - const [revert] = revertsOf(commits, 'c1'); - expect(JSON.parse(revert.items).map((i: any) => [i.type, i.name])).toEqual([[c.type, c.name]]); - }); - - it('control: a save under the same fault answers as before, the fault only logged', async () => { - const { protocol, rows, refuse } = await makeHydratingProtocol(c); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - refuse(); - - const res = await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); - - expect(res.success).toBe(true); - expect(res.advisories ?? []).toEqual([]); - expect(storedLabelOf(rows, c)).toBe('First'); - expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); - }); - - it('control: a publish of a draft under the same fault answers as before, the fault only logged', async () => { - const { protocol, rows, refuse } = await makeHydratingProtocol(c); - await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG, mode: 'draft' }); - const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); - refuse(); - - const res = await protocol.publishMetaItem({ type: c.type, name: c.name, packageId: PKG }); - - expect(res.success).toBe(true); - expect(res.advisories ?? []).toEqual([]); - expect(storedLabelOf(rows, c)).toBe('First'); - expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); - }); - }); - } -}); diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 3dfff427bd9..7013c2223f8 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -1936,21 +1936,6 @@ "verb": "update", "pinned": 1 }, - { - "file": "packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts", - "verb": "delete", - "pinned": 1 - }, - { - "file": "packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts", - "verb": "findOne", - "pinned": 1 - }, - { - "file": "packages/metadata-protocol/src/protocol.revert-commit-non-object-write-through-33851.test.ts", - "verb": "update", - "pinned": 1 - }, { "file": "packages/metadata-protocol/src/protocol.revert-stored-type-canonical.test.ts", "verb": "delete", From efd9752ea2860d8c8d12c3a1ad4e199621e20e87 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:24:47 +0000 Subject: [PATCH 6/7] fix(metadata-protocol): revertCommit reports a removed item whose registry heal stops The heal answers its stop (its outer catch, keeping the error line, or a row still stored that the registry refuses); the soft-remove limb reports it in failed[] with the removed row named. Every other caller ignores it. The forwarders in protocol.ts name the heal's stop and the write-through's request type. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .../33563-revert-commit-honest-outcome.md | 2 +- ...1-revert-non-object-write-through-fault.md | 8 +- .../src/protocol-package-commits.ts | 24 ++-- .../src/protocol-registry-hydration.ts | 35 ++++- ...tocol.revert-commit-honest-outcome.test.ts | 130 ++++++++++++++++++ packages/metadata-protocol/src/protocol.ts | 27 ++-- 6 files changed, 190 insertions(+), 36 deletions(-) diff --git a/.changeset/33563-revert-commit-honest-outcome.md b/.changeset/33563-revert-commit-honest-outcome.md index b87e1033042..3b915a625a0 100644 --- a/.changeset/33563-revert-commit-honest-outcome.md +++ b/.changeset/33563-revert-commit-honest-outcome.md @@ -9,7 +9,7 @@ Metadata-protocol: none `revertCommit` now reports an item whose row was written but whose next step did not land in `failed[]`, not `reverted[]`, and the answer's `success` is `false`. The steps are: the runtime registry refusing the restored object, its storage not following the restored body (the `object-storage-sync-refused` advisory stays on `advisories`), the mutation projector failing, and any step after the row write throwing. The entry names the row state ("its row was restored to the body of version N", or "its row was removed from sys_metadata") beside the step that failed, and quotes no driver text. The revert's own commit still records the row change. Before, each of these answered `success: true` with the item in `reverted[]`, against the method's own contract ("a revert that answers `success: true` is one the running process has already acted on"). `rollbackToPackageCommit` carries each such item into its own `failed[]` and answers `success: false`. -A write-through fault the registry helper only logs (every metadata type other than `object`) is still not seen by the revert. +The same holds for a restored item of any other metadata type whose registry write-through throws, and for a removed item whose registry heal stops (see the note on reporting a non-object item's registry fault). A revert is now itself revertible, as ADR-0067 D3 says. The revert's own commit records, for each row it changed, the version that row held before the revert, so reverting the revert brings that body back, and an item the revert removed is written again. An item recorded as existing before the commit but carrying no version to restore, which is how every revert commit recorded by an earlier release records the items it restored, is named in `failed[]` with nothing written. Before, it was skipped: it appeared in neither `reverted[]` nor `failed[]`. To undo such an older revert, restore each item from its own version history (`GET /api/v1/meta/:type/:name/history`, then `POST /api/v1/meta/:type/:name/rollback`). diff --git a/.changeset/33851-revert-non-object-write-through-fault.md b/.changeset/33851-revert-non-object-write-through-fault.md index fcd6fbe3042..fb9d7084c8a 100644 --- a/.changeset/33851-revert-non-object-write-through-fault.md +++ b/.changeset/33851-revert-non-object-write-through-fault.md @@ -2,15 +2,13 @@ '@objectstack/metadata-protocol': patch --- -fix(metadata-protocol): `revertCommit` reports a restored item of any type whose registry write-through faults +fix(metadata-protocol): `revertCommit` reports an item of any type whose registry write-through or heal faults Clause-②: no Metadata-protocol: none `revertCommit` now puts a restored `view`, `permission`, `object_extension` or other non-object item into `failed[]` when the runtime registry write-through for its restored body throws, and the answer's `success` is `false`. The entry names the row state ("its row was restored to the body of version N") beside the registry's reason, and carries the reason's `code` where it declares one, the same way a refused `object` has been reported since the previous change to this door. Before, the write-through's non-object branches (the overlay hydration, and the `object_extension` registration) only logged the fault at `warn`, so such a revert answered `success: true` with the item in `reverted[]`, while the process kept serving the body the revert replaced. `rollbackToPackageCommit` carries each such item into its own `failed[]` and answers `success: false`. -This replaces, for the restore limb, the line in the note on the previous change to this door that says such a fault "is still not seen by the revert". +A removed item is reported the same way. When the revert soft-removes an item the reverted commit created and the registry heal after the removal stops (a registry throw, or the registry refusing a row of the item still stored under another package), the item goes into `failed[]` naming "its row was removed from sys_metadata" and that the registry may still serve the removed row, with the reason and its `code`. Before, the heal's stop was only an `error` line in the server log, and the item answered `removed`. The `error` line is unchanged. -Save and publish do not change. They do not ask the write-through for these faults: under the same fault, `saveMetaItem` and `publishMetaItem` of a non-object item still answer success with no advisory, and the fault is still the same `warn` line in the server log. - -Not changed: on the soft-remove limb (an item the reverted commit created), a stop of the registry heal is still only logged at `error`, and the item is still reported as `removed`. +Save, publish and delete do not change. Save and publish do not ask the write-through for these faults: under the same fault, `saveMetaItem` and `publishMetaItem` of a non-object item still answer success with no advisory, and the fault is still the same `warn` line in the server log. `deleteMetaItem`, a publish's undo and a peer's convergence ignore the heal's answer, so a stopped heal still answers what it answered before there, with the same `error` line. diff --git a/packages/metadata-protocol/src/protocol-package-commits.ts b/packages/metadata-protocol/src/protocol-package-commits.ts index 391a4740d06..6e576f0d6c2 100644 --- a/packages/metadata-protocol/src/protocol-package-commits.ts +++ b/packages/metadata-protocol/src/protocol-package-commits.ts @@ -94,7 +94,6 @@ import type { RollbackMetaItemRequest } from './protocol-door-requests.js'; import { historySlotOf, refusePackageSelectorOutsideSlottedTypes } from './protocol-history-slots.js'; import { withRefusalAudit } from './protocol-refusal-audit.js'; import type { ProtocolHost } from './protocol-host.js'; -import type { RegistryWriteThroughRequest } from './protocol-registry-hydration.js'; import type { ImportUnmanagedPackageAnswer, InstallPackageStoredRowHook, StoredPackageRow } from './protocol-package-install.js'; /** @@ -1568,7 +1567,19 @@ export class ProtocolPackageCommitsFacet { // `object` serves no field afterwards, so it changes none. const removedCapture = captureStoredExpressionChange(host.engine, PLURAL_TO_SINGULAR[it.type] ?? it.type, it.name); if (removedCapture && !storedExpressions.has(removedCapture.object)) storedExpressions.set(removedCapture.object, removedCapture); - await host.restoreArtifactRegistryView(it.type, it.name, null, commitPackageId, member); + // [#33851] The heal's stop is this item's outcome too, the way + // the restore limb reports the write-through's refusal: the + // row is removed and the registry may still serve it. Only + // where a row was removed; with none, the heal is a + // self-heal of nothing this revert wrote, and stays logged. + const healStop = await host.restoreArtifactRegistryView(it.type, it.name, null, commitPackageId, member); + if (healStop && current) { + notApplied.push( + 'the runtime registry was not healed after the removal, so it may still serve the removed row (' + + `${clientFacingFailureText(healStop.error, 'the reason is in the server log')})`, + ); + notAppliedCode = clientFacingFailureCode(healStop.error); + } // [#14179] …and announce it on the ONE choke point, // {@link emitMetadataMutation}, exactly as the sibling // delete caller {@link deleteMetaItem} does after its own @@ -1748,10 +1759,8 @@ export class ProtocolPackageCommitsFacet { // [#33851] …and so is a fault of any other type's branch // (the overlay hydration, the `object_extension` // registration), which the write-through answers only to a - // caller that asks (`answerFaults`). The request is handed - // whole through the class's forwarder, so it is built as the - // write-through's own request type. - const writeThrough: RegistryWriteThroughRequest = { + // caller that asks (`answerFaults`). + const registryRefusal = await host.applyRegistryWriteThrough({ type: PLURAL_TO_SINGULAR[it.type] ?? it.type, name: it.name, item: restored.item.body, @@ -1765,8 +1774,7 @@ export class ProtocolPackageCommitsFacet { // org; the resolution above is what makes the comment true. organizationId: null, answerFaults: true, - }; - const registryRefusal = await host.applyRegistryWriteThrough(writeThrough); + }); if (registryRefusal) { notApplied.push( 'the runtime registry refused to serve the restored body (' diff --git a/packages/metadata-protocol/src/protocol-registry-hydration.ts b/packages/metadata-protocol/src/protocol-registry-hydration.ts index af04986d8be..c47e94f74b6 100644 --- a/packages/metadata-protocol/src/protocol-registry-hydration.ts +++ b/packages/metadata-protocol/src/protocol-registry-hydration.ts @@ -1733,6 +1733,15 @@ export class ProtocolRegistryHydrationFacet { * naming no package answers the store's refusal, naming every holder. So it * does for a row bound to a non-holder of the name whose pair relation names * zero or several bases (epic ruling 6818436831, #32620). + * + * [#33851] What it answers: the walk's stop ({@link RegistryHealStop}), + * when a throw stopped it (the logged stop above) or the registry refused or + * faulted on a row still stored (the step that registers it again); + * otherwise `undefined`, a designed outcome included (a refused baseline + * read that retires the entry, a degraded read that keeps it). Only + * `revertCommit` reads it, and reports the item in `failed[]`; every other + * caller ignores it, so a delete, a publish undo and a peer's convergence + * answer what they answered before. */ static async restoreArtifactRegistryView(host: Pick, type: string, name: string, @@ -1754,7 +1763,7 @@ export class ProtocolRegistryHydrationFacet { * rows are still stored and served, so their registry entries stay. * No effect for a type with no members. */ - member?: string,): Promise { + member?: string,): Promise { // [#6780] ADR-0005 — the plain-key entry belongs to the env-wide row, // so only an env-wide removal may heal (or retire) it. if (organizationId !== null && organizationId !== undefined) return; @@ -1894,16 +1903,22 @@ export class ProtocolRegistryHydrationFacet { } } } + // [#33851] A remaining row the registry does not take is the + // heal's stop too: the first refusal or fault is answered, after + // every row has been tried. + let refused: RegistryHealStop | undefined; for (const row of remainingRows) { - await host.applyRegistryWriteThrough({ + const refusal = await host.applyRegistryWriteThrough({ type: canonical, name, item: host.convertStoredItem(String(row.type ?? canonical), storedRowDocument(row)), packageId: boundPackageOf(row.package_id) ?? null, organizationId: null, + answerFaults: true, }); + refused ??= refusal; } - return; + return refused; } if (healed) return; @@ -2073,7 +2088,10 @@ export class ProtocolRegistryHydrationFacet { // [#32366] Best-effort, never silent: the delete has committed and // is not failed here, and what stopped the walk is said once. console.error(registryHealStoppedMessage(type, name, error)); + // [#33851] …and answered: `revertCommit` reports it per item. + return { error }; } + return undefined; } /** @@ -2480,6 +2498,17 @@ export interface ObjectRegistryRefusal { readonly error: unknown; } +/** + * [#33851] What {@link ProtocolRegistryHydrationFacet.restoreArtifactRegistryView} + * answers when its walk stopped (a throw, logged at `error` as before) or a row + * still stored was refused by the registry: the thrown or refused value, whole. + * The row removal is already committed; this is the fact the heal used to keep + * to its log line. + */ +export interface RegistryHealStop { + readonly error: unknown; +} + /** * What {@link ProtocolRegistryHydrationFacet.applyRegistryWriteThrough} is * asked to make live: the row's type, name and body, its binding and scope. diff --git a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts index 324e6fdc3e1..9c57c09ac6c 100644 --- a/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts +++ b/packages/metadata-protocol/src/protocol.revert-commit-honest-outcome.test.ts @@ -616,3 +616,133 @@ describe('[#33851] revertCommit reports a non-object write-through fault in fail }); } }); + +// ═══════════════════════════════════════════════════════════════════════════ +// §4 [#33851] A removed item whose registry heal stops is a failed item too +// ═══════════════════════════════════════════════════════════════════════════ +// +// The soft-remove limb heals the registry after it removes the row +// (`restoreArtifactRegistryView`). A throw that stopped the heal was logged at +// `error` and not read, so the revert answered `{ success: true, action: +// 'removed' }` while the registry could still serve the removed row (measured +// on this harness before the fix). The heal now answers its stop, and the +// revert reports the item as §1 and §3 report theirs. The heal's `error` line +// is unchanged, and every other caller ignores the answer: the delete, save +// and publish controls answer what they answered before. +// +// So does a row still stored under another package that the heal registers +// again and the registry refuses. + +/** The non-object cases whose heal walks the overlay tiers (an extension resyncs instead). */ +const HEAL_CASES = NON_OBJECT_CASES.filter((c) => c.verb === 'registerItem'); + +/** Saved once, by the commit under revert: the revert soft-removes it. */ +async function nonObjectCreatedByTheCommit(c: NonObjectCase) { + const rig = await makeHydratingProtocol(c); + await rig.protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + recordApply(rig.commits, 'c1', [{ type: c.type, name: c.name, existedBefore: false, prevVersion: null }]); + return rig; +} + +/** The registry's tier-1 verbs throwing, which stops the heal's walk at its outer catch. */ +function healStops(engine: any, type: string) { + engine.registry.removePackageOverlaySlots = () => { throw REFUSAL(type); }; + engine.registry.removeRuntimeShadow = () => { throw REFUSAL(type); }; +} + +const healStoppedLine = (c: NonObjectCase) => + `[Protocol] the registry heal after the removal of ${c.type} '${c.name}' stopped: The registry is sealed for ${c.type} entries.`; + +describe('[#33851] revertCommit reports a removed item whose registry heal stops in failed[]', () => { + for (const c of HEAL_CASES) { + describe(c.type, () => { + it('control: a clean soft-remove reverts it and answers success', async () => { + const { protocol, rows } = await nonObjectCreatedByTheCommit(c); + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res).toMatchObject({ success: true, revertedCount: 1, failedCount: 0, failed: [] }); + expect(res.reverted).toEqual([{ type: c.type, name: c.name, action: 'removed' }]); + expect(storedLabelOf(rows, c)).toBeUndefined(); + }); + + it('a heal that stops: failed[], the removed row and the code named, success false, the error line kept', async () => { + const { protocol, rows, commits, engine } = await nonObjectCreatedByTheCommit(c); + const error = vi.spyOn(console, 'error').mockImplementation(() => {}); + healStops(engine, c.type); + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res.success).toBe(false); + expect(res.reverted).toEqual([]); + expect(res.failedCount).toBe(1); + expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); + expect(res.failed[0].error).toContain('its row was removed from sys_metadata'); + expect(res.failed[0].error).toContain('may still serve the removed row'); + expect(res.failed[0].error).toContain(`The registry is sealed for ${c.type} entries.`); + expect(error.mock.calls.some((a) => String(a[0]).startsWith(healStoppedLine(c)))).toBe(true); + // The row is gone, and the revert's own commit records it. + expect(storedLabelOf(rows, c)).toBeUndefined(); + expect(JSON.parse(revertsOf(commits, 'c1')[0].items)).toHaveLength(1); + }); + + it('control: a delete under the same fault answers as before, the stop only logged', async () => { + const { protocol, rows, engine } = await makeHydratingProtocol(c); + await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + const error = vi.spyOn(console, 'error').mockImplementation(() => {}); + healStops(engine, c.type); + + const res = await protocol.deleteMetaItem({ type: c.type, name: c.name, packageId: PKG }); + + expect(res.success).toBe(true); + expect(storedLabelOf(rows, c)).toBeUndefined(); + expect(error.mock.calls.some((a) => String(a[0]).startsWith(healStoppedLine(c)))).toBe(true); + }); + + it('control: a save and a publish under the same fault answer as before', async () => { + const { protocol, rows, engine } = await makeHydratingProtocol(c); + vi.spyOn(console, 'error').mockImplementation(() => {}); + healStops(engine, c.type); + + const saved = await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('Draft'), packageId: PKG, mode: 'draft' }); + const published = await protocol.publishMetaItem({ type: c.type, name: c.name, packageId: PKG }); + + expect(saved.success).toBe(true); + expect(saved.advisories ?? []).toEqual([]); + expect(published.success).toBe(true); + expect(published.advisories ?? []).toEqual([]); + expect(storedLabelOf(rows, c)).toBe('Draft'); + }); + }); + } + + it('a row still stored under another package that the registry refuses: failed[], success false', async () => { + // An `action`: a type two packages may each hold a row of under one name. + const c: NonObjectCase = { + type: 'action', name: 'close_ticket', verb: 'registerItem', labelOf: (body) => body.label, + body: (label) => ({ name: 'close_ticket', label, type: 'url', target: 'https://example.com/close' }), + }; + const OTHER = 'app.other'; + const { protocol, rows, commits, engine } = await makeHydratingProtocol(c); + engine.registry.getPackage = (id: string) => (id === PKG || id === OTHER ? { manifest: { id } } : undefined); + await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('Other'), packageId: OTHER }); + await protocol.saveMetaItem({ type: c.type, name: c.name, item: c.body('First'), packageId: PKG }); + recordApply(commits, 'c1', [{ type: c.type, name: c.name, existedBefore: false, prevVersion: null }]); + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const error = vi.spyOn(console, 'error').mockImplementation(() => {}); + engine.registry.registerItem = () => { throw REFUSAL(c.type); }; + + const res = await protocol.revertCommit({ commitId: 'c1', packageId: PKG }); + + expect(res.success).toBe(false); + expect(res.failed[0]).toMatchObject({ type: c.type, name: c.name, code: 'NOT_OVERRIDABLE' }); + expect(res.failed[0].error).toContain('its row was removed from sys_metadata'); + // Non-vacuity: the stop is the remaining row's write-through fault, not + // the walk's outer catch. + expect(warn.mock.calls.map((a) => String(a[0]))).toContain(writeThroughWarnLine(c)); + expect(error.mock.calls.some((a) => String(a[0]).startsWith(healStoppedLine(c)))).toBe(false); + // The other package's row stays stored. + expect(storedLabelOf(rows, c)).toBe('Other'); + }); +}); diff --git a/packages/metadata-protocol/src/protocol.ts b/packages/metadata-protocol/src/protocol.ts index b28c45d112c..ae548d425a6 100644 --- a/packages/metadata-protocol/src/protocol.ts +++ b/packages/metadata-protocol/src/protocol.ts @@ -615,7 +615,7 @@ import { ProtocolWriteGatesFacet } from './protocol-write-gates.js'; // [#29985 codemod] The static tables of the facet above: the class's fields read them (#30147). import { ProtocolWriteGatesTables } from './protocol-write-gates-tables.js'; // [#29985 codemod] Registry hydration, view expansion, write-through, object storage: the members below delegate to its facet, `ProtocolRegistryHydrationFacet`. -import { ProtocolRegistryHydrationFacet, type ObjectRegistryRefusal } from './protocol-registry-hydration.js'; +import { ProtocolRegistryHydrationFacet, type ObjectRegistryRefusal, type RegistryHealStop, type RegistryWriteThroughRequest } from './protocol-registry-hydration.js'; import type { HealPackageBinding } from './protocol-heal-binding.js'; // [#29985 codemod] Save refusals, saveMetaItem, saveConflict, migrateStoredMetadata: the members below delegate to its facet, `ProtocolSaveFacet`. import { ProtocolSaveFacet } from './protocol-save.js'; @@ -8396,20 +8396,7 @@ export class ObjectStackProtocolImplementation implements } /** Docblock and body: {@link ProtocolRegistryHydrationFacet.applyRegistryWriteThrough} in `protocol-registry-hydration.ts` [#29985 codemod]. */ - private async applyRegistryWriteThrough(request: { - type: string; - name: string; - item?: any; - packageId?: string | null; - /** The row's org scope — `null` for an env-wide row. [#6602] */ - organizationId: string | null; - /** - * [#23198] The binding the write moved the row from, when it moved it - * (an orphan adoption): `null` for the package-less row. See - * {@link HydrationOptions}. - */ - reboundFrom?: { readonly packageId: string | null }; - }): Promise { + private async applyRegistryWriteThrough(request: RegistryWriteThroughRequest): Promise { // [#29985 codemod] The body moved to `protocol-registry-hydration.ts`; it reaches this class through `protocol-host.ts`. return ProtocolRegistryHydrationFacet.applyRegistryWriteThrough(protocolHost(this), request); } @@ -8431,7 +8418,7 @@ export class ObjectStackProtocolImplementation implements * No effect for a type with no members. */ member?: string, - ): Promise { + ): Promise { // [#29985 codemod] The body moved to `protocol-registry-hydration.ts`; it reaches this class through `protocol-host.ts`. return ProtocolRegistryHydrationFacet.restoreArtifactRegistryView(protocolHost(this), type, name, organizationId, packageId, member); } @@ -10860,9 +10847,11 @@ export class ObjectStackProtocolImplementation implements * advisory stays on `advisories`), its mutation projector failed, or a * step after the row write threw. The entry names the row state (removed, * or restored to the body of version N) beside the step that failed, and - * the revert's own commit still records the row change. A write-through - * fault the registry helper only logs (every type but `object`) is not - * seen here. + * the revert's own commit still records the row change. + * [#33851] That holds for every type: a restored item whose registry + * write-through threw (not only an `object` the registry refused), and a + * removed item whose registry heal stopped, so the registry may still + * serve the removed row. * * [#33564, ADR-0067 D3] The revert's own commit records, per row it * changed, the version that row held before the revert (`prevVersion`), From 999b09d9c3724b90db62df71dfb52afcf73ec569 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 15 Nov 2026 15:27:31 +0000 Subject: [PATCH 7/7] chore(changeset): leave the earlier revert note as merged; say this change supersedes its sentence Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01QsR2jTkZnXtRhuEiiyidvJ --- .changeset/33563-revert-commit-honest-outcome.md | 2 +- .changeset/33851-revert-non-object-write-through-fault.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.changeset/33563-revert-commit-honest-outcome.md b/.changeset/33563-revert-commit-honest-outcome.md index 3b915a625a0..b87e1033042 100644 --- a/.changeset/33563-revert-commit-honest-outcome.md +++ b/.changeset/33563-revert-commit-honest-outcome.md @@ -9,7 +9,7 @@ Metadata-protocol: none `revertCommit` now reports an item whose row was written but whose next step did not land in `failed[]`, not `reverted[]`, and the answer's `success` is `false`. The steps are: the runtime registry refusing the restored object, its storage not following the restored body (the `object-storage-sync-refused` advisory stays on `advisories`), the mutation projector failing, and any step after the row write throwing. The entry names the row state ("its row was restored to the body of version N", or "its row was removed from sys_metadata") beside the step that failed, and quotes no driver text. The revert's own commit still records the row change. Before, each of these answered `success: true` with the item in `reverted[]`, against the method's own contract ("a revert that answers `success: true` is one the running process has already acted on"). `rollbackToPackageCommit` carries each such item into its own `failed[]` and answers `success: false`. -The same holds for a restored item of any other metadata type whose registry write-through throws, and for a removed item whose registry heal stops (see the note on reporting a non-object item's registry fault). +A write-through fault the registry helper only logs (every metadata type other than `object`) is still not seen by the revert. A revert is now itself revertible, as ADR-0067 D3 says. The revert's own commit records, for each row it changed, the version that row held before the revert, so reverting the revert brings that body back, and an item the revert removed is written again. An item recorded as existing before the commit but carrying no version to restore, which is how every revert commit recorded by an earlier release records the items it restored, is named in `failed[]` with nothing written. Before, it was skipped: it appeared in neither `reverted[]` nor `failed[]`. To undo such an older revert, restore each item from its own version history (`GET /api/v1/meta/:type/:name/history`, then `POST /api/v1/meta/:type/:name/rollback`). diff --git a/.changeset/33851-revert-non-object-write-through-fault.md b/.changeset/33851-revert-non-object-write-through-fault.md index fb9d7084c8a..8a3835c99b6 100644 --- a/.changeset/33851-revert-non-object-write-through-fault.md +++ b/.changeset/33851-revert-non-object-write-through-fault.md @@ -11,4 +11,6 @@ Metadata-protocol: none A removed item is reported the same way. When the revert soft-removes an item the reverted commit created and the registry heal after the removal stops (a registry throw, or the registry refusing a row of the item still stored under another package), the item goes into `failed[]` naming "its row was removed from sys_metadata" and that the registry may still serve the removed row, with the reason and its `code`. Before, the heal's stop was only an `error` line in the server log, and the item answered `removed`. The `error` line is unchanged. +This supersedes the sentence of the note on the previous change to this door that says a write-through fault of every type other than `object` "is still not seen by the revert": after this change, the revert sees it, and a stopped heal too. + Save, publish and delete do not change. Save and publish do not ask the write-through for these faults: under the same fault, `saveMetaItem` and `publishMetaItem` of a non-object item still answer success with no advisory, and the fault is still the same `warn` line in the server log. `deleteMetaItem`, a publish's undo and a peer's convergence ignore the heal's answer, so a stopped heal still answers what it answered before there, with the same `error` line.