perf(contracts): 검증 생략 목록을 부팅 경로 밖에서 만든다 (1101/07-03)

문제
- 93180f6(합친 커밋 d3ddc89)이 초기 JS를 늘렸다. 기능 모양 측정
  (scripts/scale/measure-feature-shape-growth.ts) 기준으로 기능 0개가
  202,376 → 202,526 B(+150)로, 기능 1개 추가분이 960 → 1,029 B로 늘었다.
  tests/unit/feature-shape-growth.test.ts의 1 KiB 상한을 넘는다.
- 원인은 두 가지다.
  - 부팅 때 도는 composeContractContributions가 검증기마다 생략 표시를
    읽고 목록을 만들었다(feature-platform 청크 +164 B). 이 목록을 쓰는
    곳은 플랫폼 개요 화면(lazy 라우트)뿐이다.
  - 공유 zod-validator.ts가 기능이 두 개가 되면 lazy 청크 하나로 따로
    나왔다. 모든 context-routes·feature-runtime import의 preload 목록에
    파일 이름이 하나 늘어 boot·feature-declarations 청크가 각각 약 25 B
    커졌다.

고른 방법
- 목록 계산을 src/contracts/unvalidated-payload.ts의
  listUnvalidatedPayloads(composed)로 옮긴다. 플랫폼 개요 화면만 이것을
  import한다. 결정의 뜻(생략한 operation이 조립 결과에서 목록으로
  나온다)은 그대로다. 계산 시점만 화면이 열릴 때로 미룬다.
  ComposedContractContributions.unvalidatedPayloads 필드는 뺀다.
- unvalidatedPayload 팩토리도 같은 모듈로 옮긴다.
- 조립기의 표시 검사도 뺀다. 이유가 빈 생략은 unvalidatedPayload가 만들
  때 거부한다(TypeError). 손으로 붙인 표시는 값이 "NONE"이 아니거나 이유가
  없어도 목록에 나온다(화면에는 "이유 없음"). 그래서 생략이 숨지 않는다.
  external-contract-runtime.ts에는 RuntimeValidator의 선택 타입 필드
  2개만 남는다.
- vite.config.ts에서 zod-validator.ts를 schema-registry.ts와 같은 lazy
  청크로 묶는다. 어댑터를 import하는 곳은 이미 schema-registry 청크를
  preload한다. includeDependenciesRecursively: false라서 다른 모듈은
  끌려오지 않고, 두 모듈 모두 부팅 그래프 밖이다.

버린 대안
- 조립기에 "NONE + 이유" 검사만 남기기: feature-platform 청크 +57 B gzip.
  검사를 팩토리와 목록으로 옮기면 0 B다. 손으로 붙인 잘못된 표시를
  부팅 때 거부하지 못하지만, 목록에는 나온다.
- zodValidator를 schema-registry.ts 안에 정의: 빌드 설정 없이 같은 결과가
  나오지만 결정한 위치(src/contracts/zod-validator.ts)와 다르고, 다음 단계의
  기능 생성 명령이 그 경로를 쓴다.
- 어댑터를 zod.ts에 두기: zod 입구는 초기 청크라 기능 0개 초기 JS가 는다.

위험·한계
- 조립 결과 타입에서 unvalidatedPayloads 필드가 빠진다. 93180f6 뒤 이
  필드를 쓴 코드는 listUnvalidatedPayloads로 바꿔야 한다. repo 안에서는
  화면과 테스트만 썼다.
- 손으로 만든 잘못된 표시(예: validation: "PARTIAL")는 더 이상 조립에서
  거부되지 않는다. 목록에만 나온다. 테스트 2건을 이 동작으로 바꿨다.
- 청크 묶음은 빌드 설정에 두 파일 경로를 적는다. 파일 이름을 바꾸면
  정규식도 함께 바꿔야 한다. 놓치면 바이트만 늘고 동작은 같다.
