Files
clean-architecture-frontend…/tests/unit/registry-compatibility.test.ts
T
DongHyeonka 605fd17d9f fix(registry): 무효화 그래프에 더하기만 한 변경을 additive로 분류한다 (0929/07-02)
문제
FE-REG-QUERY-INVALIDATION은 무효화 그래프를 행 하나(invalidation-graph)로
투영하고 topics·namespaces·edges를 breakingFields로 둔다. 분류기는 배열에서
빠진 원소가 없으면 field-changed로 보고 breakingFields로 등급을 정한다. 그래서
topic 하나, namespace 하나, edge 하나를 더하기만 해도 breaking 3건이 되고
기준선 재승인이나 breaking 증거가 필요하다. 서버 상태를 쓰는 기능은 모두
topic을 달기 때문에 기능을 하나 추가할 때마다 사람이 재승인해야 한다(1101
리뷰 16 영역 2.1절: P-07-02가 남았고 범위가 더 넓다).

고른 방법 (오케스트레이터 결정 1)
- governance의 snapshotProjection.canonicalArrayKeyFields에 있는 필드는
  키로 식별되는 원소 집합이다. 이 필드에서 원소가 빠지지 않았으면
  set-items-added(additive)로 분류한다. 다른 레지스트리의 "행 추가"와 같은
  성격이다. 이전 집합의 원소를 읽던 소비자는 모두 그대로 찾는다. 무효화가
  늘어날 뿐이다.
- 원소를 빼거나 바꾸면 지금처럼 allowed-value-removed(breaking)다. 이 분기는
  새 분기보다 먼저 판정된다.
- 0929/07-02(82c9e59)의 의도와 맞는지 확인했다. 그 커밋은 "이전에 유효하던
  값이 모두 유효하게 남는 변경"(null 전환, allowedValues 확장)을 breaking에서
  뺐고, 새·빠진·좁아진 제한은 breaking으로 남겼다. 이번 변경도 같은 기준이다.
  1101/07-02(3c31576)는 V2/V3 parity 테스트라 레지스트리 분류와 겹치지 않는다.

버린 대안
- registryId(FE-REG-QUERY-INVALIDATION)를 분류기에 적기: 분류 규칙이
  governance 밖에 숨는다.
- governance에 새 필드(예: additiveSetFields)를 두거나 breakingFields에서
  세 필드를 빼기: $contract가 바뀌어 기준선 재승인이 필요하다. 빼기만 하면
  behavior-change가 되어 결정(additive)과도 다르다.
- 뼈대·기능에서 topic을 빼기: 실제 기능에서 같은 문제가 다시 난다.
- 기능마다 재승인: 사람 승인이 기능 추가 비용이 된다.

위험·한계
- 게이트 판정이 바뀐다. 다운스트림에서 snapshotProjection을 쓰는
  레지스트리는 키 집합에 원소를 더해도 breaking 증거를 요구하지 않는다.
  다운스트림이 이런 추가에 적어 둔 breaking 증거 행은 이제 맞는 변경이 없어
  0929/07-01 규칙대로 stale로 실패한다. update:registry-baseline으로 지운다.
- governance의 breakingFields에 topics·namespaces·edges가 남아 있지만 이
  세 필드에서는 더 이상 판정을 바꾸지 않는다(빼기·바꾸기는 그 전에
  breaking이다). 지우면 $contract 변경이라 기준선 재승인과 함께 할 일이다.
- 투영된 키 집합의 순서만 바뀐 경우도 additive로 분류된다.
  check-registries가 키 순서로 정렬해 투영하므로 실제로는 생기지 않는다.
- 키 경로가 점을 포함한 필드(a.b)는 행 최상위 필드 이름과 맞지 않아 지금처럼
  breakingFields로 판정한다.

