Skip to content

Commit 7f03663

Browse files
committed
fix(metadata-protocol): a commit revert's restore judges a pair row by the override write gate and writes the committing package's row when it is gone
Claude-Session: https://claude.ai/code/session_01JQwxbZ5jYNfPGLvPV8LYRe Co-authored-by: Claude <noreply@anthropic.com>
1 parent 55837b7 commit 7f03663

3 files changed

Lines changed: 139 additions & 52 deletions

File tree

‎packages/metadata-protocol/src/protocol.named-base-overlay-write.test.ts‎

Lines changed: 59 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -516,24 +516,77 @@ describe('the commit doors: restoring a row bound to the base is closed, removin
516516
]);
517517
});
518518

519-
it('[#29414] a revert of the base\'s edit commit whose row was since deleted is refused by the package-less close, as the per-item rollback is; nothing is written', async () => {
519+
it('[#29414] a revert of the base\'s edit commit whose row was since deleted restores into the base\'s own row, so the named-base close refuses it; nothing is written', async () => {
520520
const { protocol, rows } = makeProtocol();
521521
await intoBaseBeforeClose(protocol, 'First');
522522
const edit = await intoBaseBeforeClose(protocol, 'Second');
523523
expect(await protocol.deleteMetaItem({ type: VIEW.type, name: VIEW.name, packageId: BASE })).toMatchObject({ success: true });
524524
expect(rows(VIEW.type, VIEW.name)).toEqual([]);
525-
// The per-item rollback on the same `null` binding: the one predicate, its rollback sentence.
526-
const rollback = await thrown(() => protocol.rollbackMetaItem({ type: VIEW.type, name: VIEW.name, toVersion: 1 }));
527-
expect(resolveThrownHttpError(rollback)).toMatchObject({ status: 403, code: 'NOT_OVERRIDABLE' });
528525

529526
tick();
530527
const result = await protocol.revertCommit({ commitId: edit, packageId: BASE, actor: 'admin' });
531528

532529
expect(result).toMatchObject({ success: false, revertedCount: 0, failedCount: 1, reverted: [] });
533530
expect(result.failed).toEqual([expect.objectContaining({ type: VIEW.type, name: VIEW.name, code: 'NOT_OVERRIDABLE' })]);
534-
expect(result.failed[0].error).toBe(rollback.message);
535-
expect(result.failed[0].error).toContain('a rollback of its package-less row is closed');
531+
expectClosedSentence(result.failed[0].error, VIEW.type, VIEW.name, 'rollback');
536532
expect(rows(VIEW.type, VIEW.name)).toEqual([]);
537533
expect((await protocol.getMetaItem({ type: VIEW.type, name: VIEW.name })).item.label).toBe(PACKAGED);
538534
});
535+
536+
it('[#29414] a pair commit recorded before #29414 beside a row bound to the base names the base row\'s version: its revert is refused by the override write gate, and the pair\'s declared row is unchanged', async () => {
537+
const { protocol, rows } = makeProtocol();
538+
await intoBaseBeforeClose(protocol, 'BaseRow');
539+
const created = await publishCommit(protocol, PAIR, declared('PairFirst'));
540+
// The plan such a commit recorded before #29414: the base row's version, read off any package's row.
541+
const engine = protocol.engine;
542+
const baseVersion = (await engine.findOne('sys_metadata', { where: { type: VIEW.type, name: VIEW.name, state: 'active', package_id: BASE } })).version;
543+
expect(typeof baseVersion).toBe('number');
544+
await engine.update('sys_metadata_commit', {
545+
items: JSON.stringify([{ type: VIEW.type, name: VIEW.name, existedBefore: true, prevVersion: baseVersion }]),
546+
}, { where: { id: created } });
547+
expect(await planOf(protocol, PAIR, created)).toEqual([
548+
expect.objectContaining({ existedBefore: true, prevVersion: baseVersion }),
549+
]);
550+
551+
tick();
552+
const result = await protocol.revertCommit({ commitId: created, packageId: PAIR, actor: 'admin' });
553+
554+
expect(result).toMatchObject({ success: false, revertedCount: 0, failedCount: 1, reverted: [] });
555+
expect(result.failed).toEqual([expect.objectContaining({ type: VIEW.type, name: VIEW.name, code: 'NOT_OVERRIDABLE' })]);
556+
expect(rows(VIEW.type, VIEW.name)).toEqual([
557+
{ package_id: BASE, state: 'active', label: 'BaseRow' },
558+
{ package_id: PAIR, state: 'active', label: 'PairFirst' },
559+
]);
560+
const pairRow = await engine.findOne('sys_metadata', { where: { type: VIEW.type, name: VIEW.name, state: 'active', package_id: PAIR } });
561+
expect(JSON.parse(pairRow.metadata).overrides).toEqual({ package: BASE, basedOn: BASE_VERSION });
562+
expect((await protocol.getMetaItem({ type: VIEW.type, name: VIEW.name })).item.label).toBe('PairFirst');
563+
});
564+
565+
it('[#29414] CONTROL: the pair\'s edit commit whose row was since deleted restores the pair\'s declared row again', async () => {
566+
const { protocol, rows } = makeProtocol();
567+
await publishCommit(protocol, PAIR, declared('PairFirst'));
568+
const edit = await publishCommit(protocol, PAIR, declared('PairSecond'));
569+
expect(await protocol.deleteMetaItem({ type: VIEW.type, name: VIEW.name, packageId: PAIR })).toMatchObject({ success: true });
570+
expect(rows(VIEW.type, VIEW.name)).toEqual([]);
571+
572+
tick();
573+
const result = await protocol.revertCommit({ commitId: edit, packageId: PAIR, actor: 'admin' });
574+
575+
expect(result).toMatchObject({ success: true, revertedCount: 1, failed: [], reverted: [{ type: VIEW.type, name: VIEW.name, action: 'restored' }] });
576+
expect(rows(VIEW.type, VIEW.name)).toEqual([{ package_id: PAIR, state: 'active', label: 'PairFirst' }]);
577+
expect((await protocol.getMetaItem({ type: VIEW.type, name: VIEW.name })).item.label).toBe('PairFirst');
578+
});
579+
580+
it('[#29414] CONTROL: a writable package\'s edit commit whose row was since deleted restores into that package\'s row, never a package-less one', async () => {
581+
const { protocol, rows } = makeProtocol();
582+
await publishCommit(protocol, WRITABLE, VIEW.body('First'));
583+
const edit = await publishCommit(protocol, WRITABLE, VIEW.body('Second'));
584+
expect(await protocol.deleteMetaItem({ type: VIEW.type, name: VIEW.name, packageId: WRITABLE })).toMatchObject({ success: true });
585+
586+
tick();
587+
const result = await protocol.revertCommit({ commitId: edit, packageId: WRITABLE, actor: 'admin' });
588+
589+
expect(result).toMatchObject({ success: true, revertedCount: 1, failed: [], reverted: [{ type: VIEW.type, name: VIEW.name, action: 'restored' }] });
590+
expect(rows(VIEW.type, VIEW.name)).toEqual([{ package_id: WRITABLE, state: 'active', label: 'First' }]);
591+
});
539592
});

