Files
clean-architecture-frontend…/scripts/lib/registry-compatibility.ts
T
DongHyeonka 4ada84e1ec fix(registry): 맞는 변경이 없는 breaking 증거 행을 실패로 막는다 (0929/07-01)
문제
check:registries는 증거 행이 지금 diff의 어느 breaking 변경을 설명하는지
보지 않는다. 증거 파일 17건 중 14건이 지금 diff의 어떤 changeId와도 맞지
않았다(예: FE-REG-ERROR:QUERY_CACHE_FAILURE:telemetryEvent:field-changed,
그 필드는 07-04 이후 없다). update:registry-baseline은 기준선을 새로 찍어도
증거 행을 그대로 두므로 오래된 행이 계속 쌓인다. 5e6be9a가 리뷰 개선
(1)(증거를 값에 묶기)만 했고 (2)·(3)이 남았다.

고른 방법 (2026-11-03 결정)
- (2) validateBreakingEvidence가 지금 diff의 breaking 변경과 changeId가
  맞지 않는 증거 행마다 "stale breaking evidence <changeId>: ..."로
  실패한다. 메시지에 지울 행과 update:registry-baseline이 지운다는 사실을
  적는다. breaking이 아닌 변경(behavior-change 등)과 맞는 행도 오래된
  행으로 본다. 증거는 breaking 변경에만 쓰기 때문이다.
- (3) update:registry-baseline이 승인 파일을 쓴 뒤 증거 행을 모두 지우고,
  지운 changeId를 출력한다. 새 기준선은 지금 스냅샷이라 증거가 설명하던
  변경을 모두 흡수한다. 남은 행은 어떤 변경과도 맞지 않아 (2)에서
  실패한다. 이력 파일로 옮기지 않는다. git 이력이 이력이다.
  증거 파일은 쓰기 전에 읽어서, 파일이 없으면 아무것도 바꾸지 않고 멈춘다.
- 이번 검사에 걸리는 오래된 14건을 지웠다. 지금 diff와 맞는 3건
  (REFERENCE_RESOURCE_DETAIL.path, CACHE_INVALIDATION_PULSE backend·
  valueCodec)은 남겼다.
- docs/operations/ci-quality-gates.md 증거 안내에 두 동작을 적었다.

이유: 목록을 출력만 하면 아무도 보지 않는다. 정리가 자동이라 실패해도
고치는 비용이 작다.

버린 대안
- 오래된 행을 목록으로 출력만 하기: 위 이유.
- 지운 행을 이력 파일로 옮기기: 파일이 하나 늘고, git 이력과 같은 사실의
  사본이 된다.

위험·한계
- 다운스트림이 이 검사를 동기화하면 자기 증거 파일의 오래된 행 때문에
  게이트가 실패한다. 실패 메시지가 행을 나열하므로 지우거나
  update:registry-baseline을 한 번 돌리면 된다. CHANGELOG [계약] 행이
  필요하다.
- 같은 changeId가 증거 파일에 두 번 있으면 지금처럼 뒤의 행만 쓰고,
  앞의 행은 오래된 행으로 걸리지 않는다. 이번 범위 밖이다.

검증
- RED(수정 전): registry-compatibility.test.ts 새 사례 "fails on evidence
  rows that explain no breaking change of the current diff"가
  "expected [] to deeply equal [ …(2) ]"로 실패. registry-governance.test.ts
  새 사례 "deletes the evidence rows the new baseline explains"가
  "expected { schemaVersion: 1, changes: [ …(1) ] } to deeply equal
  { schemaVersion: 1, changes: [] }"로 실패.
- GREEN: 두 파일 25/25 통과. 오래된 행을 지우기 전 check-registries가
  "stale breaking evidence ..." 14줄로 실패(rc=1), 지운 뒤 "11 registries
  PASS"(rc=0).
- 회귀: registry-compatibility·registry-governance·second-api-feature-
  registries·release-artifacts 55/55 통과. compatibility fixtures 11 PASS.
  verify-documentation-readiness PASS_SCOPED. tsc node·test rc=0, 바꾼
  파일 eslint rc=0.
- 미실행: check:architecture, test:sample-removal(pnpm 필요). 제거 드릴은
  update:registry-baseline 뒤 check:registries를 돌리므로 (3)이 있어야
  통과한다.