- 플랫폼 개요 화면을 열면 schema-registry 청크에 어댑터(351 B raw)가 같이
  온다.

검증
- 기능 모양 측정(0개 / 1개 추가분, gzip B):
  - ee81c44(07-03 전): 202,376 / 960
  - d3ddc89(07-03 합친 뒤): 202,526 / 1,029
  - 목록만 부팅 밖으로: 202,407 / 1,035
  - 청크 묶음 추가: 202,424 / 983
  - 조립기 검사 제거(이 커밋): 202,371 / 958
- feature-shape-growth.test.ts 6건 통과.
- 07-03 테스트 3파일 33건 통과(zod-validator, external-contract-runtime,
  starter-platform-overview-page).
- 회귀: tests/unit·contract·component·runtime-schema·features·platform
  270파일 3,203건, tests/integration 12파일 158건(pnpm을 띄우는
  security-followup-archive 제외), tests/architecture 7파일 33건 통과.
- tsc app·node·test·recipes·web-worker·service-worker 오류 0. 바꾼 파일
  eslint 0. 아키텍처 그래프 검사(pnpm 대신 exec stub) 413 모듈 PASS.
  check-registries PASS(compatibility=none).
- 본 빌드 초기 JS gzip 202,371 B(26파일). raw 644,782 B로 ee81c44 측정과
  같다.

