Files
clean-architecture-frontend…/tests/unit/backend-contract-drift.test.ts
DongHyeonka 91962e24e3 test(setup): 자식 프로세스를 띄우는 시험이 잰 시간으로 timeout을 정한다
자식 프로세스를 띄우는 Vitest 시험 91개(24파일)가 기본 timeout 10초에
기대고 있었다. 셋은 FE-GATE-013에서만 도는 tests/system 시험이다.
기본값은 프로세스 안에서 도는 시험에 맞춘 값이다. 부하가 높은
desktop에서는 자식 프로세스 시험이 평소보다 크게 느려진다.
FE-GATE-020 drill 사본에서 평소 0.4~1.2초인 문서 시험이 10.6초 걸려
실패했다(2026-11-12). 가장 위험한 것은 tests/architecture/app-build-input
.test.ts로, desktop에서 이미 5.7초까지 걸렸다.

무엇을 고칠지는 desktop 계측으로 정했다.
- test:coverage 묶음(maxWorkers=4)과 test:unit을 세 번씩 돌렸다. 시험마다
  띄운 자식 프로세스는 child_process 함수를 감싸 기록했고, 소요 시간은
  JSON reporter로 받았다.
- 시험마다 실제 timeout은 task.timeout으로 기록했다.
- 자식 프로세스를 띄우는 시험 140개 중 88개가 기본값이었다. tests/system은
  그 묶음에 없어서, 아래 검사가 잡은 셋을 따로 세 번 쟀다.

고친 것:
- tests/helpers/child-process-timeout.ts의 childProcessTimeout(<잰 최대
  ms>)는 그 15배를 30초 단위로 올린 값이다. 15배는 위 0.7초 → 10.6초에서
  왔다. 시험마다 자기가 잰 최대값을 인자로 적어 근거가 호출 자리에 남는다.
- describe 안의 기본값 시험이 모두 자식 프로세스를 띄우면 describe에,
  일부만 띄우면 그 시험에 준다. 프로세스 안에서 도는 시험의 hang을 늦게
  잡지 않으려는 것이다.
- tests/setup.ts가 child_process 함수를 감싼다. 기본 timeout인 시험이
  자식 프로세스를 띄우면 그 호출에서 실패시키고, helper 이름을 알린다.
  helper나 시험이 import한 스크립트가 띄워도 잡는다. util.promisify가
  읽는 속성은 원래 함수에서 옮긴다.
- docs/work/reference/testing.md 2절에 값 정하는 법과 이 검사를 적었다.

버린 것:
- 전역 testTimeout 올리기: 프로세스 안 시험의 hang을 늦게 잡는다.
- 시험마다 손으로 정한 숫자: 근거가 남지 않고, 이미 있는 값도
  60_000·120_000처럼 근거가 없었다.
- 자식 프로세스를 띄우지 않게 바꾸기: 검사 스크립트를 CLI 그대로 시험하는
  것이 이 시험들의 목적이라 범위가 커진다.
- 파일에 timeout 선언이 있는지만 보는 정적 검사: helper가 띄우는 경우와
  같은 파일의 다른 시험을 놓친다.

위험:
- hook(beforeAll 등)에서 띄우는 프로세스는 검사하지 않는다. 계측에서
  hook이 띄운 곳은 둘이고, 둘 다 180초를 선언했다.
- 같은 파일 안에서 it.concurrent로 도는 시험이 섞이면 어느 시험의
  timeout인지 틀릴 수 있다. 지금은 그런 시험이 없다.
- 다운스트림 시험이 기본값으로 자식 프로세스를 띄우면 test:unit 등이
  실패한다. 메시지가 helper를 알린다.

검증(desktop):
- 다섯 검사(test:unit·check:types·check:ci·lint·verify:documentation)
  rc=0.
- 자식 프로세스를 띄우는 시험 파일 40개와 tests/scale: rc=0, 검사 위반 0.
- tests/system: 115개 중 18개 실패. 모두 bwrap 호스트 제약이고 검사
  위반은 0이다.
