Files
clean-architecture-frontend…/scripts/lib/registry-compatibility.ts
T
DongHyeonka 3b62ccd5db fix(registry): 응답 스키마 행을 REJECT_UNKNOWN으로 좁히면 breaking으로 본다
문제: 응답 DTO를 `.strict()`로 바꾸고 FE-REG-SCHEMA 행의
`unknownFieldPolicy`를 STRIP_UNKNOWN에서 REJECT_UNKNOWN으로 같이 고치면
check:registries가 behavior-change로 통과한다(리뷰 배치 07-R1). 1103/07-03
수정은 행과 검증기를 묶었지만 등급은 그대로였다. 그 뒤 백엔드가 응답에
필드 하나를 더하면 그 API는 SCHEMA_MISMATCH로 실패한다. 같은 경계에서
FE-REG-API는 acceptedStatuses 축소를 breaking으로 본다.

고른 방법: 분류기에 규칙 하나를 더한다. `direction: "RESPONSE"` 행의
`unknownFieldPolicy`가 REJECT_UNKNOWN이 아니던 값에서 REJECT_UNKNOWN으로
바뀌면 kind `response-reader-narrowed`, breaking이다. 반대 방향
(REJECT→STRIP, 읽는 쪽을 넓힘)과 REQUEST 행(프론트가 스스로 채우는 값)은
그대로 behavior-change다. 버린 대안: governance의 FE-REG-SCHEMA
breakingFields에 `unknownFieldPolicy`를 넣는 것(리뷰 안 B). 넓히는 변경까지
증거를 요구하게 되고, governance 계약이 바뀌어 템플릿과 다운스트림 모두
기준선을 다시 승인해야 한다. 이 규칙은 기준선과 governance를 바꾸지 않는다.
리뷰 안 (1)의 fieldTypes 선언도 같은 이유로 하지 않았다.

위험·한계: 규칙은 칸 이름(`unknownFieldPolicy`)과 값 어휘
(src/contracts/schema-registry.ts)에 묶여 있다. 어휘를 바꾸면 이 함수도
고친다. route-params·route-search(REQUEST 방향, URL을 읽는 쪽)를
REJECT_UNKNOWN으로 좁히는 변경은 여전히 behavior-change다. 지금 템플릿
스냅샷은 기준선과 같아 결과는 none 그대로다.

검증: desktop batch에서 확인.
node scripts/run-vitest.ts run tests/unit/registry-compatibility.test.ts
리뷰 07-R1 패치(응답 DTO `.strict()` + 응답 행 두 개 REJECT_UNKNOWN)를
다시 적용하면 check:registries가 `breaking change missing evidence:
FE-REG-SCHEMA:ReferenceResource(List)Payload:unknownFieldPolicy:
response-reader-narrowed`로 실패해야 한다.

Refs: 1105/07-02
2026-11-05 22:10:05 +09:00

483 lines
16 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)));
});
}
/**
* 1105/07-02. A response schema row that starts rejecting unknown keys
* narrows what the frontend accepts, as removing an accepted status does in
* FE-REG-API: every response the backend extends with a field then fails with
* SCHEMA_MISMATCH. That one direction is breaking. REJECT -> STRIP widens the
* reader, and a REQUEST row's policy is checked against what the frontend
* itself sends; both stay behavior-change, as does any other policy change.
*/
function narrowsResponseReader(
field: string,
before: unknown,
after: unknown,
row: Readonly<Record<string, unknown>>,
): boolean {
return (
field === "unknownFieldPolicy" &&
before !== "REJECT_UNKNOWN" &&
after === "REJECT_UNKNOWN" &&
row.direction === "RESPONSE"
);
}
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
>;
// 1101/16-01 (decision 1). A projected registry keeps keyed sets in one
// row: the invalidation graph's topics, namespaces and edges. An item
// added to such a set is what a new row is elsewhere, so it is additive
// even when the field is a breaking field. A removed or changed item is
// graded as allowed-value-removed below and stays breaking.
const keyedSetFields = new Set(
Object.keys(
(
currentContract.snapshotProjection as
| { canonicalArrayKeyFields?: Record<string, unknown> }
| undefined
)?.canonicalArrayKeyFields ?? {},
),
);
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 if (keyedSetFields.has(field) && Array.isArray(afterValue)) {
kind = "set-items-added";
changeImpact = "additive";
} else if (narrowsResponseReader(field, beforeValue, afterValue, afterRow)) {
kind = "response-reader-narrowed";
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),
});
}