fix(fanout): 실패 줄에 두 탈출 방법을, 결과 줄에 검토된 예외 수를 적는다

문제: fanout 검사의 실패 줄은 `FAIL <file>:<line> <call> inside
<context>`뿐이라, 제품 팀은 메시지만 보고 커서 runtime이나 검토 주석이라는
두 방법을 알 수 없었다. `// fanout-reviewed:` 주석으로 넘긴 호출 수도
출력하지 않았고, 허용 fixture는 bulk 읽기 하나였다(0929 결정 (가)를 하지
않았다).

고친 것: 실패 줄이 기능 `adapters/`의 `createCursorPaginationRuntime`과
같은 줄의 `// fanout-reviewed: <이유>`를 함께 적는다. 결과 줄과 fixture
줄이 검토된 예외의 수와 위치·이유를 적는다. 허용 fixture에 주석 달린 커서
루프를 더하고, fixture 실행은 그것이 예외로 세어져야 통과한다. 머리 주석과
`docs/operations/ci-quality-gates.md`에 미탐 범위를 적었다.

위험·한계: 휴리스틱 자체(receiver 이름)는 그대로다(1105의 재설계 (나)는
하지 않았다).

검증: desktop `node scripts/run-vitest.ts run
tests/architecture/request-fanout.test.ts` 통과. 검사기를 기준 커밋으로
되돌리면 새 시험 셋이 실패한다.