Refs: docs/reviews/2026-11-01-maturity-review/07-contracts.md 07-03
This commit is contained in:
DongHyeonka
2026-11-03 01:58:38 +09:00
parent ca161878f2
commit 8b7c6ebf6c
8 changed files with 170 additions and 127 deletions
+25 -99
View File
@@ -60,40 +60,17 @@ export interface RuntimeValidator<T> {
readonly schemaId: string;
/**
* 1101/07-03. Absent on a validator that checks its input. `"NONE"` marks
* one made by `unvalidatedPayload`, which accepts any value as `T`;
* composition lists it in `unvalidatedPayloads`. A hand-written validator
* that checks nothing and omits the marker is not detected.
* one made by `unvalidatedPayload` (`unvalidated-payload.ts`), which
* accepts any value as `T`; `listUnvalidatedPayloads` lists it.
* Composition, on the boot path, does not read the marker. A hand-written
* validator that checks nothing and omits the marker is not detected.
*/
readonly validation?: "NONE";
/** Why validation is skipped. Required with `validation: "NONE"`. */
/** Why validation is skipped. `unvalidatedPayload` requires one. */
readonly unvalidatedReason?: string;
safeParse(value: unknown): RuntimeValidationResult<T>;
}
/**
* 1101/07-03. The named way to skip runtime validation, for a payload whose
* shape the feature decides to trust (for example generated client types).
* The value reaches the mapper as `T` unchecked: a server that sends another
* shape produces no `SCHEMA_MISMATCH`. The skip and its reason stay visible in
* `ComposedContractContributions.unvalidatedPayloads`.
*/
export function unvalidatedPayload<T>(
schemaId: string,
reason: string,
): RuntimeValidator<T> {
return Object.freeze({
schemaId,
validation: "NONE" as const,
unvalidatedReason: reason,
safeParse(value: unknown) {
return Object.freeze({
success: true as const,
data: structuredClone(value) as T,
});
},
});
}
/**
* A validator invocation never escapes as a native throw. `THROWN` is the
* `CONTRACT_RUNTIME_FAILURE` signal; `false` success is the ordinary
@@ -339,58 +316,18 @@ function assertPackageIdentity(
}
}
/** 1101/07-03. A validator slot whose validation is skipped by name. */
export type UnvalidatedPayloadEntry = Readonly<{
featureId: string;
/** The HTTP operationId, or the event type of an event contract. */
contractId: string;
validator: "input" | "output" | "problem" | "envelope" | "payload";
schemaId: string;
reason: string;
}>;
/** Checks each validator and returns the ones that skip validation by name. */
function assertValidators(
featureId: string,
contractId: string,
validators: Partial<
Record<UnvalidatedPayloadEntry["validator"], RuntimeValidator<unknown>>
>,
): UnvalidatedPayloadEntry[] {
const unvalidated: UnvalidatedPayloadEntry[] = [];
for (const [role, validator] of Object.entries(validators) as [
UnvalidatedPayloadEntry["validator"],
RuntimeValidator<unknown>,
][]) {
const label = `${featureId}/${contractId}.${role}`;
if (
!validator ||
typeof validator.safeParse !== "function" ||
typeof validator.schemaId !== "string" ||
validator.schemaId.length === 0
) {
fail(`${label}: runtime validator with non-empty schemaId is required`);
}
if (validator.validation === undefined) continue;
const reason = validator.unvalidatedReason;
if (
validator.validation !== "NONE" ||
typeof reason !== "string" ||
reason.trim().length === 0
) {
fail(`${label}: an unvalidated payload needs validation "NONE" and a reason`);
}
unvalidated.push(
Object.freeze({
featureId,
contractId,
validator: role,
schemaId: validator.schemaId,
reason,
}),
);
function assertValidator(
validator: RuntimeValidator<unknown>,
label: string,
): void {
if (
!validator ||
typeof validator.safeParse !== "function" ||
typeof validator.schemaId !== "string" ||
validator.schemaId.length === 0
) {
fail(`${label}: runtime validator with non-empty schemaId is required`);
}
return unvalidated;
}
function assertStatuses(
@@ -478,7 +415,7 @@ function assertHttpContract(
installed: InstalledHttpContract<unknown, unknown, unknown>,
featureId: string,
authProfiles: InstalledRestAuthProfiles,
): UnvalidatedPayloadEntry[] {
): void {
const contract = installed?.contract;
if (!contract || typeof contract !== "object") {
fail(`${featureId}: http contract descriptor missing`);
@@ -507,11 +444,9 @@ function assertHttpContract(
) {
fail(`${label}: pathTemplate`);
}
const unvalidated = assertValidators(featureId, String(contract.operationId), {
input: contract.inputValidator,
output: contract.outputValidator,
problem: contract.problemValidator,
});
assertValidator(contract.inputValidator, `${label}.input`);
assertValidator(contract.outputValidator, `${label}.output`);
assertValidator(contract.problemValidator, `${label}.problem`);
if (typeof contract.projectRequest !== "function") {
fail(`${label}: descriptor request projection is required`);
}
@@ -589,13 +524,12 @@ function assertHttpContract(
) {
fail(`${label}: retry budget contradicts NEVER retry semantics`);
}
return unvalidated;
}
function assertEventContract(
event: InstalledEventContract<unknown, unknown>,
featureId: string,
): UnvalidatedPayloadEntry[] {
): void {
const label = `${featureId}/${String(event?.eventType)}`;
if (
typeof event?.eventType !== "string" ||
@@ -605,10 +539,8 @@ function assertEventContract(
) {
fail(`${label}: eventType`);
}
return assertValidators(featureId, event.eventType, {
envelope: event.envelopeValidator,
payload: event.payloadValidator,
});
assertValidator(event.envelopeValidator, `${label}.envelope`);
assertValidator(event.payloadValidator, `${label}.payload`);
}
export type ComposedContractContributions = Readonly<{
@@ -627,8 +559,6 @@ export type ComposedContractContributions = Readonly<{
InstalledEventContract<unknown, unknown>
>;
externalPackages: readonly InstalledContractPackageIdentity[];
/** 1101/07-03. Every validator made by `unvalidatedPayload`, in install order. */
unvalidatedPayloads: readonly UnvalidatedPayloadEntry[];
}>;
const EXECUTION_POLICY_KEYS = [
@@ -778,7 +708,6 @@ export function composeContractContributions(
const packagesById = new Map<string, InstalledContractPackageIdentity>();
const contributionIds = new Set<string>();
const installedContributions: InstalledContractContribution[] = [];
const unvalidatedPayloads: UnvalidatedPayloadEntry[] = [];
let fixtureInstalled = false;
for (const raw of rows) {
@@ -914,9 +843,7 @@ export function composeContractContributions(
installed as InstalledHttpContract<unknown, unknown, unknown>,
featureId,
);
unvalidatedPayloads.push(
...assertHttpContract(snapshot, featureId, authProfiles),
);
assertHttpContract(snapshot, featureId, authProfiles);
const operationId = snapshot.contract.operationId;
const previous = httpByOperationId.get(operationId);
if (previous) fail(`duplicate operation: ${operationId}`);
@@ -930,7 +857,7 @@ export function composeContractContributions(
event as InstalledEventContract<unknown, unknown>,
featureId,
);
unvalidatedPayloads.push(...assertEventContract(snapshot, featureId));
assertEventContract(snapshot, featureId);
if (eventByType.has(snapshot.eventType)) {
fail(`duplicate event type: ${snapshot.eventType}`);
}
@@ -960,6 +887,5 @@ export function composeContractContributions(
httpByOperationId: createReadOnlyRegistry(httpByOperationId),
eventByType: createReadOnlyRegistry(eventByType),
externalPackages: Object.freeze(externalPackages),
unvalidatedPayloads: Object.freeze(unvalidatedPayloads),
});
}
+94
View File
@@ -0,0 +1,94 @@
import type {
ComposedContractContributions,
RuntimeValidator,
} from "./external-contract-runtime.ts";
/**
* 1101/07-03. The named way to skip runtime validation, for a payload whose
* shape the feature decides to trust (for example generated client types).
* The value reaches the mapper as `T` unchecked: a server that sends another
* shape produces no `SCHEMA_MISMATCH`. `listUnvalidatedPayloads` lists every
* such validator with its reason.
*/
export function unvalidatedPayload<T>(
schemaId: string,
reason: string,
): RuntimeValidator<T> {
if (reason.trim().length === 0) {
throw new TypeError(`${schemaId}: an unvalidated payload needs a reason`);
}
return Object.freeze({
schemaId,
validation: "NONE" as const,
unvalidatedReason: reason,
safeParse(value: unknown) {
return Object.freeze({
success: true as const,
data: structuredClone(value) as T,
});
},
});
}
/** 1101/07-03. A validator slot whose validation is skipped by name. */
export type UnvalidatedPayloadEntry = Readonly<{
featureId: string;
/** The HTTP operationId, or the event type of an event contract. */
contractId: string;
validator: "input" | "output" | "problem" | "envelope" | "payload";
schemaId: string;
/** Empty when a hand-built marker carries no reason. */
reason: string;
}>;
/**
* 1101/07-03. Every validator of a composed result that carries a skip
* marker, in install order. It reads the composed result instead of being
* built during composition, so only the screen that shows it (the platform
* overview, a lazy route) pays for it: composition runs on the boot path.
* Any marker value counts, so a hand-built marker that is not `"NONE"` or has
* no reason still shows up rather than passing as validated.
*/
export function listUnvalidatedPayloads(
composed: ComposedContractContributions,
): readonly UnvalidatedPayloadEntry[] {
const entries: UnvalidatedPayloadEntry[] = [];
const add = (
featureId: string,
contractId: string,
validators: Partial<
Record<UnvalidatedPayloadEntry["validator"], RuntimeValidator<unknown>>
>,
) => {
for (const [validator, { validation, schemaId, unvalidatedReason }] of Object.entries(
validators,
) as [UnvalidatedPayloadEntry["validator"], RuntimeValidator<unknown>][]) {
if (validation === undefined) continue;
entries.push(
Object.freeze({
featureId,
contractId,
validator,
schemaId,
reason: typeof unvalidatedReason === "string" ? unvalidatedReason.trim() : "",
}),
);
}
};
for (const { featureId, http, events } of composed.contributions) {
for (const { contract } of http) {
add(featureId, contract.operationId, {
input: contract.inputValidator,
output: contract.outputValidator,
problem: contract.problemValidator,
});
}
for (const event of events) {
add(featureId, event.eventType, {
envelope: event.envelopeValidator,
payload: event.payloadValidator,
});
}
}
return Object.freeze(entries);
}
+2 -2
View File
@@ -10,8 +10,8 @@ import type { ZodType } from "./zod.ts";
* - an issue path stays an array of numbers and strings (symbol keys become
* strings); an issue code is zod's code as a string.
* A package that ships its own validators keeps implementing the protocol
* directly. To skip validation on purpose, use `unvalidatedPayload`, which
* composition lists.
* directly. To skip validation on purpose, use `unvalidatedPayload`
* (`unvalidated-payload.ts`), which `listUnvalidatedPayloads` lists.
*/
export function zodValidator<T>(
schemaId: string,
@@ -3,8 +3,11 @@ import { type ComponentType, useEffect, useState } from "react";
import {
HTTP_EXECUTION_CEILINGS,
type ComposedContractContributions,
type UnvalidatedPayloadEntry,
} from "../../contracts/external-contract-runtime.ts";
import {
listUnvalidatedPayloads,
type UnvalidatedPayloadEntry,
} from "../../contracts/unvalidated-payload.ts";
import { SERVER_STATE_PROFILES } from "../../contracts/server-state.ts";
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../../features/installed-contract-contributions.ts";
import { ROUTE_REGISTRY } from "../../features/installed-feature-contracts.ts";
@@ -173,7 +176,11 @@ const UNVALIDATED_COLUMNS: readonly DataTableColumn<UnvalidatedPayloadEntry>[] =
</>
),
},
{ id: "reason", header: "생략 이유", cell: (row) => row.reason },
{
id: "reason",
header: "생략 이유",
cell: (row) => row.reason || "이유 없음",
},
]);
type ProfileRow = (typeof SERVER_STATE_PROFILES)[keyof typeof SERVER_STATE_PROFILES];
@@ -473,7 +480,7 @@ export function PlatformOverviewPage({
<DataTable
caption="런타임 검증을 생략한 계약"
columns={UNVALIDATED_COLUMNS}
rows={contracts.unvalidatedPayloads}
rows={listUnvalidatedPayloads(contracts)}
rowKey={(row) => `${row.contractId}.${row.validator}`}
empty={null}
/>
@@ -3,10 +3,8 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import {
composeContractContributions,
unvalidatedPayload,
} from "../../src/contracts/external-contract-runtime.ts";
import { composeContractContributions } from "../../src/contracts/external-contract-runtime.ts";
import { unvalidatedPayload } from "../../src/contracts/unvalidated-payload.ts";
import { SERVER_STATE_PROFILES } from "../../src/contracts/server-state.ts";
import { COMPOSED_CONTRACT_CONTRIBUTIONS } from "../../src/features/loaded-feature-runtimes.ts";
import { ROUTE_REGISTRY } from "../../src/features/installed-feature-contracts.ts";
+23 -15
View File
@@ -4,10 +4,13 @@ import {
ContractContributionError,
composeContractContributions,
invokeValidator,
unvalidatedPayload,
type InstalledContractContribution,
type RuntimeValidator,
} from "../../src/contracts/external-contract-runtime.ts";
import {
listUnvalidatedPayloads,
unvalidatedPayload,
} from "../../src/contracts/unvalidated-payload.ts";
import {
TEST_CONTRACT_CONTRIBUTION,
TEST_EVENT_CONTRACT,
@@ -164,7 +167,7 @@ describe("template fixture provenance (07-04, §4.8)", () => {
});
// 1101/07-03. Skipping runtime validation stays possible, but only a skip
// made through `unvalidatedPayload` is named, so composition can list it.
// made through `unvalidatedPayload` is named, so the composed result lists it.
describe("validation skipped by name (1101/07-03)", () => {
const [listRow] = TEST_CONTRACT_CONTRIBUTION.http as readonly [
InstalledContractContribution["http"][number],
@@ -179,13 +182,13 @@ describe("validation skipped by name (1101/07-03)", () => {
it("lists nothing when every validator checks its input", () => {
expect(
composeContractContributions([TEST_CONTRACT_CONTRIBUTION]).unvalidatedPayloads,
listUnvalidatedPayloads(composeContractContributions([TEST_CONTRACT_CONTRIBUTION])),
).toEqual([]);
});
it("lists an operation whose output skips validation, with its reason", () => {
expect(
composeContractContributions([withOutput(skipped)]).unvalidatedPayloads,
listUnvalidatedPayloads(composeContractContributions([withOutput(skipped)])),
).toEqual([
{
featureId: "test-feature",
@@ -207,7 +210,7 @@ describe("validation skipped by name (1101/07-03)", () => {
}),
]);
expect(composed.unvalidatedPayloads).toEqual([
expect(listUnvalidatedPayloads(composed)).toEqual([
expect.objectContaining({
contractId: "test.entity.changed",
validator: "payload",
@@ -216,18 +219,23 @@ describe("validation skipped by name (1101/07-03)", () => {
]);
});
it.each([
["no reason", { ...skipped, unvalidatedReason: " " }],
["an unknown marker", { ...skipped, validation: "PARTIAL" }],
])("rejects a skip marker with %s", (_label, validator) => {
expect(
captureContributionError(() =>
composeContractContributions([withOutput(validator as RuntimeValidator<unknown>)]),
).reason,
).toBe(
'test-feature/TEST_LIST_ENTITIES.output: an unvalidated payload needs validation "NONE" and a reason',
it("refuses to name a skip without a reason", () => {
expect(() => unvalidatedPayload("TestEntity", " ")).toThrow(
"TestEntity: an unvalidated payload needs a reason",
);
});
// Composition (boot path) does not read the marker, so a hand-built one is
// not refused there; the list still shows it instead of passing it as checked.
it("lists a hand-built marker that is not NONE or has no reason", () => {
const handBuilt = { ...skipped, validation: "PARTIAL", unvalidatedReason: undefined };
expect(
listUnvalidatedPayloads(
composeContractContributions([withOutput(handBuilt as unknown as RuntimeValidator<unknown>)]),
),
).toEqual([expect.objectContaining({ validator: "output", reason: "" })]);
});
});
describe("validator invocation (07-06)", () => {
+2 -4
View File
@@ -1,9 +1,7 @@
import { describe, expect, it } from "vitest";
import {
invokeValidator,
unvalidatedPayload,
} from "../../src/contracts/external-contract-runtime.ts";
import { invokeValidator } from "../../src/contracts/external-contract-runtime.ts";
import { unvalidatedPayload } from "../../src/contracts/unvalidated-payload.ts";
import { z } from "../../src/contracts/zod.ts";
import { zodValidator } from "../../src/contracts/zod-validator.ts";
+12
View File
@@ -181,6 +181,18 @@ export default defineConfig(({ mode }) => {
// chunk would import the entry, whose hash changes with each
// build id.
{ name: "preload-helper", test: /vite[\\/]preload-helper/ },
// 1101/07-03. Every feature's schemas and runtime half import
// the shared zod adapter. Alone it becomes a chunk of its own
// once two features share it, and every route and runtime
// import then preloads one more file (about 50 gzip bytes of
// initial JavaScript for the second feature). Those imports
// already preload schema-registry.ts, so the adapter rides
// that lazy chunk. Both modules stay off the boot graph.
{
name: "schema-registry",
test: /[\\/]src[\\/]contracts[\\/](?:schema-registry|zod-validator)\.ts$/,
includeDependenciesRecursively: false,
},
{
name: createFeatureChunkGroups(process.cwd()),
// The boot-failure screen's modules stay out of