검증
- RED(수정 전): registry-compatibility.test.ts "grades a topic, namespace
  and edge added to the graph as additive" 실패. 커밋된 기준선에 topic·
  namespace·edge를 하나씩 더한 스냅샷이 [edges, breaking], [namespaces,
  breaking], [topics, breaking]로 분류됐다. 빼기·바꾸기 4건은 통과(breaking).
- GREEN: 같은 파일 23건 통과. registry-governance(무효화 원소 변조 4건이
  여전히 breaking)·second-api-feature-registries 포함 33건 통과.
  check-registry-compatibility-fixtures 11 PASS. check-registries "11
  registries PASS; compatibility=none".
- 회귀: tests/unit 178파일 중 177 통과. 실패 1건
  feature-shape-growth(초기 JS 증가 1036 > 1024 B)는 이 변경을 빼고 돌려도
  실패한다(1042 B, 기준 커밋의 기존 상태). tsc node·test rc=0, 바꾼 파일
  eslint rc=0.
- 미실행: check:architecture(pnpm 필요).

Refs: docs/reviews/2026-11-01-maturity-review/16-structure-patterns.md 2.1, 16-01
Refs: docs/reviews/2026-09-29-maturity-review/07-contracts.md 07-02
2026-11-03 01:50:12 +09:00

306 lines
11 KiB
TypeScript