‎packages/metadata-protocol/src/protocol.ts‎

Lines changed: 74 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1512,6 +1512,45 @@ export class ObjectStackProtocolImplementation implements
15121512
return restoredBodyWriter.call(host, type, name, binding, source);
15131513
}
15141514

1515+
/**
1516+
* [ADR-0146 D2] The write intent and the body writer of a restore into
1517+
* the row `binding` names — the per-item rollback's ({@link rollbackMetaItem})
1518+
* and [#29414] a commit revert's restore limb ({@link revertCommit}), one
1519+
* derivation for both.
1520+
*
1521+
* A restore into the base's paired `.custom` row is the pair's declared
1522+
* override, as its save is: it edits no managed item, so the store is told
1523+
* a runtime-only write, and the restored body is judged by the override
1524+
* write gate into the pair ({@link overrideWriteVerdict}). A version that
1525+
* declares no override (a body the base row stored, which a commit plan
1526+
* recorded before #29414 can name) is refused as the save is
1527+
* (`overrideWriteRefusalError`, `403 NOT_OVERRIDABLE`), thrown from inside
1528+
* `deriveRestoredBody`, so nothing is written. Any other binding: the
1529+
* caller's `artifactBacked` decides the intent, and the body writer is
1530+
* {@link restoredBodyWriter}'s alone.
1531+
*/
1532+
private restoreWriteFor(
1533+
singularType: string,
1534+
name: string,
1535+
binding: string | null,
1536+
artifactBacked: boolean,
1537+
source: string,
1538+
): { intent: 'override-artifact' | 'runtime-only'; deriveRestoredBody: (historyBody: unknown) => Promise<unknown> } {
1539+
const owner = artifactBacked ? this.packagedArtifactOwner({ type: singularType, name }) : undefined;
1540+
const pairRow = owner !== undefined && isCustomizationPairOf(binding, owner);
1541+
const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !pairRow ? 'override-artifact' : 'runtime-only';
1542+
const writeRestored = this.restoredBodyWriter(singularType, name, binding, source);
1543+
const deriveRestoredBody = pairRow
1544+
? async (historyBody: unknown): Promise<unknown> => {
1545+
const body = await writeRestored(historyBody);
1546+
const verdict = this.overrideWriteVerdict({ type: singularType, name, packageId: binding, item: body });
1547+
if (verdict.verdict === 'refuse') throw overrideWriteRefusalError(verdict);
1548+
return body;
1549+
}
1550+
: writeRestored;
1551+
return { intent, deriveRestoredBody };
1552+
}
1553+
15151554
/**
15161555
* [#25278] The save door's refusal family, asked of a history body a
15171556
* restore is about to make the active row.
@@ -19965,9 +20004,13 @@ export class ObjectStackProtocolImplementation implements
1996520004
* (`package_id` = the commit's), as the plan {@link publishPackageDrafts}
1996620005
* records describes it: a pair commit beside a row bound to its read-only
1996720006
* base removes or restores the pair's row and leaves the base's served.
19968-
* A restore whose row is gone writes the package-less row, so it asks the
19969-
* package-less close ({@link packagelessOverlayWriteRefusal}) on that
19970-
* `null` binding exactly as {@link rollbackMetaItem} does.
20007+
* The restore writes the committing package's row, in place or created
20008+
* again when it was deleted since, so this door never writes the
20009+
* package-less row; a commit of the read-only base itself is refused by
20010+
* the #29390 close. A restore into the base's paired `.custom` row is judged
20011+
* by the override write gate as {@link rollbackMetaItem} judges it
20012+
* ({@link restoreWriteFor}): a version declaring no override is refused
20013+
* into `failed[]`.
1997120014
*/
1997220015
async revertCommit(request: {
1997320016
commitId: string;
@@ -20311,8 +20354,18 @@ export class ObjectStackProtocolImplementation implements
2031120354
// The soft-remove limb above stated the same intent as a
2031220355
// CONSTANT and was fixed the same way (#6620), so both limbs now
2031320356
// derive it. The registry half of both is #6621, below.
20314-
const intent: 'override-artifact' | 'runtime-only' =
20315-
this.isArtifactBacked(it.type, it.name) ? 'override-artifact' : 'runtime-only';
20357+
//
20358+
// [#29414, ADR-0146 D2] …and a restore into the base's paired
20359+
// `.custom` row is the pair's declared override, judged by the
20360+
// override write gate exactly as {@link rollbackMetaItem}
20361+
// judges it ({@link restoreWriteFor}, one derivation): a
20362+
// version that declares no override — the base row's body a
20363+
// plan recorded before #29414 names as the pair's pre-commit
20364+
// version — is refused into `failed[]`, nothing written.
20365+
const { intent, deriveRestoredBody } = this.restoreWriteFor(
20366+
PLURAL_TO_SINGULAR[it.type] ?? it.type, it.name, commitPackageId,
20367+
this.isArtifactBacked(it.type, it.name), 'protocol.revertCommit',
20368+
);
2031620369
// [#6621 / #4636] The ownership key the write-through needs,
2031720370
// read from the ROW rather than from the request — the sibling
2031820371
// revert caller {@link rollbackMetaItem} reads it exactly this
@@ -20332,25 +20385,16 @@ export class ObjectStackProtocolImplementation implements
2033220385
// the shape that ends in a `catch {}` swallowing a real outage
2033320386
// (#4867). Per ITEM, because a batch mixes bindings.
2033420387
//
20335-
// [#29414] The binding is the committing package's own row's
20336-
// (`current`, read under `commitPackageId` above), not any
20337-
// package's: `commitPackageId` when that row is stored, `null`
20338-
// when it is not (deleted since the commit), which is what
20339-
// `restoreVersion` then writes — the package-unbound row, as
20340-
// the per-item rollback writes it.
20341-
const restorePackageId: string | null = current ? commitPackageId : null;
20342-
// [#29414, ADR-0146 D11] …so a restore whose row is gone
20343-
// writes the package-less row, and is asked the package-less
20344-
// close exactly as {@link rollbackMetaItem} asks it on the
20345-
// same `null` binding ({@link packagelessOverlayWriteRefusal},
20346-
// its rollback sentence): an overlay type's item the
20347-
// read-only base ships is refused into `failed[]` with
20348-
// nothing written. A binding naming a package leaves it open.
20349-
const closed = await this.packagelessOverlayWriteRefusal(
20350-
{ type: PLURAL_TO_SINGULAR[it.type] ?? it.type, name: it.name, packageId: restorePackageId, state: 'active', ...memberOption(member) },
20351-
'rollback',
20352-
);
20353-
if (closed) throw closed;
20388+
// [#29414, ADR-0048, ADR-0067 D3] The binding is the
20389+
// committing package's, never another package's row's: the
20390+
// restore writes the committing package's own row, in place
20391+
// when it is stored and created again when it was deleted
20392+
// since (`restoreVersion` is handed `commitPackageId` and
20393+
// writes it either way). So this door never writes the
20394+
// package-less row, and the package-less close has nothing
20395+
// here to judge (every commit names its package); the write
20396+
// naming the read-only base itself is closed below.
20397+
const restorePackageId: string = commitPackageId;
2035420398
// [#29390, ADR-0146 D1, D11] A restore writes the row this
2035520399
// binding names, so a restore into a row bound to the
2035620400
// read-only base itself (a commit recorded before #28905
@@ -20380,9 +20424,8 @@ export class ObjectStackProtocolImplementation implements
2038020424
// in `failed[]` below, with nothing written. Judged under
2038120425
// the SINGULAR type, the spelling the write-through
2038220426
// registers under. See {@link restoredBodyWriter}.
20383-
deriveRestoredBody: this.restoredBodyWriter(
20384-
PLURAL_TO_SINGULAR[it.type] ?? it.type, it.name, restorePackageId, 'protocol.revertCommit',
20385-
),
20427+
// [ADR-0146 D2] …and, for the pair's row, the override write gate.
20428+
deriveRestoredBody,
2038620429
...memberOption(member),
2038720430
});
2038820431
// [#6621] #4521 — a revert is a live write like any other: the
@@ -20772,21 +20815,10 @@ export class ObjectStackProtocolImplementation implements
2077220815
// the override write gate as that save is ({@link overrideWriteVerdict}
2077320816
// into the pair): a version that declares no override is refused as
2077420817
// the save is, with nothing written.
20775-
const owner = artifactBacked ? this.packagedArtifactOwner({ type: singularType, name: request.name }) : undefined;
20776-
const pairRowRollback = owner !== undefined && isCustomizationPairOf(rollbackPackageId, owner);
20777-
const intent: 'override-artifact' | 'runtime-only' = artifactBacked && !pairRowRollback
20778-
? 'override-artifact' : 'runtime-only';
20779-
const writeRestored = this.restoredBodyWriter(singularType, request.name, rollbackPackageId, 'protocol.rollbackMetaItem');
20780-
const deriveRestoredBody = pairRowRollback
20781-
? async (historyBody: unknown): Promise<unknown> => {
20782-
const body = await writeRestored(historyBody);
20783-
const verdict = this.overrideWriteVerdict({
20784-
type: singularType, name: request.name, packageId: rollbackPackageId, item: body,
20785-
});
20786-
if (verdict.verdict === 'refuse') throw overrideWriteRefusalError(verdict);
20787-
return body;
20788-
}
20789-
: writeRestored;
20818+
// [#29414] The derivation a commit revert's restore limb shares ({@link restoreWriteFor}).
20819+
const { intent, deriveRestoredBody } = this.restoreWriteFor(
20820+
singularType, request.name, rollbackPackageId, artifactBacked, 'protocol.rollbackMetaItem',
20821+
);
2079020822
try {
2079120823
const result = await repo.restoreVersion(ref, request.toVersion, {
2079220824
// #4556 — NULL, not 'system', for an actor-less rollback.

‎packages/metadata-protocol/src/sys-metadata-repository.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1687,9 +1687,10 @@ export class SysMetadataRepository implements MetadataRepository {
16871687
* [#29414] The package whose active row is restored. Stated → the
16881688
* active row (its parent hash and its binding) is resolved under the
16891689
* ADR-0048 key `(org, type, name, package_id)`, so another package's
1690-
* row of the same name is never the one restored; no such row → the
1691-
* unbound row, as below. Omitted → the "match any package" resolution,
1692-
* as before. A LOCAL extension, as on {@link delete}.
1690+
* row of the same name is never the one restored, and the restore is
1691+
* written under it, creating that package's row again when it is gone.
1692+
* Omitted → the "match any package" resolution and, with no active row,
1693+
* the unbound row, as before. A LOCAL extension, as on {@link delete}.
16931694
*/
16941695
packageId?: string | null;
16951696
},
@@ -1764,7 +1765,8 @@ export class SysMetadataRepository implements MetadataRepository {
17641765
intent: opts.intent ?? 'override-artifact',
17651766
state: 'active',
17661767
opType: 'revert',
1767-
packageId: activePackageId,
1768+
// [#29414] The stated package's row, found or not.
1769+
packageId: 'packageId' in opts ? (opts.packageId ?? null) : activePackageId,
17681770
});
17691771
}
17701772

0 commit comments

Comments
 (0)