Refs: docs/reviews/2026-09-29-maturity-review/07-contracts.md
2026-11-03 00:55:33 +09:00

441 lines
14 KiB
TypeScript

import { createHash } from "node:crypto";
export const COMPATIBILITY_IMPACTS = Object.freeze([
"none",
"additive",
"behavior-change",
"breaking",
] as const);
type CompatibilityImpact = (typeof COMPATIBILITY_IMPACTS)[number];
type RegistryRecord = Record<string, unknown> & {
registryId?: unknown;
contract?: unknown;
rows?: unknown;
};
type RegistryChange = {
changeId: string;
registryId: string;
rowName: string;
field: string;
kind: string;
impact: CompatibilityImpact;
before?: unknown;
after?: unknown;
};
type RegistryDiff = Readonly<{
impact: CompatibilityImpact;
changes: readonly RegistryChange[];
}>;
const impactRank = new Map(
COMPATIBILITY_IMPACTS.map((impact, index) => [impact, index]),
);
export function canonicalizeRegistryValue(value: unknown): unknown {
if (Array.isArray(value)) {
const projected: unknown[] = value.map(canonicalizeRegistryValue);
return projected.every(
(item) =>
item === null ||
["string", "number", "boolean"].includes(typeof item),
)
? projected.sort((left, right) =>
JSON.stringify(left).localeCompare(JSON.stringify(right)),
)
: projected;
}
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value)
.sort(([left], [right]) => left.localeCompare(right))
.map(([key, item]) => [key, canonicalizeRegistryValue(item)]),
);
}
return value;
}
export function canonicalRegistryJson(value: unknown): string {
return JSON.stringify(canonicalizeRegistryValue(value)) ?? "undefined";
}
export function registrySnapshotDigest(snapshot: unknown): string {
return createHash("sha256")
.update(canonicalRegistryJson(snapshot))
.digest("hex");
}
function strongestImpact(
current: CompatibilityImpact,
candidate: CompatibilityImpact,
): CompatibilityImpact {
return (impactRank.get(candidate) ?? 0) > (impactRank.get(current) ?? 0)
? candidate
: current;
}
function valueType(value: unknown): string {
if (value === null) return "null";
if (Array.isArray(value)) return "array";
return typeof value;
}
/** The governance `fieldTypes` vocabulary: `integer` is its own name. */
export function registryRuntimeType(value: unknown): string {
if (Number.isInteger(value)) return "integer";
return valueType(value);
}
/** `declaration` is a governance field type such as `string|null`. */
export function matchesDeclaredType(value: unknown, declaration: string): boolean {
const actual = registryRuntimeType(value);
return declaration
.split("|")
.some(
(candidate) =>
candidate === actual ||
(candidate === "number" && actual === "integer"),
);
}
/**
* 0929/07-02. A null on one side and a value on the other is a change inside
* the field's declared type when that type admits both (`string|null`), not a
* change of type: hiding a navigation label is graded like renaming it.
*/
function isDeclaredNullableChange(
before: unknown,
after: unknown,
declaration: unknown,
): boolean {
return (
typeof declaration === "string" &&
(before === null || after === null) &&
matchesDeclaredType(before, declaration) &&
matchesDeclaredType(after, declaration)
);
}
/**
* 0929/07-02. Every field keeps its restriction and every value it allowed:
* rows valid before stay valid. A new, dropped or narrowed restriction is
* still breaking.
*/
function onlyExtendsAllowedValues(before: unknown, after: unknown): boolean {
if (!before || !after || typeof before !== "object" || typeof after !== "object") {
return false;
}
const previous = before as Record<string, unknown>;
const current = after as Record<string, unknown>;
const fields = Object.keys(previous);
if (fields.length !== Object.keys(current).length) return false;
return fields.every((field) => {
const allowedBefore = previous[field];
const allowedAfter = current[field];
if (!Array.isArray(allowedBefore) || !Array.isArray(allowedAfter)) return false;
const kept = new Set(allowedAfter.map((value) => canonicalRegistryJson(value)));
return allowedBefore.every((value) => kept.has(canonicalRegistryJson(value)));
});
}
function changeId(
registryId: string,
rowName: string,
field: string,
kind: string,
): string {
return `${registryId}:${rowName}:${field}:${kind}`;
}
/**
* Calculates a semantic diff. Object key and primitive-array ordering is
* canonicalized before comparison and therefore cannot create a false change.
*/
export function diffRegistrySnapshots(
before: Readonly<Record<string, unknown>>,
after: Readonly<Record<string, unknown>>,
): RegistryDiff {
const changes: RegistryChange[] = [];
let impact: CompatibilityImpact = "none";
const beforeRegistryRows = (before.registries ?? []) as RegistryRecord[];
const beforeRegistries = new Map<string, RegistryRecord>(
beforeRegistryRows.map((registry) => [
String(registry.registryId),
registry,
]),
);
const afterRegistryRows = (after.registries ?? []) as RegistryRecord[];
const afterRegistries = new Map<string, RegistryRecord>(
afterRegistryRows.map((registry) => [
String(registry.registryId),
registry,
]),
);
const registryIds = new Set([
...beforeRegistries.keys(),
...afterRegistries.keys(),
]);
for (const registryId of [...registryIds].sort()) {
const previous = beforeRegistries.get(registryId);
const current = afterRegistries.get(registryId);
if (!previous || !current) {
const changeImpact = previous ? "breaking" : "additive";
impact = strongestImpact(impact, changeImpact);
changes.push({
changeId: changeId(registryId, "*", "*", previous ? "removed" : "added"),
registryId,
rowName: "*",
field: "*",
kind: previous ? "registry-removed" : "registry-added",
impact: changeImpact,
});
continue;
}
const previousContract = (previous.contract ?? {}) as Record<string, unknown>;
const currentContract = (current.contract ?? {}) as Record<string, unknown>;
const contractFields = new Set([
...Object.keys(previousContract),
...Object.keys(currentContract),
]);
for (const field of [...contractFields].sort()) {
const beforeHas = Object.hasOwn(previousContract, field);
const afterHas = Object.hasOwn(currentContract, field);
const beforeValue = previousContract[field];
const afterValue = currentContract[field];
if (
beforeHas &&
afterHas &&
canonicalRegistryJson(beforeValue) ===
canonicalRegistryJson(afterValue)
) {
continue;
}
const extendsAllowedValues =
field === "allowedValues" &&
beforeHas &&
afterHas &&
onlyExtendsAllowedValues(beforeValue, afterValue);
const kind = !beforeHas
? "contract-field-added"
: !afterHas
? "contract-field-removed"
: extendsAllowedValues
? "allowed-values-extended"
: "contract-field-changed";
const changeImpact: CompatibilityImpact = extendsAllowedValues
? "additive"
: "breaking";
impact = strongestImpact(impact, changeImpact);
changes.push({
changeId: changeId(registryId, "$contract", field, kind),
registryId,
rowName: "$contract",
field,
kind,
impact: changeImpact,
before: canonicalizeRegistryValue(beforeValue),
after: canonicalizeRegistryValue(afterValue),
});
}
const breakingFields = new Set(
(currentContract.breakingFields ?? []) as string[],
);
const fieldTypes = (currentContract.fieldTypes ?? {}) as Record<
string,
unknown
>;
const beforeRows = (previous.rows ?? {}) as Record<
string,
Record<string, unknown>
>;
const afterRows = (current.rows ?? {}) as Record<
string,
Record<string, unknown>
>;
const rowNames = new Set([
...Object.keys(beforeRows),
...Object.keys(afterRows),
]);
for (const rowName of [...rowNames].sort()) {
const beforeRow = beforeRows[rowName];
const afterRow = afterRows[rowName];
if (!beforeRow || !afterRow) {
const changeImpact = beforeRow ? "breaking" : "additive";
impact = strongestImpact(impact, changeImpact);
changes.push({
changeId: changeId(
registryId,
rowName,
"*",
beforeRow ? "removed" : "added",
),
registryId,
rowName,
field: "*",
kind: beforeRow ? "row-removed" : "row-added",
impact: changeImpact,
});
continue;
}
const fields = new Set([
...Object.keys(beforeRow),
...Object.keys(afterRow),
]);
for (const field of [...fields].sort()) {
const beforeHas = Object.hasOwn(beforeRow, field);
const afterHas = Object.hasOwn(afterRow, field);
const beforeValue = beforeRow[field];
const afterValue = afterRow[field];
if (
beforeHas &&
afterHas &&
canonicalRegistryJson(beforeValue) ===
canonicalRegistryJson(afterValue)
) {
continue;
}
let kind: string;
let changeImpact: CompatibilityImpact;
if (!beforeHas) {
kind = "field-added";
changeImpact = "additive";
} else if (!afterHas) {
kind = "field-removed";
changeImpact = "breaking";
} else if (
valueType(beforeValue) !== valueType(afterValue) &&
!isDeclaredNullableChange(beforeValue, afterValue, fieldTypes[field])
) {
kind = "field-type-changed";
changeImpact = "breaking";
} else if (
Array.isArray(beforeValue) &&
Array.isArray(afterValue) &&
beforeValue.some(
(item) =>
!afterValue.some(
(candidate) =>
canonicalRegistryJson(candidate) ===
canonicalRegistryJson(item),
),
)
) {
kind = "allowed-value-removed";
changeImpact = "breaking";
} else {
kind = "field-changed";
changeImpact = breakingFields.has(field)
? "breaking"
: "behavior-change";
}
impact = strongestImpact(impact, changeImpact);
changes.push({
changeId: changeId(registryId, rowName, field, kind),
registryId,
rowName,
field,
kind,
impact: changeImpact,
before: canonicalizeRegistryValue(beforeValue),
after: canonicalizeRegistryValue(afterValue),
});
}
}
}
return Object.freeze({
impact,
changes: Object.freeze(changes),
});
}
export function verifyRegistryBaselineApproval(
snapshot: Readonly<Record<string, unknown>>,
approval: Readonly<Record<string, unknown>>,
) {
const actualDigest = registrySnapshotDigest(snapshot);
const approvedDigest = approval.snapshotDigest;
return Object.freeze({
passed:
approval.schemaVersion === 1 &&
typeof approval.owner === "string" &&
approval.owner.length > 0 &&
typeof approval.approvedAt === "string" &&
approvedDigest === actualDigest,
actualDigest,
approvedDigest:
typeof approvedDigest === "string" ? approvedDigest : "missing",
});
}
export function validateBreakingEvidence(
diff: RegistryDiff,
evidenceFile: Readonly<Record<string, unknown>>,
) {
const entries = (evidenceFile.changes ?? []) as Array<Record<string, unknown>>;
const evidence = new Map<string, Record<string, unknown>>(
entries.map((entry) => [String(entry.changeId), entry]),
);
const failures: string[] = [];
const breakingChanges = diff.changes.filter(
(entry) => entry.impact === "breaking",
);
for (const change of breakingChanges) {
const entry = evidence.get(change.changeId);
if (!entry) {
failures.push(`breaking change missing evidence: ${change.changeId}`);
continue;
}
// 0929/07-01. The changeId names a row and field, not a value. Without
// the value, evidence for one change would also pass the next change of
// the same field. Removals have no value to name.
if (change.after !== undefined) {
if (!Object.hasOwn(entry, "after")) {
failures.push(
`breaking change ${change.changeId} evidence needs after (the canonical JSON value it explains)`,
);
} else if (
canonicalRegistryJson(entry.after) !== canonicalRegistryJson(change.after)
) {
failures.push(
`breaking change ${change.changeId} evidence explains after=${canonicalRegistryJson(entry.after)}, the change is after=${canonicalRegistryJson(change.after)}`,
);
}
}
for (const field of [
"versionBump",
"migration",
"compatibilityWindow",
"rollback",
"owner",
]) {
const value = entry[field];
if (typeof value !== "string" || value.trim().length === 0) {
failures.push(
`breaking change ${change.changeId} missing non-empty ${field}`,
);
}
}
}
// 0929/07-01 (2). A row that explains no breaking change of this diff was
// absorbed by an earlier baseline or describes a change that is gone. It
// fails rather than being listed, because a printed list is not read, and
// the fix is cheap: update:registry-baseline deletes absorbed rows.
const explained = new Set(breakingChanges.map((change) => change.changeId));
for (const entry of entries) {
if (!explained.has(String(entry.changeId))) {
failures.push(
`stale breaking evidence ${String(entry.changeId)}: no breaking change in the current diff has this changeId. Delete the row (update:registry-baseline deletes the rows a new baseline explains)`,
);
}
}
return Object.freeze({
passed: failures.length === 0,
failures: Object.freeze(failures),
});
}