test(contracts): FE-REG-SCHEMA 행의 방향·모르는 필드 정책을 검증기와 대조한다
문제 참조 기능의 FE-REG-SCHEMA 행은 응답 스키마를 STRIP_UNKNOWN, 요청 스키마를 REJECT_UNKNOWN이라 적는다. 실제 정책은 zod .strip()·.strict()가 정하고, unknownFieldPolicy·direction을 읽는 실행 코드는 없다. 응답 DTO를 .strict()로 바꿔도 check:registries와 관련 테스트가 모두 통과한다(실험 X8). 그러면 백엔드가 응답에 필드 하나를 더할 때마다 그 API가 SCHEMA_MISMATCH로 실패하는데, 스냅샷과 docs/contracts/compatibility.md는 여전히 additive라 말한다. 고른 방법 설치된 기능의 HTTP descriptor마다 입력·출력 검증기를 FE-REG-SCHEMA 행과 대조하는 테스트를 더한다. - direction: 입력 검증기 행은 REQUEST, 출력 검증기 행은 RESPONSE. - unknownFieldPolicy: 아무 스키마도 선언하지 않는 키 하나를 가진 객체와, 그 객체 하나를 담은 배열을 검증기에 넣는다. 그 객체 위치의 unrecognized_keys면 REJECT_UNKNOWN, 객체 안을 봤는데 그 issue가 없으면 STRIP_UNKNOWN이다. 정책을 적은 행만 본다. loaded-feature-runtimes를 읽으므로 다운스트림이 더한 기능도 같은 검사를 받는다. create:feature 뼈대(NoRequest strict, 목록 응답 strip)도 맞는다. 버린 대안 - 메타데이터에서 두 칸을 지우기: 읽는 곳이 없어 가장 단순하지만 호환 문서의 근거가 사라지고 기준선 재승인이 필요하다. 메타데이터 생성은 다른 작업(16-04~06) 범위다. - 스키마마다 유효한 예시 값을 두고 모르는 키를 더하기: 기능마다 예시를 손으로 써야 해 다운스트림 기능을 자동으로 덮지 못한다. 위험·한계 - 탐침은 payload의 첫 객체 단계(객체, 또는 배열의 항목)만 본다. 그 아래 중첩 객체의 정책은 보지 않는다. - problem 검증기는 FE-REG-SCHEMA 행이 없어 대상이 아니다. 검증 - 변이: 응답 DTO .strip()→.strict()(X8), 생성 명령 .strict()→.strip(), 응답 행 direction을 REQUEST로 바꾸면 각각 실패한다. 되돌리면 2건 통과. 설치된 기능이 없으면(샘플 제거 뒤) 두 건 모두 빈 채로 통과한다. - eslint, check:types:test 통과. Refs: docs/reviews/2026-11-03-maturity-review/07-contracts.md 07-03
This commit is contained in:
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { RuntimeValidator } from "../../src/contracts/external-contract-runtime.ts";
|
||||
import {
|
||||
COMPOSED_CONTRACT_CONTRIBUTIONS,
|
||||
SCHEMA_REGISTRY,
|
||||
} from "../../src/features/loaded-feature-runtimes.ts";
|
||||
|
||||
/**
|
||||
* 1103/07-03. FE-REG-SCHEMA rows state each HTTP schema's direction and
|
||||
* unknown-field policy, and `docs/contracts/compatibility.md` builds the
|
||||
* "adding a response field is additive" rule on `STRIP_UNKNOWN`. Nothing at
|
||||
* run time reads those two fields, so they are checked here against the
|
||||
* validators the installed HTTP descriptors run.
|
||||
*
|
||||
* The probe is an object with one key no schema declares, and the same object
|
||||
* as the only item of an array, so it reaches the first object level of an
|
||||
* object or list payload. A validator that rejects it with
|
||||
* `unrecognized_keys` rejects unknown fields; one that reaches the object
|
||||
* without that issue tolerates them. A nested object below that level is not
|
||||
* probed.
|
||||
*/
|
||||
const PROBE_KEY = "__unknownFieldProbe";
|
||||
|
||||
type ProbedPolicy = "REJECT_UNKNOWN" | "STRIP_UNKNOWN" | "UNREACHED";
|
||||
|
||||
function probeUnknownFieldPolicy(validator: RuntimeValidator<unknown>): ProbedPolicy {
|
||||
const probe = { [PROBE_KEY]: true };
|
||||
for (const [value, objectPath] of [
|
||||
[probe, []],
|
||||
[[probe], [0]],
|
||||
] as const) {
|
||||
const result = validator.safeParse(value);
|
||||
if (result.success) return "STRIP_UNKNOWN";
|
||||
const atObject = (path: readonly (string | number)[]) =>
|
||||
JSON.stringify(path) === JSON.stringify(objectPath);
|
||||
if (
|
||||
result.issues.some(
|
||||
(issue) => issue.code === "unrecognized_keys" && atObject(issue.path),
|
||||
)
|
||||
) {
|
||||
return "REJECT_UNKNOWN";
|
||||
}
|
||||
// Every issue sits at or above the probed object (wrong type, wrong
|
||||
// shape): the validator never looked inside it, so try the next probe.
|
||||
const unreached = result.issues.every(
|
||||
(issue) =>
|
||||
issue.path.length <= objectPath.length &&
|
||||
issue.path.every((segment, index) => segment === objectPath[index]),
|
||||
);
|
||||
if (!unreached) return "STRIP_UNKNOWN";
|
||||
}
|
||||
return "UNREACHED";
|
||||
}
|
||||
|
||||
const slots = COMPOSED_CONTRACT_CONTRIBUTIONS.contributions.flatMap(
|
||||
({ http }) =>
|
||||
http.flatMap(({ contract }) => [
|
||||
{
|
||||
operationId: contract.operationId,
|
||||
direction: "REQUEST" as const,
|
||||
validator: contract.inputValidator,
|
||||
},
|
||||
{
|
||||
operationId: contract.operationId,
|
||||
direction: "RESPONSE" as const,
|
||||
validator: contract.outputValidator,
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
// With no installed feature (after the sample is removed) there is nothing to
|
||||
// probe, and both cases pass empty.
|
||||
describe("FE-REG-SCHEMA policy of the installed HTTP schemas (1103/07-03)", () => {
|
||||
it("declares the direction each schema is used in", () => {
|
||||
const wrong = slots.flatMap(({ operationId, direction, validator }) => {
|
||||
const declared = SCHEMA_REGISTRY[validator.schemaId]?.direction;
|
||||
return declared === undefined || declared === direction
|
||||
? []
|
||||
: [`${operationId} ${validator.schemaId}: row ${declared}, used as ${direction}`];
|
||||
});
|
||||
|
||||
expect(wrong).toEqual([]);
|
||||
});
|
||||
|
||||
it("declares the unknown-field policy its validator applies", () => {
|
||||
const wrong = slots.flatMap(({ operationId, validator }) => {
|
||||
const declared = SCHEMA_REGISTRY[validator.schemaId]?.unknownFieldPolicy;
|
||||
if (declared === undefined) return [];
|
||||
const probed = probeUnknownFieldPolicy(validator);
|
||||
return probed === declared
|
||||
? []
|
||||
: [`${operationId} ${validator.schemaId}: row ${declared}, validator ${probed}`];
|
||||
});
|
||||
|
||||
expect(wrong).toEqual([]);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user