import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import {
canonicalRegistryJson,
diffRegistrySnapshots,
registrySnapshotDigest,
validateBreakingEvidence,
verifyRegistryBaselineApproval,
} from "../../scripts/lib/registry-compatibility.ts";
function snapshot(
rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>,
) {
return {
schemaVersion: 2,
registries: [
{
registryId: "FE-REG-TEST",
contract: { breakingFields: ["path"] },
rows,
},
],
};
}
describe("registry compatibility evidence", () => {
it("canonicalizes object and primitive-array ordering", () => {
expect(
canonicalRegistryJson({
second: ["b", "a"],
first: { z: 1, a: 2 },
}),
).toBe('{"first":{"a":2,"z":1},"second":["a","b"]}');
});
it("classifies additive, behavioral and breaking actual diffs", () => {
expect(
diffRegistrySnapshots(
snapshot({ A: { path: "/a" } }),
snapshot({ A: { path: "/a" }, B: { path: "/b" } }),
).impact,
).toBe("additive");
expect(
diffRegistrySnapshots(
snapshot({ A: { path: "/a", owner: "one" } }),
snapshot({ A: { path: "/a", owner: "two" } }),
).impact,
).toBe("behavior-change");
expect(
diffRegistrySnapshots(
snapshot({ A: { path: "/a" } }),
snapshot({ A: { path: "/moved" } }),
).impact,
).toBe("breaking");
expect(
diffRegistrySnapshots(
snapshot({ A: { path: "/a" } }),
snapshot({}),
).impact,
).toBe("breaking");
});
// 0929/07-02. Changes the governance contract already describes are graded
// by it; anything else stays fail-closed.
describe("changes the declared contract describes", () => {
function registry(
contract: Readonly<Record<string, unknown>>,
rows: Readonly<Record<string, Readonly<Record<string, unknown>>>>,
) {
return {
schemaVersion: 2,
registries: [{ registryId: "FE-REG-TEST", contract, rows }],
};
}
const nullable = {
breakingFields: ["path", "schema"],
fieldTypes: {
path: "string",
label: "string|null",
order: "integer|null",
schema: "string|null",
},
};
it.each([
["a label hidden", { label: "Home" }, { label: null }, "behavior-change", "field-changed"],
["a label shown", { label: null }, { label: "Home" }, "behavior-change", "field-changed"],
["an order set", { order: null }, { order: 2 }, "behavior-change", "field-changed"],
["a nullable breaking field set", { schema: null }, { schema: "Params" }, "breaking", "field-changed"],
["a value outside the declared type", { order: null }, { order: "2" }, "breaking", "field-type-changed"],
])("grades %s by the declared field type", (_label, before, after, impact, kind) => {
const diff = diffRegistrySnapshots(
registry(nullable, { A: { path: "/a", ...before } }),
registry(nullable, { A: { path: "/a", ...after } }),
);
expect(diff.changes.map((change) => [change.kind, change.impact])).toEqual([
[kind, impact],
]);
});
it("keeps a null transition breaking when no field type is declared", () => {
expect(
diffRegistrySnapshots(
registry({ breakingFields: ["path"] }, { A: { path: "/a", label: "Home" } }),
registry({ breakingFields: ["path"] }, { A: { path: "/a", label: null } }),
).impact,
).toBe("breaking");
});
it.each([
["one more allowed value", { kind: ["one"] }, { kind: ["one", "two"] }, "additive"],
["an allowed value removed", { kind: ["one", "two"] }, { kind: ["two", "three"] }, "breaking"],
["a newly restricted field", { kind: ["one"] }, { kind: ["one"], mode: ["a"] }, "breaking"],
["a restriction dropped", { kind: ["one"], mode: ["a"] }, { kind: ["one"] }, "breaking"],
])("grades %s in allowedValues", (_label, before, after, impact) => {
const diff = diffRegistrySnapshots(
registry({ breakingFields: ["path"], allowedValues: before }, { A: { path: "/a" } }),
registry({ breakingFields: ["path"], allowedValues: after }, { A: { path: "/a" } }),
);
expect(diff.impact).toBe(impact);
});
});
// 1101/16-01 (decision 1). Every feature with server state adds a topic, so
// adding one must not need a new baseline. The committed baseline is used
// as it stands: after the sample's removal its graph may be empty.
describe("the invalidation graph in the committed baseline", () => {
type Graph = { topics: unknown[]; namespaces: unknown[]; edges: unknown[] };
type Snapshot = {
registries: Array<{ registryId: string; rows: Record<string, Graph> }>;
};
const baseline = JSON.parse(
readFileSync("config/contracts/registry-baseline.json", "utf8"),
) as Snapshot;
const namespace = { namespaceId: "added-namespace", namespaceVersion: 1 };
const topicId = "qinv.01k9zaddedtopic000000000";
function withGraph(snapshot: Snapshot, edit: (graph: Graph) => void): Snapshot {
const copy = structuredClone(snapshot);
const graph = copy.registries.find(
({ registryId }) => registryId === "FE-REG-QUERY-INVALIDATION",
)?.rows["invalidation-graph"];
if (!graph) throw new Error("baseline has no invalidation graph");
edit(graph);
return copy;
}
const extended = withGraph(baseline, (graph) => {
graph.topics.push(topicId);
graph.namespaces.push(namespace);
graph.edges.push({ topicId, namespace });
});
it("grades a topic, namespace and edge added to the graph as additive", () => {
const diff = diffRegistrySnapshots(baseline, extended);
expect(diff.changes.map(({ field, impact }) => [field, impact])).toEqual([
["edges", "additive"],
["namespaces", "additive"],
["topics", "additive"],
]);
expect(diff.impact).toBe("additive");
});
it.each([
["a topic removed", (graph: Graph) => graph.topics.splice(graph.topics.indexOf(topicId), 1)],
["an edge removed", (graph: Graph) => graph.edges.pop()],
[
"a namespace version changed",
(graph: Graph) => {
graph.namespaces[graph.namespaces.length - 1] = { ...namespace, namespaceVersion: 2 };
},
],
[
"an edge moved to another topic",
(graph: Graph) => {
graph.edges[graph.edges.length - 1] = { topicId: "qinv.01k9zothertopic000000000", namespace };
},
],
])("keeps %s breaking", (_label, edit) => {
expect(diffRegistrySnapshots(extended, withGraph(extended, edit)).impact).toBe("breaking");
});
});
it("verifies the approved digest and complete breaking evidence", () => {
const before = snapshot({ A: { path: "/before" } });
const after = snapshot({ A: { path: "/after" } });
const digest = registrySnapshotDigest(before);
expect(
verifyRegistryBaselineApproval(before, {
schemaVersion: 1,
snapshotDigest: digest,
owner: "platform",
approvedAt: "2026-07-26T00:00:00.000Z",
}).passed,
).toBe(true);
expect(
verifyRegistryBaselineApproval(before, {
schemaVersion: 1,
snapshotDigest: "tampered",
owner: "platform",
approvedAt: "2026-07-26T00:00:00.000Z",
}).passed,
).toBe(false);
const diff = diffRegistrySnapshots(before, after);
expect(validateBreakingEvidence(diff, { changes: [] }).passed).toBe(false);
const changeId = diff.changes[0]?.changeId;
expect(
validateBreakingEvidence(diff, {
changes: [
{
changeId,
after: "/after",
versionBump: "2",
migration: "dual-read",
compatibilityWindow: "one release",
rollback: "restore previous registry snapshot",
owner: "platform",
},
],
}).passed,
).toBe(true);
});
// 0929/07-01. Evidence is for one value, not for every later change of the
// same row and field.
describe("evidence bound to the value it explains", () => {
const evidence = (extra: Readonly<Record<string, unknown>>) => ({
changes: [
{
changeId: "FE-REG-TEST:A:path:field-changed",
versionBump: "2",
migration: "dual-read",
compatibilityWindow: "one release",
rollback: "restore previous registry snapshot",
owner: "platform",
...extra,
},
],
});
const moved = diffRegistrySnapshots(
snapshot({ A: { path: "/a" } }),
snapshot({ A: { path: "/entries" } }),
);
it("rejects evidence written for another value of the same field", () => {
expect(validateBreakingEvidence(moved, evidence({ after: "/items" })).failures).toEqual([
'breaking change FE-REG-TEST:A:path:field-changed evidence explains after="/items", the change is after="/entries"',
]);
});
it("requires the explained value", () => {
expect(validateBreakingEvidence(moved, evidence({})).failures).toEqual([
"breaking change FE-REG-TEST:A:path:field-changed evidence needs after (the canonical JSON value it explains)",
]);
});
it("compares canonical values, so key and primitive order do not matter", () => {
const reordered = diffRegistrySnapshots(
snapshot({ A: { path: { b: ["y", "x"], a: 1 } } }),
snapshot({ A: { path: { a: 2, b: ["x", "y"] } } }),
);
expect(
validateBreakingEvidence(reordered, evidence({ after: { b: ["y", "x"], a: 2 } })).passed,
).toBe(true);
});
// 0929/07-01 (2). A row that explains no breaking change of the current
// diff fails the gate, and the message names every such row.
it("fails on evidence rows that explain no breaking change of the current diff", () => {
const diff = diffRegistrySnapshots(
snapshot({ A: { path: "/a", owner: "one" } }),
snapshot({ A: { path: "/entries", owner: "two" } }),
);
const row = (changeId: string, after?: string) => ({
...evidence(after === undefined ? {} : { after }).changes[0],
changeId,
});
expect(
validateBreakingEvidence(diff, {
changes: [
row("FE-REG-TEST:A:path:field-changed", "/entries"),
row("FE-REG-TEST:B:*:removed"),
row("FE-REG-TEST:A:owner:field-changed", "two"),
],
}).failures,
).toEqual([
"stale breaking evidence FE-REG-TEST:B:*:removed: no breaking change in the current diff has this changeId. Delete the row (update:registry-baseline deletes the rows a new baseline explains)",
"stale breaking evidence FE-REG-TEST:A:owner:field-changed: no breaking change in the current diff has this changeId. Delete the row (update:registry-baseline deletes the rows a new baseline explains)",
]);
});
it("needs no value for a removal", () => {
const removed = diffRegistrySnapshots(
snapshot({ A: { path: "/a" } }),
snapshot({}),
);
expect(
validateBreakingEvidence(removed, {
changes: [{ ...evidence({}).changes[0], changeId: "FE-REG-TEST:A:*:removed" }],
}).passed,
).toBe(true);
});
});
});