Files
DongHyeonka c1e258bb81 test(playwright): CI 판정용 재시도로 흔들림을 가리고 실패로 남긴다
Playwright가 재시도하지 않아 실패가 흔들림인지 회귀인지 run에 남지
않는다. CI=true에서만 한 번 더 돌고, 재시도에서 통과해도 실패로
끝낸다. 설정 helper로만 주고 검사기가 설정 객체의 key를 거절한다.

failOnFlakyTests만으로는 재시도에서만 test.fail()에 닿은 시험의 첫
실패가 통과로 바뀐다. helper의 reporter가 실패한 시도를 따로 판정하고
다른 보고에 없는 원인을 색 코드 없이 찍는다. e2e 공유 fixture 빌드는 재시도에서 앞
시도의 실패 기록을 다시 쓰지 않는다(카드 C9). package script와 게이트
args는 029 파서와 이어 쓴 script 때문에 버렸다. CI 판별은 러너 정책이라
CI env를 읽는다.

위험·한계: 많이 깨진 run은 브라우저 게이트가 최대 약 두 배 걸린다
(추정). 명령줄 --reporter는 이 판정 reporter를 뺀다. JUnit에서 실패한
시험의 시간과 failure/error 분류는 첫 시도 기준이 된다. 검사기는 spec
안의 describe.configure({ retries })를 보지 않는다. 빌드가 실패 기록
없이 끊기면(worker 종료, hook 시간 초과) 재시도도 기다리다 실패한다.

검증: main으로 옮기기 전 트리 c8df70ab에서 test:unit 3632개, types,
lint, FE-GATE-029, verify:documentation rc=0, 변이 30개 검출. desktop
실제 브라우저: 일시 빌드 실패는 6 flaky, 계속 실패는 3 failed, 숨은
실패는 rc=1과 원인 출력. 트리 3dea9c06에서 숨은 expect 실패의 색 코드
시험이 고치기 전 1개 실패, 고친 뒤 35개 통과.

Refs: CI-FE-0001
2026-11-23 00:45:11 +09:00

153 lines
5.6 KiB
TypeScript

import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { test } from "@playwright/test";
/**
* One fixture build per Playwright run instead of one per browser project.
*
* The fixture specs build a copy of the repository in `beforeAll`, and every
* browser project runs that hook again: one e2e run made the same builds
* three times, synchronously, while the other workers drove browsers. Those
* builds took the CPU from the browsers next to them, and Firefox's first
* render in a test then missed its 5 s expectation (FE-GATE-008, desktop and
* runner). Builds are the same for every engine and no test writes into them.
*
* With `SHARED_FIXTURE_BUILD_ROOT` set (the e2e config's global setup sets it
* for the run), the first worker that needs `key` builds it under that root and
* the others wait for it and reuse it; the global teardown removes the root.
* A failed build is shared within an attempt only: the CI retry (FLAKY-3)
* reuses a build that succeeded, and else builds again in a folder of its
* retry number, once for all the workers on that retry, so that a build that
* failed once ends flaky and one that fails again ends failed.
* Unset (a Vitest test, another config), every call builds its own copy in a
* new temp folder as before.
*/
export const SHARED_FIXTURE_BUILD_ROOT_VARIABLE = "SHARED_FIXTURE_BUILD_ROOT";
const POLL_MS = 200;
const KEY = /^[a-z0-9][a-z0-9-]{0,63}$/u;
export type SharedFixtureBuild<Value> = Readonly<{
/** The folder `create` built into. */
root: string;
value: Value;
/** Owned by the run (not removable by the spec) when true. */
shared: boolean;
}>;
type BuildRecord = Readonly<{ fingerprint: string; value: unknown }>;
function hasCode(error: unknown, code: string): boolean {
return typeof error === "object" && error !== null && "code" in error && error.code === code;
}
async function readRecord(file: string): Promise<BuildRecord | undefined> {
try {
return JSON.parse(await readFile(file, "utf8")) as BuildRecord;
} catch (error) {
if (hasCode(error, "ENOENT")) return undefined;
throw error;
}
}
async function readFailure(file: string): Promise<string | undefined> {
try {
return await readFile(file, "utf8");
} catch (error) {
if (hasCode(error, "ENOENT")) return undefined;
throw error;
}
}
/** The attempt of the test whose hook asks, in a Playwright worker; 0 anywhere else. */
function runningRetry(environment: NodeJS.ProcessEnv): number {
return environment["TEST_WORKER_INDEX"] === undefined ? 0 : test.info().retry;
}
/**
* `create(root)` fills the empty folder `root` and returns a JSON value that
* describes it (paths under `root`). `fingerprint` names what `create` builds;
* a second caller of the same `key` with another fingerprint is refused.
* `retry` is the caller's attempt: it passes over the failures of those before.
*/
export async function sharedFixtureBuild<Value>(
key: string,
fingerprint: string,
create: (root: string) => Promise<Value>,
environment: NodeJS.ProcessEnv = process.env,
retry: number = runningRetry(environment),
): Promise<SharedFixtureBuild<Value>> {
if (!KEY.test(key)) throw new Error(`Invalid fixture build key: ${key}`);
const sharedRoot = environment[SHARED_FIXTURE_BUILD_ROOT_VARIABLE];
if (!sharedRoot) {
const root = await mkdtemp(path.join(tmpdir(), `${key}-`));
try {
return { root, value: await create(root), shared: false };
} catch (error) {
await rm(root, { recursive: true, force: true });
throw error;
}
}
for (let attempt = 0; ; attempt += 1) {
// The dot keeps a retry's folder apart from every key (see KEY).
const root = path.join(sharedRoot, attempt === 0 ? key : `${key}.retry${attempt}`);
const recordFile = `${root}.json`;
const failureFile = `${root}.failed`;
let owner = true;
try {
await mkdir(root);
} catch (error) {
if (!hasCode(error, "EEXIST")) throw error;
owner = false;
}
if (owner) {
let value: Value;
try {
value = await create(root);
} catch (error) {
await writeFile(failureFile, String(error instanceof Error ? error.stack : error));
throw error;
}
const temporary = `${recordFile}.${process.pid}.tmp`;
await writeFile(temporary, JSON.stringify({ fingerprint, value }));
await rename(temporary, recordFile);
return { root, value, shared: true };
}
// Another worker builds `key`; the spec's own hook timeout bounds this wait.
for (;;) {
const record = await readRecord(recordFile);
if (record) {
if (record.fingerprint !== fingerprint) {
throw new Error(
`Fixture build ${key} was built from another definition in this run.`,
);
}
return { root, value: record.value as Value, shared: true };
}
const failure = await readFailure(failureFile);
if (failure !== undefined) {
if (attempt < retry) break;
throw new Error(`Fixture build ${key} failed in another worker:\n${failure}`);
}
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
}
}
}
/** The e2e config's global setup: a shared root for this run, and its teardown. */
export async function startSharedFixtureBuilds(
environment: NodeJS.ProcessEnv = process.env,
): Promise<() => Promise<void>> {
const root = await mkdtemp(path.join(tmpdir(), "e2e-fixture-builds-"));
environment[SHARED_FIXTURE_BUILD_ROOT_VARIABLE] = root;
return async () => {
delete environment[SHARED_FIXTURE_BUILD_ROOT_VARIABLE];
await rm(root, { recursive: true, force: true });
};
}