Files
DongHyeonka 762393a940 fix(contracts): 짝 백엔드 pin을 백엔드 main d32b4b53으로 옮긴다
문제: pin(45d2a478)이 백엔드 main보다 한참 뒤라 drift 검사가 exit 1이다.
그사이 백엔드가 폴더를 다시 배치하고(scaffold 원본 셋의 경로) 샘플을
지웠다. 계약 문서 6.1절 근거 파일 넷과 위치 목록이 main에 없고, 매뉴얼
04는 pin과 다른 bbe944bd를 기준이라 적는다. Fileserver 업로드 client의
게시 전 5xx 표는 pin 대조 밖이다(1105/01-02). 백엔드 697e62e8c부터
fileserver의 permit·pool 포화가 429에서 503 SERVER_BUSY로 바뀌어, client는
작업 전에 거절된 업로드를 결과 불명으로 읽는다.

고른 방법(R9-D4):
- pin, 답 표 source, 표 사본(--write-excerpt)을 d32b4b53으로 옮긴다.
  §4의 새 행 404 OPERATION_NOT_FOUND는 durable operation 조회의 답이라
  notCopied에 이유와 함께 둔다.
- scaffold 원본 세 경로를 새 위치로 고친다(내용 0줄 변경 확인).
- pin에 backend.codeSources를 더한다. Fileserver code 파일과 게시 전
  5xx 표(codes)를 적고, readers에 fileserver-upload.ts를 넣는다. drift
  검사가 그 파일들의 변경과, pin 커밋에 없는 경로(옮겨진 파일)를 알린다.
  pin 시험이 client 표와 pin 사본을 양쪽으로 대조한다.
- NOT_APPLIED_5XX_CODES에 SERVER_BUSY를 더한다. raise 자리 둘
  (TransferAdmissionController, BlockingTransferExecutor)이 모두 작업 전이다.
- 6.1절 표의 백엔드 파일:줄을 d32b4b53에서 다시 찾았다. 판정은 같다.
  샘플과 함께 사라진 근거(참조 도메인 행, WorkLogWebMapper 등)는 뺐고,
  새 출처(PatchBodies, 알림 컨트롤러 필드 거절)를 적었다.
- 매뉴얼 04의 기준을 pin으로 바꾸고 백엔드 경로 셋을 고친다.
버린 대안: 문서만 옛 pin 기준으로 맞추기 — drift 검사는 계속 막힌다.

위험·한계: V3 경로의 503 SERVER_BUSY는 상태만 정해진 모든 503에도 붙어
code로 단계를 가를 수 없다. 그래서 V3 표에 넣지 않고 결과 불명 쪽에
둔다(6.1절). 백엔드 main은 계속 움직이므로 다음 백엔드 병합 뒤 drift가
다시 1일 수 있다(설계된 신호).

검증: 노트북, 공유 clone(d32b4b53)으로
node scripts/check-backend-contract-drift.ts --backend <clone>: 옮기기 전
exit 1(문서·scaffold 4건), 옮긴 뒤 exit 0. desktop RED — pin·drift·
업로드 표 시험이 고치기 전 코드에서 실패
(/tmp/claude-gates/r9b-pr1-red/exec_node.log). merge 단계는 PR 본문.

Refs: 1112/02-05, 1112/08-18, 1105/01-02
2026-11-13 19:02:07 +09:00

384 lines
14 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" },
},
];
/** 1105/01-02. A backend code file the frontend reads a code table from. */
const FILESERVER_CODES =
"src/application/fileserver/src/main/java/dev/caskeleton/application/fileserver/api/error/FileserverErrorCode.java";
const CODE_SOURCE = {
path: FILESERVER_CODES,
fact: "5xx before publishing",
copiedTo: { file: "src/adapters/http/fileserver-upload.ts", symbol: "NOT_APPLIED_5XX_CODES" },
codes: ["PARTIAL_WRITE"],
};
const CODE_SOURCES = [CODE_SOURCE];
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;
/** 1105/01-02. The Fileserver code file in that later commit. */
codeHead?: string;
/** S-05. Code sources the pin names, by default the one the backend has. */
codeSources?: readonly (typeof CODE_SOURCE)[];
/** 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",
[FILESERVER_CODES]: "PARTIAL_WRITE(500)\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 }),
...(options.codeHead === undefined ? {} : { [FILESERVER_CODES]: options.codeHead }),
};
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,
codeSources: options.codeSources ?? CODE_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 and 1 code sources unchanged");
});
});
/**
* 1105/01-02. The upload client reads some Fileserver 5xx codes as refused
* before publishing. That table was read by hand from the backend, outside
* every pin comparison, so a backend code change left it with no signal.
*
* 1112/02-05. A source path the pinned commit does not have (the backend moved
* its folders) was read as a deletion between the pin and HEAD, and a pin
* that named the old path at the new commit compared nothing.
*/
describe("check:backend-contract-drift code sources (1105/01-02, 1112/02-05)", { timeout: childProcessTimeout(502) }, () => {
it("reports a code source the frontend copies a table from, with where the copy is", async () => {
const result = await drift({ codeHead: "PARTIAL_WRITE(503)\n" });
expect(result.status, result.stdout + result.stderr).toBe(1);
expect(result.stderr).toContain(`code source ${FILESERVER_CODES} changed`);
expect(result.stderr).toContain(
"recheck NOT_APPLIED_5XX_CODES in src/adapters/http/fileserver-upload.ts",
);
});
it("fails on a source the pinned commit does not have", async () => {
const moved = "src/application-fileserver/FileserverErrorCode.java";
const result = await drift({ codeSources: [{ ...CODE_SOURCE, path: moved }] });
expect(result.status, result.stdout + result.stderr).toBe(1);
expect(result.stderr).toContain(`${moved} is not in the pinned`);
});
});