Refs: 0929/12-01
This commit is contained in:
DongHyeonka
2026-11-13 21:49:58 +09:00
parent aebb7c8c55
commit 923b29be6c
4 changed files with 128 additions and 23 deletions
+8
View File
@@ -491,6 +491,14 @@ gate의 realtime source/fixture 검사는 native SSE/WebSocket/Web Push API가
bootstrap/installed-feature 조합을 차단한다. optional recipe source gate는
uncomposed runtime 전체를 tree-shaking 없이 합성해 catalog의 gzip 예산도
blocking으로 검증한다.
같은 gate의 `check:request-fanout`은 `src/features`·`src/application`에서 루프나 배열
순회 callback 안의 요청(`fetch()`, 이름이 transport인 receiver의 method)을 거절한다.
실패 줄은 두 탈출 방법을 함께 적는다: 기능 `adapters/`에서
`createCursorPaginationRuntime`(`src/adapters/query-cache`)으로 페이지를 받거나, 상한이
있고 검토한 반복이면 그 호출 줄에 `// fanout-reviewed: <이유>`를 적는다. 결과 줄은
주석으로 넘긴 호출의 수와 위치를 적는다. 이름이 다른 receiver(`repository.load()`),
루프가 부르는 이름 있는 함수 안의 요청, 재귀, 순회 전에 만든 promise는 보지 못한다
(`scripts/check-request-fanout.ts` 머리 주석).
`FE-GATE-030`(main 단계)은 reference runtime source·전용 test·catalog metadata를 제거한
임시 repository에서도 base typecheck, architecture, test, build가 통과하는지
검증해 skeleton의 선택성을 유지한다. browser file/storage와 realtime runtime은
+73 -23
View File
@@ -17,6 +17,16 @@ import { parseAsync } from "@babel/core";
* The HTTP runtime itself (src/adapters/http) owns its bounded retry loop and is
* out of scope. A reviewed exception is written on the call's line as
* `// fanout-reviewed: <reason>`.
*
* 0929/12-01. A failure names both ways out: fetch page after page through
* `createCursorPaginationRuntime` (src/adapters/query-cache) assembled in the
* feature's `adapters/`, or mark a bounded, reviewed repetition on the call's
* line. Every reviewed exception is counted and listed in the result line.
*
* What it does not see: a dispatch through a receiver named otherwise
* (`repository.load()`, a destructured `get`), a dispatch in a named function
* that a loop calls, recursion, and promises built before an iteration and
* awaited inside it. Reviews still look for those.
*/
export const REQUEST_FANOUT_ROOTS = Object.freeze(["src/features", "src/application"]);
@@ -44,6 +54,14 @@ const FUNCTION_TYPES = new Set(["ArrowFunctionExpression", "FunctionExpression"]
type Node = { type: string; loc?: { start: { line: number } } } & Record<string, unknown>;
export type FanoutViolation = Readonly<{ file: string; line: number; call: string; context: string }>;
export type FanoutReviewedException = Readonly<{ file: string; line: number; call: string; reason: string }>;
const REVIEWED = /fanout-reviewed:\s*(\S.*?)\s*$/u;
/** How to fix a failure; both ways the source gate accepts. */
export const FANOUT_REMEDY =
"load one page per request with createCursorPaginationRuntime (src/adapters/query-cache) assembled in the " +
"feature's adapters/, or, for a bounded repetition someone reviewed, write `// fanout-reviewed: <reason>` on the call's line";
function receiverName(node: Node | undefined): string | null {
if (!node) return null;
@@ -81,6 +99,14 @@ export async function findRequestFanout(
file: string,
sourceText: string,
): Promise<readonly FanoutViolation[]> {
return (await inspectRequestFanout(file, sourceText)).violations;
}
/** Per-row dispatches, and the ones a `fanout-reviewed:` comment let through. */
export async function inspectRequestFanout(
file: string,
sourceText: string,
): Promise<Readonly<{ violations: readonly FanoutViolation[]; reviewed: readonly FanoutReviewedException[] }>> {
const plugins: ("jsx" | ["typescript", { dts: boolean }])[] = [["typescript", { dts: false }]];
if (file.endsWith(".tsx")) plugins.push("jsx");
const tree = (await parseAsync(sourceText, {
@@ -93,6 +119,7 @@ export async function findRequestFanout(
if (!tree) throw new Error(`cannot parse ${file}`);
const lines = sourceText.split("\n");
const violations: FanoutViolation[] = [];
const reviewed: FanoutReviewedException[] = [];
const visit = (node: Node, parent: Node | undefined, repeating: string | null): void => {
let context = repeating;
@@ -106,9 +133,9 @@ export async function findRequestFanout(
if (node.type === "CallExpression" && context) {
const call = dispatchDescription(node);
const line = node.loc?.start.line ?? 0;
if (call && !/fanout-reviewed:\s*\S/u.test(lines[line - 1] ?? "")) {
violations.push({ file, line, call, context });
}
const reason = REVIEWED.exec(lines[line - 1] ?? "")?.[1];
if (call && reason !== undefined) reviewed.push({ file, line, call, reason });
else if (call) violations.push({ file, line, call, context });
}
for (const [key, value] of Object.entries(node)) {
if (key === "loc" || key === "start" || key === "end" || key === "extra") continue;
@@ -121,7 +148,7 @@ export async function findRequestFanout(
}
};
visit(tree, undefined, null);
return violations;
return { violations, reviewed };
}
async function sourceFiles(directory: string): Promise<string[]> {
@@ -143,39 +170,62 @@ async function sourceFiles(directory: string): Promise<string[]> {
export async function scanRequestFanout(
root: string,
roots: readonly string[] = REQUEST_FANOUT_ROOTS,
): Promise<Readonly<{ files: number; violations: readonly FanoutViolation[] }>> {
): Promise<Readonly<{
files: number;
violations: readonly FanoutViolation[];
reviewed: readonly FanoutReviewedException[];
}>> {
const files = (await Promise.all(roots.map((entry) => sourceFiles(path.join(root, entry))))).flat();
const violations: FanoutViolation[] = [];
const reviewed: FanoutReviewedException[] = [];
for (const file of files) {
violations.push(
...(await findRequestFanout(path.relative(root, file), await readFile(file, "utf8"))),
);
const found = await inspectRequestFanout(path.relative(root, file), await readFile(file, "utf8"));
violations.push(...found.violations);
reviewed.push(...found.reviewed);
}
return { files: files.length, violations };
return { files: files.length, violations, reviewed };
}
export function formatFanoutViolation(violation: FanoutViolation): string {
return `FAIL ${violation.file}:${violation.line} ${violation.call} inside ${violation.context}: ${FANOUT_REMEDY}`;
}
function formatReviewed(reviewed: readonly FanoutReviewedException[]): string {
if (reviewed.length === 0) return "0 reviewed exceptions";
return `${reviewed.length} reviewed exception${reviewed.length === 1 ? "" : "s"} (` +
`${reviewed.map((entry) => `${entry.file}:${entry.line} ${entry.reason}`).join("; ")})`;
}
/**
* The forbidden fixture must be rejected; the allowed fixture must pass, with
* its reviewed cursor loop counted as a reviewed exception.
*/
export async function checkRequestFanoutFixtures(root: string): Promise<Readonly<{ ok: boolean; line: string }>> {
const forbidden = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/forbidden"]);
const allowed = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/allowed"]);
const ok = forbidden.violations.length >= forbidden.files && forbidden.files > 0 &&
allowed.violations.length === 0 && allowed.reviewed.length > 0;
return {
ok,
line: `request fan-out fixtures: forbidden ${forbidden.violations.length} rejected in ${forbidden.files} files, ` +
`allowed ${allowed.violations.length} violations and ${formatReviewed(allowed.reviewed)} ${ok ? "PASS" : "FAIL"}`,
};
}
async function main(): Promise<void> {
const fixture = process.argv.includes("--fixture");
const root = process.cwd();
if (fixture) {
// The forbidden fixture must be rejected; the allowed fixture must pass.
const forbidden = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/forbidden"]);
const allowed = await scanRequestFanout(root, ["tests/fixtures/architecture/request-fanout/allowed"]);
const ok = forbidden.violations.length >= forbidden.files && forbidden.files > 0 && allowed.violations.length === 0;
process.stdout.write(
`request fan-out fixtures: forbidden ${forbidden.violations.length} rejected in ${forbidden.files} files, allowed ${allowed.violations.length} violations ${ok ? "PASS" : "FAIL"}\n`,
);
if (!ok) process.exitCode = 1;
const result = await checkRequestFanoutFixtures(root);
process.stdout.write(`${result.line}\n`);
if (!result.ok) process.exitCode = 1;
return;
}
const result = await scanRequestFanout(root);
for (const violation of result.violations) {
process.stderr.write(
`FAIL ${violation.file}:${violation.line} ${violation.call} inside ${violation.context}\n`,
);
}
for (const violation of result.violations) process.stderr.write(`${formatFanoutViolation(violation)}\n`);
process.stdout.write(
`request fan-out: ${result.files} files scanned, ${result.violations.length} per-row dispatches ${result.violations.length === 0 ? "PASS" : "FAIL"}\n`,
`request fan-out: ${result.files} files scanned, ${result.violations.length} per-row dispatches, ` +
`${formatReviewed(result.reviewed)} ${result.violations.length === 0 ? "PASS" : "FAIL"}\n`,
);
if (result.violations.length > 0) process.exitCode = 1;
}
+29
View File
@@ -3,7 +3,9 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
import {
checkRequestFanoutFixtures,
findRequestFanout,
formatFanoutViolation,
scanRequestFanout,
} from "../../scripts/check-request-fanout.ts";
@@ -21,6 +23,13 @@ describe("no per-row transport loop (frontend N+1 source gate)", () => {
expect(new Set(forbidden.violations.map((violation) => violation.file)).size).toBe(forbidden.files);
expect(forbidden.files).toBe(3);
expect(allowed.violations).toEqual([]);
expect(allowed.reviewed).toEqual([
expect.objectContaining({
file: "tests/fixtures/architecture/request-fanout/allowed/reviewed-cursor-loop.ts",
call: "gateway.page()",
reason: "cursor pages, bounded by maxPages",
}),
]);
});
it("names the dispatch and the repeating construct", async () => {
@@ -40,4 +49,24 @@ describe("no per-row transport loop (frontend N+1 source gate)", () => {
);
expect(violations).toEqual([]);
});
// 0929/12-01. The failure line named only the call, so a product team saw
// neither the cursor runtime nor the reviewed-exception comment, and the
// result line hid how many calls a comment let through.
it("tells the author both ways out on the failure line", async () => {
const [violation] = await findRequestFanout(
"inline.ts",
"export const load = (api: { get(id: string): Promise<unknown> }, ids: string[]) =>\n Promise.all(ids.map((id) => api.get(id)));\n",
);
const line = formatFanoutViolation(violation!);
expect(line).toMatch(/^FAIL inline\.ts:2 api\.get\(\) inside \.map\(\) callback: /u);
expect(line).toContain("createCursorPaginationRuntime (src/adapters/query-cache)");
expect(line).toContain("`// fanout-reviewed: <reason>` on the call's line");
});
it("counts and lists the reviewed exceptions in the fixture result line", async () => {
const result = await checkRequestFanoutFixtures(path.resolve("."));
expect(result.ok).toBe(true);
expect(result.line).toMatch(/allowed 0 violations and 1 reviewed exception \(tests\/fixtures\/architecture\/request-fanout\/allowed\/reviewed-cursor-loop\.ts:\d+ cursor pages, bounded by maxPages\) PASS/u);
});
});
@@ -0,0 +1,18 @@
// Allowed: a cursor loop someone reviewed. Each page needs the cursor the
// previous page returned, so the requests cannot be one bulk read; the count
// is bounded by the page cap. Feature code normally gets this from
// createCursorPaginationRuntime (src/adapters/query-cache).
type Page = Readonly<{ items: readonly string[]; nextCursor: string | null }>;
type Gateway = { page(cursor: string | null): Promise<Page> };
export async function loadAll(gateway: Gateway, maxPages: number) {
const items: string[] = [];
let cursor: string | null = null;
for (let page = 0; page < maxPages; page += 1) {
const next: Page = await gateway.page(cursor); // fanout-reviewed: cursor pages, bounded by maxPages
items.push(...next.items);
if (next.nextCursor === null) break;
cursor = next.nextCursor;
}
return items;
}