- 변이: 검사를 끄면 tests/unit/child-process-timeout.test.ts가 실패한다.
  tracked-artifacts describe의 timeout을 지우면 그 시험이 검사 메시지로
  실패한다.
- 재현: CPU 10% 제한에서 app-build-input·registry-governance·hosting-probe
  ·design-system-rules를 돌렸다. main 650d22fa는 11개가 10초 timeout으로
  실패했다. 이 커밋은 71개 모두 통과했고, 가장 긴 시험은 17.7초였다.
2026-11-12 11:22:59 +09:00

334 lines
12 KiB
TypeScript

import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
/**
* 1105/07-01. `check:backend-contract-drift` on a fake paired backend: a git
* repository with a small `docs/web/http-contract.md`, and a frontend root
* with the pin, the answer table and the table excerpt. The script compared
* only the document between the pin and HEAD, so an answer table or an
* excerpt that disagreed with the pinned document passed, and no checkout
* passed as "skipped".
*/
type Answer = Readonly<{ section: string; code: string; status: number }>;
type Sections = Readonly<Record<string, readonly (readonly string[])[]>>;
const T2A = [
"| 경우 | status | `error.code` | 클라이언트 행동 |",
"| --- | --- | --- | --- |",
"| 재생: 같은 키, 첫 요청 완료 | 첫 요청과 같은 성공 status | — (성공 Envelope) | 받아들인다 |",
"| 처리 중 | 409 | `IDEMPOTENT_IN_FLIGHT` | 같은 키로 다시 보낸다 |",
];
const T2B = [
"| 경우 | status | `error.code` | 클라이언트 행동 |",
"| --- | --- | --- | --- |",
"| 결과 불명 | 503 | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 같은 키로 나중에 |",
];
const T4 = [
"| 코드 | status | 언제 |",
"| --- | --- | --- |",
"| `REQUEST_TIMEOUT` | 503 | 시간 안에 끝나지 않았다 |",
"| `RATE_LIMIT_UNAVAILABLE` | 503 | rate-limit 저장소 응답 없음 |",
];
const SECTIONS: Sections = { "2": [T2A, T2B], "4": [T4] };
const ANSWERS: readonly Answer[] = [
{ section: "2", code: "IDEMPOTENT_IN_FLIGHT", status: 409 },
{ section: "2", code: "IDEMPOTENCY_COMPLETION_UNKNOWN", status: 503 },
{ section: "4", code: "REQUEST_TIMEOUT", status: 503 },
];
const NOT_COPIED = [
{ section: "4", code: "RATE_LIMIT_UNAVAILABLE", reason: "fixture" },
];
function contractDocument(sections: Sections): string {
return [
"# HTTP wire 계약",
"",
"## 1. Envelope",
"",
"| 응답 | 키 |",
"| --- | --- |",
"| 성공 | `data` |",
"",
"## 2. 멱등성 응답",
"",
...(sections["2"]?.[0] ?? []),
"",
"### 저장소가 응답하지 않을 때",
"",
...(sections["2"]?.[1] ?? []),
"",
"## 4. web 전용 오류 코드",
"",
...(sections["4"]?.[0] ?? []),
"",
"## 5. 바꿀 때",
"",
"- 표를 고치면 짝 프론트에 알린다.",
"",
].join("\n");
}
const directories: string[] = [];
afterEach(async () => {
await Promise.all(
directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })),
);
});
function git(cwd: string, ...args: string[]): string {
const result = spawnSync("git", args, {
cwd,
encoding: "utf8",
env: {
...process.env,
GIT_AUTHOR_NAME: "drift-fixture",
GIT_AUTHOR_EMAIL: "drift-fixture@localhost",
GIT_COMMITTER_NAME: "drift-fixture",
GIT_COMMITTER_EMAIL: "drift-fixture@localhost",
},
});
if (result.error || result.status !== 0) {
throw new Error(`fixture git ${args[0]} failed: ${result.stderr || result.error?.message}`);
}
return result.stdout.trim();
}
const DOCUMENT = "docs/web/http-contract.md";
/**
* 1105/16-02. One of the backend scaffold files `create:feature
* --with-create` copies a fact from (the aggregate's name limit).
*/
const AGGREGATE =
"scripts/feature-scaffold/templates/src/domain-core/src/main/java/dev/caskeleton/domain/__feature__/__Feature__.java.tmpl";
const SCAFFOLD_SOURCES = [
{
path: AGGREGATE,
fact: "NAME_MAX_LENGTH 100",
copiedTo: { file: "scripts/create-feature-write-slice.ts", symbol: "BACKEND_NAME_MAX_LENGTH" },
},
];
async function commitFiles(
backend: string,
files: Readonly<Record<string, string>>,
message: string,
): Promise<string> {
for (const [file, text] of Object.entries(files)) {
await mkdir(path.dirname(path.join(backend, file)), { recursive: true });
await writeFile(path.join(backend, file), text);
}
git(backend, "add", "--all");
git(backend, "commit", "--quiet", "--no-gpg-sign", "--no-verify", "-m", message);
return git(backend, "rev-parse", "HEAD");
}
async function drift(
options: Readonly<{
answers?: readonly Answer[];
excerpt?: Sections;
notCopied?: typeof NOT_COPIED;
/** The document of a backend commit after the pin. */
head?: string;
/** 1105/16-02. The scaffold aggregate template in that later commit. */
scaffoldHead?: string;
/** 1105/16-02. A file the pin does not name, in that later commit. */
otherHead?: string;
/** Where the script looks for the backend instead of the fake one. */
backend?: string;
flags?: readonly string[];
}> = {},
) {
const root = await mkdtemp(path.join(tmpdir(), "drift-frontend-"));
const backend = await mkdtemp(path.join(tmpdir(), "drift-backend-"));
directories.push(root, backend);
git(backend, "init", "--quiet", "--initial-branch=fixture");
const commit = await commitFiles(
backend,
{
[DOCUMENT]: contractDocument(SECTIONS),
[AGGREGATE]: "public static final int NAME_MAX_LENGTH = 100;\n",
"README.md": "backend\n",
},
"pinned",
);
const later = {
...(options.head === undefined ? {} : { [DOCUMENT]: options.head }),
...(options.scaffoldHead === undefined ? {} : { [AGGREGATE]: options.scaffoldHead }),
...(options.otherHead === undefined ? {} : { "README.md": options.otherHead }),
};
if (Object.keys(later).length > 0) await commitFiles(backend, later, "after the pin");
const source = {
repository: "clean-architecture-backend-template",
commit,
document: DOCUMENT,
};
const write = async (file: string, value: unknown) => {
await mkdir(path.dirname(path.join(root, file)), { recursive: true });
await writeFile(path.join(root, file), `${JSON.stringify(value, null, 2)}\n`);
};
await write("config/contracts/backend-contract-pin.json", {
schemaVersion: 1,
backend: { ...source, sectionsCompared: ["1", "2", "4"], scaffoldSources: SCAFFOLD_SOURCES },
frontend: {
contractDocument: "docs/architecture/backend-api-and-server-state-contract.md",
contractSections: ["4.1", "6", "6.1"],
readers: ["src/adapters/http/backend-envelope.ts"],
},
tables: {
idempotencyAnswers: "config/contracts/backend-idempotency-answers.json",
backendExcerpt: "config/contracts/backend-http-contract-excerpt.json",
},
notCopied: options.notCopied ?? NOT_COPIED,
owner: "fixture",
comparedOn: "2026-11-05",
});
await write("config/contracts/backend-idempotency-answers.json", {
schemaVersion: 1,
source,
answers: (options.answers ?? ANSWERS).map((answer) => ({
...answer,
refusedBeforeWrite: false,
sameKeyResend: true,
})),
});
await write("config/contracts/backend-http-contract-excerpt.json", {
schemaVersion: 1,
source,
sections: options.excerpt ?? SECTIONS,
});
const result = spawnSync(
process.execPath,
[
path.resolve("scripts/check-backend-contract-drift.ts"),
"--backend",
options.backend ?? backend,
...(options.flags ?? []),
],
{ cwd: root, encoding: "utf8" },
);
return {
status: result.status,
stdout: result.stdout,
stderr: result.stderr,
readExcerpt: async () =>
JSON.parse(
await readFile(path.join(root, "config/contracts/backend-http-contract-excerpt.json"), "utf8"),
) as { sections: Sections },
};
}
describe("check:backend-contract-drift (1105/07-01)", { timeout: childProcessTimeout(450) }, () => {
it("passes when the excerpt and the answer table match the pinned document", async () => {
const result = await drift();
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
});
it("fails when an answer's status is not the pinned document's", async () => {
const result = await drift({
answers: ANSWERS.map((answer) =>
answer.code === "IDEMPOTENCY_COMPLETION_UNKNOWN" ? { ...answer, status: 500 } : answer,
),
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"answer 500 IDEMPOTENCY_COMPLETION_UNKNOWN is not a row of the pinned document's §2",
);
});
it("fails when the excerpt is not the pinned document's, even if the answers follow it", async () => {
const edited = T2B.map((line) => line.replace("| 503 |", "| 500 |"));
const result = await drift({
excerpt: { ...SECTIONS, "2": [T2A, edited] },
answers: ANSWERS.map((answer) =>
answer.code === "IDEMPOTENCY_COMPLETION_UNKNOWN" ? { ...answer, status: 500 } : answer,
),
});
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"excerpt differs from the pinned document: §2 -| 결과 불명 | 500 |",
);
expect(result.stderr).toContain(
"excerpt differs from the pinned document: §2 +| 결과 불명 | 503 |",
);
});
it("fails on a row of the pinned document neither copied nor listed as not copied", async () => {
const result = await drift({ notCopied: [] });
expect(result.status).toBe(1);
expect(result.stderr).toContain(
"§4 503 RATE_LIMIT_UNAVAILABLE is neither in the answer table nor in the pin's notCopied",
);
});
// D6g in the 2026-11-05 review: the backend changes a copied row after the pin.
it("fails on a copied row the backend changed after the pin", async () => {
const result = await drift({
head: contractDocument({
...SECTIONS,
"2": [T2A, T2B.map((line) => line.replace("| 503 |", "| 500 |"))],
}),
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("| 결과 불명 | 500 |");
});
it("does not pass without a backend checkout", async () => {
const result = await drift({ backend: path.join(tmpdir(), "no-such-backend-checkout") });
expect(result.status).toBe(2);
expect(result.stderr).toContain("not compared");
});
it("writes the excerpt from the pinned document with --write-excerpt", async () => {
const result = await drift({
excerpt: { "2": [T2A], "4": [T4.slice(0, 3)] },
flags: ["--write-excerpt"],
});
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect((await result.readExcerpt()).sections).toEqual(SECTIONS);
});
});
/**
* 1105/16-02. `create:feature --with-create` copies four facts from the
* paired backend's feature scaffold (path plural rule, name limit 100, error
* codes, check order). The pin and this script covered only
* `docs/web/http-contract.md`, so a backend that changed its scaffold left
* the frontend generator writing another path, limit or code with no signal.
*/
describe("check:backend-contract-drift scaffold sources (1105/16-02)", { timeout: childProcessTimeout(502) }, () => {
it("reports a scaffold source the generator copies from, with where the copy is", async () => {
const result = await drift({ scaffoldHead: "public static final int NAME_MAX_LENGTH = 120;\n" });
expect(result.status, result.stdout + result.stderr).toBe(1);
expect(result.stderr).toContain(`scaffold source ${AGGREGATE} changed`);
expect(result.stderr).toContain(
"recheck BACKEND_NAME_MAX_LENGTH in scripts/create-feature-write-slice.ts",
);
});
it("passes a later backend commit that changed neither the document nor a scaffold source", async () => {
const result = await drift({ otherHead: "backend, later\n" });
expect(result.stderr).toBe("");
expect(result.status).toBe(0);
expect(result.stdout).toContain("1 scaffold sources unchanged");
});
});