test(playwright): CI 판정용 재시도로 흔들림을 가리고 실패로 남긴다 #94
@@ -15,7 +15,7 @@ paths:
|
||||
3. 템플릿 원래 상태 밖에서도 돈다: 기능을 더한 상태, 확장 지점을 채운 상태, 입력·객체가 셋 이상.
|
||||
4. 단언이 대상에 닿는지 본다: fixture가 비어 첫 줄에서 return하지 않는가, 로딩·오류 화면이나 fixture 자신을 검사하지 않는가.
|
||||
5. `.only`를 두지 않는다. `.skip`·`fixme`는 Playwright spec에만, owner·defect·route·만료일이 있는 quarantine으로만 둔다(`scripts/check-test-evidence.ts`). 빠른 계층에는 quarantine이 없다. 편집 훅이 마지막 커밋보다 늘어난 skip·only·fixme·todo를 알린다.
|
||||
6. 가끔 떨어지는 테스트를 재시도·timeout 늘리기·worker 줄이기·`force` 클릭으로 덮지 않는다. 반복 실행 → 실패 기록 → 결정적 재현 → 수정 → 변이 순서로 원인을 찾는다.
|
||||
6. 가끔 떨어지는 테스트를 재시도·timeout 늘리기·worker 줄이기·`force` 클릭으로 덮지 않는다. CI의 판정용 재시도(`flakyJudgement()`, 통과해도 실패)는 덮기가 아니다. 반복 실행 → 실패 기록 → 결정적 재현 → 수정 → 변이 순서로 원인을 찾는다.
|
||||
7. 환경에 기대지 않는다: gitignore된 생성물, 작성자 PC의 글꼴·CPU, 바깥 env(`CI=true`, 빌드 식별값). 테스트가 띄우는 빌드·서버의 env는 테스트가 정한다.
|
||||
8. 플랫폼 테스트를 기능·스타터 화면에 묶지 않는다(테스트 전용 라우트, `tests/mocks/`). 테스트가 지워도 되는 문서(`docs/reviews/` 등)를 읽지 않는다.
|
||||
9. 자식 프로세스를 띄우는 suite는 자기 timeout을 선언한다. 전역 timeout을 올리지 않는다. 기본값보다 긴 timeout은 `childProcessTimeout(<desktop에서 잰 가장 긴 ms>)`로만 준다(손 숫자는 `tests/unit/test-timeout-declarations.test.ts`가 거절).
|
||||
|
||||
@@ -36,7 +36,7 @@ paths:
|
||||
9. 빠른 층에 느린 시험(프로세스를 띄우는 도구 시험, 실제 시계로 기다리는 시험)을 섞거나 같은 파일을 두 번 돈다. 자식 프로세스를 띄우는 suite는 자기 timeout을 선언한다. — 결함 패턴 T8, `docs/testing/taxonomy.md`
|
||||
10. 고정 경로·포트·바깥 env에 기댄다. 브라우저 시험은 `TEST_RUN_ID`와 빈 포트를 쓴다. 시험이 띄우는 빌드·서버의 env는 시험이 정한다(`scripts/lib/build-environment.ts`). `CI=true` 없이 통과한 시험이 실제 CI에서 실패했다. — `docs/work/reference/testing.md` 4절, `docs/work/reference/gates.md` 4절, 결함 패턴 G3·G4
|
||||
11. 새 시험 파일이 어느 게이트에서도 돌지 않는다. 이를 잡는 `check:ci:gating`(FE-GATE-029)은 main 단계라 PR에서는 돌지 않는다. `config/ci/ungated-tests.json`에 줄을 더하는 것은 기준을 낮추는 일이다. — `docs/work/reference/gates.md` 8절
|
||||
12. 가끔 떨어지는 시험을 재시도·timeout 늘리기·worker 줄이기·`force` 클릭으로 덮거나 "부하 탓"으로 닫는다. 부하 탓으로 적었던 두 실패가 모두 시험 결함이었다. — `docs/work/reference/testing.md` 5절
|
||||
12. 가끔 떨어지는 시험을 재시도·timeout 늘리기·worker 줄이기·`force` 클릭으로 덮거나 "부하 탓"으로 닫는다. 부하 탓으로 적었던 두 실패가 모두 시험 결함이었다. CI의 판정용 재시도(`flakyJudgement()`, 통과해도 실패)는 덮기가 아니다. — `docs/work/reference/testing.md` 5절
|
||||
|
||||
## 이 분야에서 실패는 이렇게 보인다
|
||||
|
||||
|
||||
+6
-1
@@ -20,6 +20,10 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
|
||||
- `db6a6eb6`에서 이 범위를 받는 프로젝트는 아래 정리 단계 절의 "먼저 할 일" 15·16·17을 먼저 한다. 그 셋을 들인 브랜치가 이 범위에 든다(절 소개). 아래 시험 timeout 항목은 17이 들인 `childProcessTimeout`을 전제로 한다.
|
||||
- FE-GATE-013은 `scripts/run-in-system-container.sh`가 띄우는 privileged systemd 컨테이너 안에서 돈다. 자기 runner가 job에서 Docker로 privileged 컨테이너를 띄울 수 없으면 이 게이트가 실패한다. 그런 runner면 `docs/operations/ci-quality-gates.md` FE-GATE-013 절의 호스트 조건을 갖춘 runner에서 돌린다.
|
||||
- merge / browser tests job이 Playwright 공식 이미지(`config/ci/gates.json`의 `browser-install.image`, digest 고정)에서 돈다. `@playwright/test`를 올릴 때 이 digest도 같은 버전으로 바꾼다(`tests/unit/ci-browser-image.test.ts`가 막는다).
|
||||
- Playwright 설정은 CI의 판정용 재시도를 공용 helper로만 받는다.
|
||||
- 옮기기 전: 설정의 객체에 `retries`·`failOnFlakyTests` key(따옴표·`["retries"]`·축약 포함)가 있으면 `check:test-evidence`(FE-GATE-008, 레지스트리의 설정)가 실패한다. 루트 `playwright*.config.ts`에 helper, reporter, JUnit `includeRetries` 가운데 하나가 없으면 `tests/unit/playwright-flaky-judgement.test.ts`(FE-GATE-005)가 그 설정 이름을 대며 실패한다.
|
||||
- 옮기는 법: 두 속성을 지우고 `...flakyJudgement()`를 펼친다(`scripts/lib/playwright-flaky-judgement.ts`). `reporter`에 `flakyJudgementReporter`를 넣고 JUnit 옵션에 `includeRetries: true`를 준다. 명령줄 `--reporter`는 설정의 reporter를 바꾸므로 게이트 명령에 쓰지 않는다.
|
||||
- 옮긴 뒤 확인: `scripts/verify.sh gate FE-GATE-005 FE-GATE-008`.
|
||||
- devDependencies에서 `dependency-cruiser`가 빠진다. 그 CLI를 따로 쓰고 있었으면 다시 더한다.
|
||||
- 선택 runtime 제거 드릴 셋이 merge의 FE-GATE-020에서 main 단계의 새 게이트 FE-GATE-030으로 옮는다. main job 이름이 `main / self-tests and removal drills`로 바뀐다. 그 이름을 필수 검사로 걸었으면 바꾼다. 선택 runtime을 바꾸는 PR은 `scripts/verify.sh gate FE-GATE-030`을 직접 돌린다.
|
||||
- merge job 셋과 main job(`main / self-tests and removal drills`)이 runner의 actions/cache 저장소에서 Node·corepack·pnpm store와 메타데이터 캐시를 복원하고, main run만 저장한다. runner에 캐시 서버가 없으면 복원 단계가 경고만 내고 설치가 그대로 돈다. 자기 runner의 캐시 크기 상한을 확인한다(항목 하나가 압축 전 약 0.7GB, lockfile이 바뀔 때마다 새 항목).
|
||||
@@ -137,6 +141,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
|
||||
| [보안] | telemetry payload 정제가 복사하는 값의 총수를 `maxNodes`(기본 512)로 막는다. 같은 객체를 여러 key가 가리키는 payload(정규화된 엔티티 graph 등)를 경로마다 따로 복사해, `emit` 한 번이 호출 스택을 수 초 막거나 heap OOM으로 탭을 죽였다. 여러 경로가 가리키는 객체의 key는 한 번만 읽는다. 순회가 너비 우선이 되어 상한이 차면 얕은 필드가 남고 깊은 값이 `[truncated]`가 된다. 복사본 객체의 key 순서가 원본 순서가 된다(전에는 거꾸로, fingerprint는 그대로). 깊이 제한 시험이 잘린 모양과 순환 payload를 단언한다 | `src/platform/telemetry/redact-telemetry.ts`, `src/platform/telemetry/telemetry-pipeline.ts`, `tests/platform/telemetry/redact-telemetry.test.ts`, `config/scale/feature-shape-ceilings.json` | `d406c10b`, `0190b631` |
|
||||
| [계약] | `mapTransportFailure`가 `JsonBudgetExceededError`의 own data `violation`이 `"invalid-json"`이면 `response.invalid`로 분류한다. 전에는 `parseBoundedJson`이 JSON이 아닌 응답에 던진 오류가 `response.too-large`가 되어 날 `SyntaxError`(`response.invalid`)와 갈렸다. 두 kind의 category(`contract`)·retryability(`never`)는 같다. `violation`이 accessor면 부르지 않고 `response.too-large`로 둔다. 시험 표에 fan-out 초과·`TimeoutError`·invalid-json 줄을 더한다 | `src/platform/errors/platform-errors.ts`, `tests/platform/errors/platform-errors.test.ts` | `a934554d` |
|
||||
| [계약] | `verify:documentation`(FE-GATE-017)의 숫자 복사 검사가 `config/performance/budgets.json`의 예산 값(1000 이상, 천 단위 쉼표가 있든 없든), 세 자리 이상 시험 수(「시험·테스트 N개」「N개 시험」「N tests」「N개(가) 통과·실패」「통과·실패 N개」「N passed·failed」), 조사가 붙은 게이트 개수(「게이트가 29개」)도 본다. 예산 값은 단위를 붙여 써도(「206848B」「2500ms」) 읽는다. 전에는 게이트·recipe·adapter 개수만 봤다. 자기 문서가 이 값을 옮겨 적었으면 실패하니 정본(`budgets.json`, 시험 보고서)을 가리키게 고친다. 양쪽이 숫자인 「A에서 B로」 안의 값은 지난 변경의 기록이라 읽지 않는다. 1000 미만 예산 값, KiB로 쓴 예산, 100 미만 시험 수는 여전히 검사 밖이다 | `scripts/lib/docs-system.ts` | `d460a5f8`, `9aab9c0f`, `a0e3644a` |
|
||||
| [계약] | Playwright 여섯 설정이 `CI=true`에서만 실패한 시험을 한 번 더 돌고, 재시도에서 통과해도 실패로 끝난다. 흔들린 시험의 JUnit testcase에는 첫 실패가 expect 실패(expect 시간 초과 포함)면 `<flakyFailure>`, 시험 시간 초과·throw·worker crash면 `<flakyError>`가 남고, 예상 실패(`test.fail()`)가 통과한 것이면 아무 자식도 남지 않는다. 그래서 흔들림 수는 JUnit 요소 하나로 세지 않고 `N flaky` 줄로 본다. testcase 수는 그대로다. `failOnFlakyTests`가 놓치는 경우(재시도에서만 `test.fail()`이 불린 시험)는 helper의 reporter가 실패시키고 그 시도의 project와 오류를 찍는다. e2e 공유 fixture 빌드는 재시도가 앞 시도의 실패 기록을 다시 쓰지 않고 한 번 더 빌드한다(성공한 빌드는 다시 쓴다). `check:test-evidence`가 레지스트리에 든 설정의 `retries`·`failOnFlakyTests` key를 거절한다(주석과 `"http-retries"` 같은 긴 key는 세지 않는다). 많이 깨진 run은 브라우저 게이트가 더 오래 돈다. 위 "먼저 할 일" | `scripts/lib/playwright-flaky-judgement.ts`, `playwright.config.ts`와 다른 Playwright 설정, `scripts/check-test-evidence.ts`, `tests/e2e/support/shared-fixture-builds.ts`, `tests/unit/playwright-flaky-judgement.test.ts`, `tests/unit/shared-fixture-builds.test.ts` | `c1e258bb` |
|
||||
|
||||
### 그 밖의 변경
|
||||
|
||||
@@ -157,7 +162,7 @@ Gitea runner에서 merge 단계를 초록으로 만들고, worker를 늘리지
|
||||
| HTTP 실행기의 deadline 분류 시험이 가짜 시계로 대기 지점에서 deadline을 낸다. 실제 30ms deadline이 부하에서 backoff 전에 지나 TIMEOUT 대신 전송 실패로 끝났다 | `tests/unit/http-execution-v3.test.ts` | `37a85004` |
|
||||
| provider guardian이 commit 전에 죽었는데 supervisor가 그 종료를 보기 전에 COMMIT을 써 `EPIPE`가 나도, commit 실패가 guardian 종료(`provider guardian failed: exit=…, signal=…`)를 말하고 쓰기 오류는 `cause`로 붙는다. 시스템 시험이 가끔 `write EPIPE`만 남겼다 | `scripts/lib/provider-guardian-client.ts`, `tests/integration/provider-guardian-transaction.test.ts`, `docs/operations/ci-quality-gates.md` | `f6300949` |
|
||||
| 위험 커버리지가 `"use strict"` 밖의 지시문(`"use client"` 등)을 문장으로 센다. V8 coverage가 그렇게 센다(`check:v8-coverage-counter-semantics` fixture에 지시문 모듈 둘) | `scripts/lib/risk-coverage.ts`, `scripts/lib/v8-coverage-counter-semantics.ts` | `0c3c9d33` |
|
||||
| e2e fixture build를 브라우저 project마다가 아니라 run에 한 번 만든다. global setup이 공유 폴더를 만들고 처음 닿은 worker만 build한다. 자기 spec에서 `prepareServiceWorkerBuilds`를 부르면 `key`를 준다. Service Worker 빌드 helper도 같은 준비 함수(`buildEditedCopies`)를 쓴다. 시험 분류 문서가 build가 공유된다고 적는다 (0929/11-07) | `playwright.config.ts`, `tests/e2e/support/shared-fixture-builds.ts`, `tests/e2e/support/fixture-builds.ts`, `tests/e2e/support/service-worker-builds.ts`, `docs/testing/taxonomy.md` | `c6d7f43a`, `e4701b21`, `52e1a471`, `dec8a9db` |
|
||||
| e2e fixture build를 브라우저 project마다가 아니라 run에 한 번 만든다(실패한 build는 CI 재시도에서 한 번 더 만든다). global setup이 공유 폴더를 만들고 처음 닿은 worker만 build한다. 자기 spec에서 `prepareServiceWorkerBuilds`를 부르면 `key`를 준다. Service Worker 빌드 helper도 같은 준비 함수(`buildEditedCopies`)를 쓴다. 시험 분류 문서가 build가 공유된다고 적는다 (0929/11-07) | `playwright.config.ts`, `tests/e2e/support/shared-fixture-builds.ts`, `tests/e2e/support/fixture-builds.ts`, `tests/e2e/support/service-worker-builds.ts`, `docs/testing/taxonomy.md` | `c6d7f43a`, `e4701b21`, `52e1a471`, `dec8a9db` |
|
||||
| FE-GATE-013의 시스템 컨테이너가 systemd 전에 root cgroup 제어기를 켠다. 부팅 중 `docker exec`가 root cgroup에 남으면 systemd가 user manager에 제어기를 넘기지 못해 provider 시험 18개가 exit 125로 떨어졌다(desktop 4회 중 1회). 사전 점검이 user manager의 cpu·memory·pids 제어기를 보고, provider 실패 메시지에 우리 단계가 쓴 고정 이유 줄을 남긴다 | `scripts/run-in-system-container.sh`, `scripts/check-system-test-prerequisites.ts`, `scripts/lib/provider-sandbox-diagnostics.ts`, `scripts/run-and-validate-provider.ts`, `scripts/lib/provider-scope-wrapper.ts` | `6d6fd61a`, `4e1a385f`, `13b40934` |
|
||||
| `useApplicationQuery`가 「데이터가 있고 마지막 조회가 실패했다」를 렌더 중에 계산한다. 낡은 데이터를 다시 시도하는 동안 지난 실패 대신 refreshing을 보인다. query·mutation 실패 진단이 실패의 `kind`를 남기고, 예상 밖 throw는 정의 이름을 쓴다. 진단 `error_kind` 값을 읽는 대시보드가 있으면 바꾼다 (1112/01-05, 1112/01-04) | `src/presentation/adapters/query/application-query.ts` | `d4aa365b` |
|
||||
| 공통 primitive의 키보드·보조기술 동작을 맞춘다. Popover가 이름 있는 dialog를 그린다. Dialog 안의 Menu·Popover·Tooltip에서 누른 Escape가 Dialog까지 닫지 않고, Dialog 밖에 열린 popover·tooltip은 Dialog의 Escape를 먹지 않는다(`src/presentation/design-system/primitives/escape-layer.ts`). SearchField·Checkbox가 필수를 기호와 입력 상태 둘로 알린다. TextArea 글자 수는 `aria-describedby`로 입력에 잇고 0에 닿을 때만 따로 발표한다. 닫기 버튼으로 닫은 Toast는 다음 toast의 닫기 버튼, 없으면 들어오기 전 요소로 포커스를 돌린다. 라우트 h1은 `:focus:not(:focus-visible)`만 outline을 지워 첫 화면 heading에 포커스 링이 보인다(템플릿 시각 골든 넷을 다시 찍었다). Tooltip은 포인터를 설명 위로 옮겨도 남는다. 홈 준비 목록이 role 없는 요소에 이름을 달지 않는다. fe-a11y·fe-ux 스킬이 제출 실패 때 포커스가 첫 오류 필드로 간다고 적는다 (1112/05-02, 1112/05-06, 1112/05-09, 1112/05-10, 1112/05-11, 1112/05-13, 1112/05-14, 1112/05-15, 1112/05-17) | `src/presentation/design-system/primitives/`, `src/presentation/styles/theme/`, `.claude/skills/fe-a11y/SKILL.md`, `.claude/skills/fe-ux/SKILL.md` | `353bed7a`, `42b183f7`, `20a9d900`, `ceafab66` |
|
||||
|
||||
@@ -62,3 +62,5 @@
|
||||
| `verdict` | 판정 결과(예: 「8회 중 1회 실패」, 「재현 안 됨」)와 원인 |
|
||||
| `quarantined_until` | 격리했으면 기한, 아니면 빈 값 |
|
||||
| `fixed_by` | 고친 PR(`프론트 #47` 형식), 아직이면 빈 값 |
|
||||
|
||||
CI 보고서의 flaky는 design-docs `ci/manual.md` 8.3절 1단계의 「섞임」이다. 그때 `first_run`에 그 run 번호를, `verdict`에 「runner run N, 재시도 1회에서 통과(flaky)」를 적는다.
|
||||
|
||||
@@ -60,10 +60,10 @@ runner는 gitignore된 `src/.generated/` 제품 index를 먼저
|
||||
직접 지정할 때만 모은다(`test:system`이 그렇게 한다). 그래서 맨 `vitest` 실행은
|
||||
CI runner suite를 시작하지 않는다.
|
||||
|
||||
저장소 사본을 build하는 e2e spec(fixture build)은 e2e 실행 하나에 한 번만 build한다.
|
||||
저장소 사본을 build하는 e2e spec(fixture build)은 e2e 실행 하나에서 성공한 build를 다시 하지 않는다.
|
||||
`playwright.config.ts`의 global setup이 공유 폴더를 만들고, 브라우저 project 셋 가운데
|
||||
그 build에 처음 닿은 worker만 build한다. 나머지 worker는 그 결과를 기다려 쓴다
|
||||
(`tests/e2e/support/shared-fixture-builds.ts`). 공유 폴더가 없는 실행(Vitest 시험, 다른
|
||||
(`tests/e2e/support/shared-fixture-builds.ts`). 실패한 build는 CI 재시도에서 한 번 더 한다. 공유 폴더가 없는 실행(Vitest 시험, 다른
|
||||
Playwright 설정)은 부를 때마다 자기 사본을 만든다. 다른 project가 같은 폴더를 쓰므로
|
||||
시험은 build 폴더에 쓰지 않는다. 사본을 고치는 일은 build 전의 `edit`에서만 한다.
|
||||
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
- 리팩터링: 지킬 동작·타입·실패·진단을 "보존 조건"으로 먼저 적는다(리뷰 가이드 36.3·39.9절). 기존 테스트가 그 조건을 지키는지 보고, 못 지키면 테스트부터 더한다. 바꾼 뒤 같은 테스트가 그대로 통과해야 한다. 테스트를 고쳐야 통과하면 동작이 바뀐 것이다. 소비자 없는 확장 지점은 지우지 않고, 갈라진 복사본은 하나로 합친다.
|
||||
- 성능: [reference/performance.md](reference/performance.md)의 조건으로 기준선을 다시 잰다 → 원인을 좁힌다(waterfall·청크 목록·trace) → 변경 하나 → 대조군(바꾸기 전 커밋)과 같은 세션에서 다시 잰다. 지난 측정값을 기준선으로 쓰지 않는다.
|
||||
- 구조 변경: 설계와 대안을 먼저 적고, [reference/structure.md](reference/structure.md) 3절 「바꿀 때 같이 고칠 것」을 같은 커밋에서 고친 뒤 제거 드릴(FE-GATE-020)을 돌린다.
|
||||
- 테스트 구조: [reference/testing.md](reference/testing.md). 가끔 떨어지는 테스트는 재시도·timeout으로 덮지 않고 반복 실행 → 실패 기록 → 결정적 재현 → 수정 → 변이 순서로 원인을 찾는다.
|
||||
- 테스트 구조: [reference/testing.md](reference/testing.md). 가끔 떨어지는 테스트는 재시도·timeout으로 덮지 않고 반복 실행 → 실패 기록 → 결정적 재현 → 수정 → 변이 순서로 원인을 찾는다. CI의 판정용 재시도(`flakyJudgement()`, 통과해도 실패)는 덮기가 아니다.
|
||||
|
||||
### 4.4 수정 라운드와 묶음
|
||||
|
||||
|
||||
@@ -77,6 +77,7 @@
|
||||
| FE-7 main job도 의존성 캐시 | 2026-11-20 | 2026-11-13 「의존성 캐시는 merge job만」을 바꾼다. main job(`main_gate`, FE-GATE-029·030)도 merge job 셋과 같은 키·경로로 캐시를 복원한다. 저장은 그대로 main run만 하고, 설치는 그대로 `--frozen-lockfile`이다. release·promotion·provider job은 그대로 매번 새로 설치한다. 이유: main job만 install이 15~24초였다(merge job은 1~2초). main job은 공급망 증거를 만들지 않는다. 재검토: main job이 공급망 증거를 만들게 되면 release·promotion job처럼 매번 새로 설치하게 되돌린다. main run 로그의 install step이 캐시를 복원해도 줄지 않으면 캐시 step을 뺀다 | 총괄(2026-11-20): design-docs `ci/06-frontend-ci-speed-handoff.md` 4.2절 |
|
||||
| FE-4 005 안 일반 실행 빼기 | 2026-11-20 | FE-GATE-005는 `tests/unit`·`tests/contract`를 `test:coverage`에서 한 번만 돈다. `test:unit`·`test:contract` 명령을 게이트에서 빼고, 같은 coverage 실행에서 `scripts/lib/coverage-bundle-junit-reporter.ts`가 `artifacts/tests/unit.xml`·`contract.xml`을 쓴다. 증거 이름과 게이트 ID는 그대로이고, 두 증거는 FE-GATE-005의 명령이 그 실행 중에 새로 만든다. 전제(게이트마다 증거를 새로 만든다)는 그대로다. 버린 안: coverage 실행 한 번이 FE-GATE-004·006·007의 증거까지 내기(design-docs `ci/04-…` R-3 (가), 약 −1:30). 그 세 게이트가 FE-GATE-005의 결과를 읽게 되어 FE-6에서 버린 꼴과 같다: coverage 실행이 죽으면 세 게이트도 판정을 못 내고, 혼자 돌릴 수 없다. 004는 005보다 앞이라 차례도 바꿔야 했다. 이유: FE-GATE-005 안에서 같은 시험 파일을 두 번 돌았다(약 0:57). 대가: unit·contract 시험은 이제 coverage 계측 아래에서만 돈다. 시간에 기대는 시험이 가려질 수 있다. 004·006·007의 묶음은 coverage에서 한 번 더 돈다(약 0:33). 재검토: coverage 실행에서 안 보이고 일반 실행에서만 보이는 unit·contract 실패가 나오면 일반 실행을 되돌린다. Vitest를 올릴 때는 reporter가 그 JUnit reporter에 기대므로 분할한 보고서를 일반 실행과 다시 대조한다 | 총괄(2026-11-20): 소유자 2026-11-19 CI 속도 지시, design-docs `ci/06-frontend-ci-speed-handoff.md` 4.3·6.2절 |
|
||||
| DES-DEC-0002 perContext 기록 대조 바닥 | 2026-11-21 | FE-GATE-005의 기록 대조(`initialJavascriptRecordDrift`, `scripts/scale/measure-feature-shape-growth.ts`)에서 perContextGzipBytes 칸만 바닥을 16 B에서 64 B로 넓힌다(`PER_CONTEXT_RECORD_TOLERANCE_BYTES`). 다른 비용 칸의 16 B, 합계 256 B, context 상한 512 B·기능 상한 1 KiB, `config/scale/feature-shape-ceilings.json`은 그대로다. D-6(프론트 main 뒤처짐 막기 끔)도 그대로 둔다: 2026-11에 센 다시 볼 조건(합치면 깨지는 변경으로 한 주 두 번 넘게 빨강)이 W46 1회·W47 0회로 채워지지 않았다. 이유(확인한 사실): 이 칸은 한 커밋에서는 같은 값이고 커밋 사이에서는 2~28 B(잰 값과 기록, 최대 차 26 B)를 오간다. 초기 청크를 바꾼 PR이 먼저 병합된 뒤 다른 PR이 낡은 base에서 잰 기록을 쓰면 main이 빨강이 됐다(#56 병합 `e98d8ee9`, 기록 28·빌드 7). 64 B는 그 최대 차의 두 배 넘게, context 상한의 1/8이다. 게이트 문턱을 넓히는 일이라 소유자가 정했다(꼭 지킬 것 4). 버린 안: 둘 다 그대로(PR을 하나씩 최신 main에서 여는 관행이 깨지면 같은 빨강), 뒤처짐 막기 켬(병합마다 갱신 run 15~24분), context 여럿 평균(줄일 잡음이 있는지 모르고 측정 시간이 는다), perContext 대조 빼기(기록이 낡아도 못 잡는다). 대가: 기록이 빌드와 64 B까지 달라도 통과한다. 재검토: 64 B 바닥에서도 perContext 기록 불일치로 main이 빨강이 되거나, 합치면 깨지는 변경으로 main이 한 ISO 주에 두 번 넘게 빨강이 된다 | 소유자 결정(2026-11-21, 답 원문 「전부 권함대로」): design 허브 DES-DEC-0002(repo 밖, 항목 DES-FE-0007) |
|
||||
| CI 계획 D-3 판정용 재시도 | 2026-11-13 | CI(`CI=true`)에서만 Playwright가 실패한 시험을 한 번 더 돌고, 재시도에서 통과해도 게이트는 실패한다. 0925의 D-3(Web Lock 직렬화)과 다른 결정이다. 재시도는 설정 helper `flakyJudgement()`로만 주고(`scripts/lib/playwright-flaky-judgement.ts`), `scripts/check-test-evidence.ts`는 `config/repository-layout.json`의 `playwright-configs`에 든 설정(dev 설정은 없다)에서 객체 key로 직접 쓴 두 옵션을 거절한다. 펼침·변수·helper 인자로 바뀐 값과 dev 설정은 `tests/unit/playwright-flaky-judgement.test.ts`가 루트 설정마다 계산된 값으로 잡는다. spec 안의 `describe.configure({ retries })`는 둘 다 보지 않는다. `failOnFlakyTests`만으로는 본문의 `test.fail()`이 재시도에서만 불린 시험의 첫 실패가 통과로 바뀐다. 그래서 같은 파일의 reporter가 실패한 시도가 있으면 run을 실패로 끝내고, 다른 보고에 없는 그 오류를 찍는다(2026-11-22 구현에서 확인). 재시도는 e2e 공유 fixture 빌드의 앞 시도 실패 기록을 다시 쓰지 않는다(CI-FE-0001 C9). 이유: 흔들림과 회귀를 같은 run에서 가린다. 전에는 세션이 desktop에서 손으로 세 번 돌렸다. 대가: 실패한 시험만큼 시간이 든다. 많이 깨진 PR은 FE-GATE-008이 최대 약 두 배 걸린다(추정). 버린 안: 재시도 없음 그대로(판정 근거가 run에 없다), `retries`만 켜기(흔들림을 덮는다), package script·`config/ci/gates.json` args로 주기(FE-GATE-029가 부분 실행으로 세거나 Playwright에 닿지 않는다). 재검토: Playwright를 올려 `tests/unit/playwright-flaky-judgement.test.ts`가 실패하거나, 재시도 때문에 browser job이 시간 상한에 닿는다 | 권하는 안으로 정함(총괄, 2026-11-13): design-docs `ci/03-time-reduction-plan.md` 5절. 위임: 소유자 원문(2026-11-11 23:09 KST, 백엔드 세션 직접 입력) 「앞으로 카드 띄우지 말고 너가 판단하고 바로바로 진행할 수 있도록」·「최종 보고만 받을 수 있게」. 이 결정을 따로 묻고 받은 소유자 답은 없다 |
|
||||
| 구조·기술 결정 기록 | 2026-07-26~ | `VD-01`~(빈 번호 있음) | `docs/adr/` |
|
||||
|
||||
## 3. 결정 대기 쓰는 법
|
||||
|
||||
@@ -81,7 +81,7 @@
|
||||
|
||||
**금지.**
|
||||
|
||||
- 재시도, timeout 늘리기, worker 줄이기, `force` 클릭·합성 이벤트로 덮지 않는다.
|
||||
- 재시도, timeout 늘리기, worker 줄이기, `force` 클릭·합성 이벤트로 덮지 않는다. CI의 판정용 재시도(`flakyJudgement()`, 통과해도 실패)는 덮기가 아니다. 재시도는 그 helper(`scripts/lib/playwright-flaky-judgement.ts`)로만 준다. 새 Playwright 설정은 helper를 펼치고 같은 파일의 reporter(`flakyJudgementReporter`)를 `reporter`에 넣는다(`tests/unit/playwright-flaky-judgement.test.ts`가 본다).
|
||||
- skip은 Playwright spec에만, owner·defect·route·만료일이 있는 quarantine으로만 둔다(`scripts/check-test-evidence.ts`). 빠른 계층에는 quarantine이 없다. 고치거나 느린 층으로 옮긴다(소유자 결정 2026-11-03).
|
||||
- "부하 탓"으로 닫지 않는다. 부하를 낮춘 재현과 결정적 재현으로 확인하기 전에는 원인이 아니다. 부하 탓으로 적었던 두 실패가 모두 테스트 결함이었다.
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
import e2eConfig from "./playwright.config.ts";
|
||||
import { flakyJudgementReporter } from "./scripts/lib/playwright-flaky-judgement.ts";
|
||||
import { testRunPath } from "./scripts/lib/run-isolation.ts";
|
||||
|
||||
// test:a11y (FE-GATE-009) runs the @a11y specs on the e2e build, browsers and
|
||||
@@ -20,7 +21,11 @@ export default defineConfig({
|
||||
outputDir: testRunPath("artifacts/tests/a11y/results"),
|
||||
reporter: [
|
||||
["list"],
|
||||
flakyJudgementReporter,
|
||||
["html", { outputFolder: testRunPath("artifacts/tests/a11y/report"), open: "never" }],
|
||||
["junit", { outputFile: testRunPath("artifacts/tests/a11y/results.xml") }],
|
||||
[
|
||||
"junit",
|
||||
{ outputFile: testRunPath("artifacts/tests/a11y/results.xml"), includeRetries: true },
|
||||
],
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
import { LOCAL_BUILD_IDENTITY } from "./scripts/lib/build-environment.ts";
|
||||
import { flakyJudgement, flakyJudgementReporter } from "./scripts/lib/playwright-flaky-judgement.ts";
|
||||
import {
|
||||
reservePort,
|
||||
RUN_OUTPUT_ROOT_VARIABLE,
|
||||
@@ -19,9 +20,11 @@ const origin = `http://127.0.0.1:${port}`;
|
||||
export default defineConfig({
|
||||
testDir: "./tests/browser-capabilities",
|
||||
forbidOnly: true,
|
||||
...flakyJudgement(),
|
||||
outputDir: testRunPath("artifacts/tests/browser-capabilities/results"),
|
||||
reporter: [
|
||||
["list"],
|
||||
flakyJudgementReporter,
|
||||
[
|
||||
"html",
|
||||
{
|
||||
@@ -33,6 +36,7 @@ export default defineConfig({
|
||||
"junit",
|
||||
{
|
||||
outputFile: testRunPath("artifacts/tests/browser-capabilities/results.xml"),
|
||||
includeRetries: true,
|
||||
},
|
||||
],
|
||||
],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
import { flakyJudgement, flakyJudgementReporter } from "./scripts/lib/playwright-flaky-judgement.ts";
|
||||
import {
|
||||
reservePort,
|
||||
RUN_OUTPUT_ROOT_VARIABLE,
|
||||
@@ -25,11 +26,16 @@ export default defineConfig({
|
||||
// browser project (tests/e2e/support/shared-fixture-builds.ts).
|
||||
globalSetup: "./tests/e2e/support/e2e-global-setup.ts",
|
||||
forbidOnly: true,
|
||||
...flakyJudgement(),
|
||||
outputDir: testRunPath("artifacts/tests/e2e/results"),
|
||||
reporter: [
|
||||
["list"],
|
||||
flakyJudgementReporter,
|
||||
["html", { outputFolder: testRunPath("artifacts/tests/e2e/report"), open: "never" }],
|
||||
["junit", { outputFile: testRunPath("artifacts/tests/e2e/results.xml") }],
|
||||
[
|
||||
"junit",
|
||||
{ outputFile: testRunPath("artifacts/tests/e2e/results.xml"), includeRetries: true },
|
||||
],
|
||||
],
|
||||
use: {
|
||||
baseURL: origin,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { defineConfig } from "@playwright/test";
|
||||
|
||||
import releaseConfig from "./playwright.config.ts";
|
||||
import { LOCAL_BUILD_IDENTITY } from "./scripts/lib/build-environment.ts";
|
||||
import { flakyJudgementReporter } from "./scripts/lib/playwright-flaky-judgement.ts";
|
||||
import {
|
||||
reservePort,
|
||||
RUN_OUTPUT_ROOT_VARIABLE,
|
||||
@@ -25,8 +26,12 @@ export default defineConfig({
|
||||
outputDir: testRunPath("artifacts/tests/e2e-dev/results"),
|
||||
reporter: [
|
||||
["list"],
|
||||
flakyJudgementReporter,
|
||||
["html", { outputFolder: testRunPath("artifacts/tests/e2e-dev/report"), open: "never" }],
|
||||
["junit", { outputFile: testRunPath("artifacts/tests/e2e-dev/results.xml") }],
|
||||
[
|
||||
"junit",
|
||||
{ outputFile: testRunPath("artifacts/tests/e2e-dev/results.xml"), includeRetries: true },
|
||||
],
|
||||
],
|
||||
use: {
|
||||
...releaseConfig.use,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
import { flakyJudgement, flakyJudgementReporter } from "./scripts/lib/playwright-flaky-judgement.ts";
|
||||
import {
|
||||
reservePort,
|
||||
TEST_PORT_VARIABLES,
|
||||
@@ -16,9 +17,11 @@ const origin = `http://127.0.0.1:${port}`;
|
||||
export default defineConfig({
|
||||
testDir: "./tests/storybook",
|
||||
forbidOnly: true,
|
||||
...flakyJudgement(),
|
||||
outputDir: testRunPath("artifacts/tests/storybook/results"),
|
||||
reporter: [
|
||||
["list"],
|
||||
flakyJudgementReporter,
|
||||
[
|
||||
"html",
|
||||
{
|
||||
@@ -28,7 +31,7 @@ export default defineConfig({
|
||||
],
|
||||
[
|
||||
"junit",
|
||||
{ outputFile: testRunPath("artifacts/tests/storybook/results.xml") },
|
||||
{ outputFile: testRunPath("artifacts/tests/storybook/results.xml"), includeRetries: true },
|
||||
],
|
||||
],
|
||||
use: {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { defineConfig, devices } from "@playwright/test";
|
||||
|
||||
import { LOCAL_BUILD_IDENTITY } from "./scripts/lib/build-environment.ts";
|
||||
import { flakyJudgement, flakyJudgementReporter } from "./scripts/lib/playwright-flaky-judgement.ts";
|
||||
import {
|
||||
reservePort,
|
||||
RUN_OUTPUT_ROOT_VARIABLE,
|
||||
@@ -28,15 +29,20 @@ const workshopPort = await reservePort(TEST_PORT_VARIABLES.visualWorkshop);
|
||||
export default defineConfig({
|
||||
testDir: "./tests/visual",
|
||||
forbidOnly: true,
|
||||
...flakyJudgement(),
|
||||
snapshotDir: "./tests/visual/__snapshots__",
|
||||
outputDir: testRunPath("artifacts/tests/visual/results"),
|
||||
reporter: [
|
||||
["list"],
|
||||
flakyJudgementReporter,
|
||||
[
|
||||
"html",
|
||||
{ outputFolder: testRunPath("artifacts/tests/visual/report"), open: "never" },
|
||||
],
|
||||
["junit", { outputFile: testRunPath("artifacts/tests/visual/results.xml") }],
|
||||
[
|
||||
"junit",
|
||||
{ outputFile: testRunPath("artifacts/tests/visual/results.xml"), includeRetries: true },
|
||||
],
|
||||
],
|
||||
expect: {
|
||||
toHaveScreenshot: {
|
||||
|
||||
@@ -103,6 +103,7 @@ const TEST_NAMES = new Set(["test", "it", "describe"]);
|
||||
// a test object that is itself a test object.
|
||||
const TEST_MEMBERS = new Set([...TEST_NAMES, "serial", "parallel", "step"]);
|
||||
const SKIP_METHODS = new Set(["skip", "fixme"]);
|
||||
const RETRY_OPTIONS = new Set(["retries", "failOnFlakyTests"]);
|
||||
const SYNTAX_METADATA = new Set([
|
||||
"loc",
|
||||
"start",
|
||||
@@ -267,8 +268,7 @@ function parserPlugins(file: string): BabelParserPlugin[] {
|
||||
return ["typescript"];
|
||||
}
|
||||
|
||||
/** Each `skip`·`fixme` call on a test object, as `<callee> at line <n>` (e.g. `testInfo.skip at line 3`). */
|
||||
async function skipCalls(file: string, source: string): Promise<string[]> {
|
||||
async function parseSyntax(file: string, source: string): Promise<SyntaxNode> {
|
||||
const syntaxTree = await parseAsync(source, {
|
||||
filename: file,
|
||||
babelrc: false,
|
||||
@@ -277,6 +277,26 @@ async function skipCalls(file: string, source: string): Promise<string[]> {
|
||||
parserOpts: { plugins: parserPlugins(file) },
|
||||
});
|
||||
if (!isSyntaxNode(syntaxTree)) throw new Error("Babel returned no syntax tree");
|
||||
return syntaxTree;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an object in `source` has a `retries`·`failOnFlakyTests` key: plain,
|
||||
* quoted, `["retries"]` or shorthand. A comment, a string and a longer key
|
||||
* ("http-retries") are none.
|
||||
*/
|
||||
async function setsRetryOption(file: string, source: string): Promise<boolean> {
|
||||
let found = false;
|
||||
walkSyntax(await parseSyntax(file, source), (node) => {
|
||||
if (node.type !== "ObjectProperty" && node.type !== "ObjectMethod") return;
|
||||
if (RETRY_OPTIONS.has(staticName(node["key"], node["computed"] === true) ?? "")) found = true;
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
/** Each `skip`·`fixme` call on a test object, as `<callee> at line <n>` (e.g. `testInfo.skip at line 3`). */
|
||||
async function skipCalls(file: string, source: string): Promise<string[]> {
|
||||
const syntaxTree = await parseSyntax(file, source);
|
||||
const names = testObjectNames(syntaxTree);
|
||||
const calls: string[] = [];
|
||||
walkSyntax(syntaxTree, (node) => {
|
||||
@@ -616,6 +636,24 @@ async function playwrightConfigFailures(
|
||||
if (!source.includes("forbidOnly: true")) {
|
||||
failures.push(`${config}: missing forbidOnly: true, so a committed test.only passes the gate`);
|
||||
}
|
||||
// FLAKY-3: a retry set anywhere but flakyJudgement() lets a test that
|
||||
// passes on its retry pass the gate. A property after the spread wins, so
|
||||
// any failOnFlakyTests of the config's own is refused with it. This reads
|
||||
// keys; what a config evaluates to is
|
||||
// tests/unit/playwright-flaky-judgement.test.ts's to judge.
|
||||
if (/\b(?:retries|failOnFlakyTests)\b/u.test(source)) {
|
||||
try {
|
||||
if (await setsRetryOption(config, source)) {
|
||||
failures.push(
|
||||
`${config}: retries come only from ...flakyJudgement(), so a test that passes on its retry still fails the gate`,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
failures.push(
|
||||
`${config}: cannot parse to look for retries: ${error instanceof Error ? error.message : String(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return failures;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { stripVTControlCharacters } from "node:util";
|
||||
|
||||
import type { FullConfig, FullResult, Reporter, TestCase, TestError, TestResult } from "@playwright/test/reporter";
|
||||
|
||||
/**
|
||||
* FLAKY-3 (docs/work/reference/decisions.md "CI 계획 D-3"). In CI a failed
|
||||
* Playwright test runs once more only to tell a flaky test from a broken one:
|
||||
* a test that passes on its retry is reported flaky and the run still fails.
|
||||
* Outside CI nothing retries. Configs spread this and name the reporter below;
|
||||
* they set neither option themselves (scripts/check-test-evidence.ts).
|
||||
*/
|
||||
export function flakyJudgement(environment: NodeJS.ProcessEnv = process.env) {
|
||||
const ci = environment["CI"] === "true";
|
||||
return Object.freeze({ retries: ci ? 1 : 0, failOnFlakyTests: ci });
|
||||
}
|
||||
|
||||
/** This module as an entry of a config's `reporter` list. */
|
||||
export const flakyJudgementReporter = [fileURLToPath(import.meta.url)] as const;
|
||||
|
||||
type FailedAttempt = Readonly<{ test: TestCase; result: TestResult }>;
|
||||
|
||||
/**
|
||||
* Whether the list reporter leaves out why this attempt failed. It prints the
|
||||
* errors of a test that ends flaky or failed, and "Expected to fail, but
|
||||
* passed." only while the last attempt still expects a failure.
|
||||
*/
|
||||
function leftOutOfTheReport({ test, result }: FailedAttempt): boolean {
|
||||
return test.outcome() === "expected" || (result.status === "passed" && test.expectedStatus !== "failed");
|
||||
}
|
||||
|
||||
function errorText({ message, value, stack, cause }: TestError): string {
|
||||
const text = [stack ?? message ?? value, cause && `[cause]: ${errorText(cause)}`].filter(Boolean).join("\n");
|
||||
return stripVTControlCharacters(text);
|
||||
}
|
||||
|
||||
/** One attempt, headed like the list reporter's failures so ci:gate quotes it (ci-gate-failure.ts). */
|
||||
function failureBlock({ test, result }: FailedAttempt, index: number): string {
|
||||
const [, project, , ...titles] = test.titlePath();
|
||||
const { file, line, column } = test.location;
|
||||
const causes = result.status === "passed" ? ["Expected to fail, but passed."] : result.errors.map(errorText);
|
||||
return [
|
||||
` ${index + 1}) ${project ? `[${project}] › ` : ""}${file}:${line}:${column} › ${titles.join(" › ")}`,
|
||||
" failed an attempt before the retry changed what it expects; the run fails",
|
||||
...causes,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* What failOnFlakyTests misses. Playwright 1.62 judges every attempt of a test
|
||||
* by the expected status of the last one, so when only the retry reaches
|
||||
* test.fail() (a fixture failed before the body called it), the first failure
|
||||
* becomes an expected one and the run passes. This judges each attempt when it
|
||||
* ends: a failed attempt fails the run, as it does without a retry, and its
|
||||
* error is printed here when no other report has it.
|
||||
*/
|
||||
export default class FlakyJudgementReporter implements Reporter {
|
||||
#judging = false;
|
||||
readonly #failed: FailedAttempt[] = [];
|
||||
|
||||
onBegin(config: FullConfig): void {
|
||||
this.#judging = config.failOnFlakyTests;
|
||||
}
|
||||
|
||||
onTestEnd(test: TestCase, result: TestResult): void {
|
||||
if (result.status !== "skipped" && result.status !== test.expectedStatus) this.#failed.push({ test, result });
|
||||
}
|
||||
|
||||
async onEnd(result: FullResult): Promise<{ status: "failed" } | undefined> {
|
||||
if (!this.#judging || this.#failed.length === 0) return undefined;
|
||||
for (const [index, attempt] of this.#failed.filter(leftOutOfTheReport).entries()) {
|
||||
process.stderr.write(failureBlock(attempt, index));
|
||||
}
|
||||
return result.status === "passed" ? { status: "failed" } : undefined;
|
||||
}
|
||||
|
||||
// The report stays the list reporter's.
|
||||
printsToStdio(): boolean {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,8 @@ import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promise
|
||||
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.
|
||||
*
|
||||
@@ -15,6 +17,10 @@ import path from "node:path";
|
||||
* 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.
|
||||
*/
|
||||
@@ -55,16 +61,23 @@ async function readFailure(file: string): Promise<string | undefined> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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];
|
||||
@@ -78,47 +91,51 @@ export async function sharedFixtureBuild<Value>(
|
||||
}
|
||||
}
|
||||
|
||||
const root = path.join(sharedRoot, key);
|
||||
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;
|
||||
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 {
|
||||
value = await create(root);
|
||||
await mkdir(root);
|
||||
} catch (error) {
|
||||
await writeFile(failureFile, String(error instanceof Error ? error.stack : error));
|
||||
throw error;
|
||||
if (!hasCode(error, "EEXIST")) throw error;
|
||||
owner = false;
|
||||
}
|
||||
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.`,
|
||||
);
|
||||
if (owner) {
|
||||
let value: Value;
|
||||
try {
|
||||
value = await create(root);
|
||||
} catch (error) {
|
||||
await writeFile(failureFile, String(error instanceof Error ? error.stack : error));
|
||||
throw error;
|
||||
}
|
||||
return { root, value: record.value as Value, shared: true };
|
||||
const temporary = `${recordFile}.${process.pid}.tmp`;
|
||||
await writeFile(temporary, JSON.stringify({ fingerprint, value }));
|
||||
await rename(temporary, recordFile);
|
||||
return { root, value, shared: true };
|
||||
}
|
||||
const failure = await readFailure(failureFile);
|
||||
if (failure !== undefined) {
|
||||
throw new Error(`Fixture build ${key} failed in another worker:\n${failure}`);
|
||||
|
||||
// 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));
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, POLL_MS));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
// A Playwright config that retries on its own under a computed key:
|
||||
// check-test-evidence.ts --playwright-config must reject it (FLAKY-3).
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "tests/e2e",
|
||||
forbidOnly: true,
|
||||
["retries"]: 1,
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
// A Playwright config that takes the CI retry from the helper:
|
||||
// check-test-evidence.ts --playwright-config must accept it (FLAKY-3).
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
import { flakyJudgement, flakyJudgementReporter } from "../../../../scripts/lib/playwright-flaky-judgement.ts";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "tests/e2e",
|
||||
...flakyJudgement(),
|
||||
forbidOnly: true,
|
||||
reporter: [flakyJudgementReporter, ["junit", { outputFile: "artifacts/tests/e2e/results.xml", includeRetries: true }]],
|
||||
});
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
// A Playwright config that lets a flaky test pass after the helper said it
|
||||
// fails: check-test-evidence.ts --playwright-config must reject it (FLAKY-3).
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
import { flakyJudgement } from "../../../../scripts/lib/playwright-flaky-judgement.ts";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "tests/e2e",
|
||||
...flakyJudgement(),
|
||||
failOnFlakyTests: false,
|
||||
forbidOnly: true,
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
// A Playwright config that retries on its own, so a test that passes on its
|
||||
// retry passes the gate: check-test-evidence.ts --playwright-config must
|
||||
// reject it (FLAKY-3).
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "tests/e2e",
|
||||
forbidOnly: true,
|
||||
projects: [{ name: "chromium", retries: 1 }],
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
// A Playwright config that retries on its own under a quoted key:
|
||||
// check-test-evidence.ts --playwright-config must reject it (FLAKY-3).
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "tests/e2e",
|
||||
forbidOnly: true,
|
||||
"retries": 1,
|
||||
});
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
// A Playwright config that only names the two options, in comments, in longer
|
||||
// keys and in a string: check-test-evidence.ts --playwright-config must accept
|
||||
// it (FLAKY-3).
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
import { flakyJudgement } from "../../../../scripts/lib/playwright-flaky-judgement.ts";
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "tests/e2e",
|
||||
// retries: see flakyJudgement()
|
||||
/* failOnFlakyTests: the helper sets it */
|
||||
...flakyJudgement(),
|
||||
forbidOnly: true,
|
||||
metadata: { "http-retries": 2, note: "retries: one in CI" },
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
// A Playwright config that retries on its own through a shorthand property:
|
||||
// check-test-evidence.ts --playwright-config must reject it (FLAKY-3).
|
||||
import { defineConfig } from "@playwright/test";
|
||||
|
||||
const retries = 1;
|
||||
|
||||
export default defineConfig({
|
||||
testDir: "tests/e2e",
|
||||
forbidOnly: true,
|
||||
retries,
|
||||
});
|
||||
@@ -0,0 +1,409 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readdirSync } from "node:fs";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { formatGateFailure } from "../../scripts/lib/ci-gate-failure.ts";
|
||||
import { flakyJudgementReporter } from "../../scripts/lib/playwright-flaky-judgement.ts";
|
||||
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
|
||||
import { loadConfigFile, releaseRuns } from "../helpers/playwright-run-isolation.ts";
|
||||
|
||||
/**
|
||||
* FLAKY-3. In CI a failed Playwright test runs once more to tell a flaky test
|
||||
* from a broken one, and the run fails either way. The first block runs the
|
||||
* real Playwright on a config with no browser and no server. The second reads
|
||||
* what each config of this repository evaluates to.
|
||||
*
|
||||
* The probe specs are written at run time, so no runner, lint or typecheck
|
||||
* picks them up. They are below .tmp/ so `@playwright/test` resolves.
|
||||
*/
|
||||
const HELPER = pathToFileURL(path.resolve("scripts/lib/playwright-flaky-judgement.ts")).href;
|
||||
const PLAYWRIGHT_CLI = createRequire(import.meta.url).resolve("@playwright/test/cli");
|
||||
/**
|
||||
* Longest desktop run of a test in the first block and in the last one, over
|
||||
* four runs of this file, two of them with coverage (2026-11-22).
|
||||
*/
|
||||
const RUN_MS = 3_584;
|
||||
const CHECK_MS = 694;
|
||||
|
||||
const folders: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await releaseRuns();
|
||||
await Promise.all(folders.splice(0).map((folder) => rm(folder, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
function count(text: string, pattern: RegExp): number {
|
||||
return [...text.matchAll(pattern)].length;
|
||||
}
|
||||
|
||||
/** Runs `body` as a spec, in each of `projects`, that records the retry number of each attempt. */
|
||||
async function runProbe(body: string, ci: string | undefined, projects: readonly string[] = []) {
|
||||
await mkdir(".tmp", { recursive: true });
|
||||
const root = await mkdtemp(path.resolve(".tmp/flaky-judgement-"));
|
||||
folders.push(root);
|
||||
const attempts = path.join(root, "attempts");
|
||||
const junit = path.join(root, "results.xml");
|
||||
await writeFile(
|
||||
path.join(root, "probe.config.ts"),
|
||||
`import { defineConfig } from "@playwright/test";
|
||||
import { flakyJudgement, flakyJudgementReporter } from ${JSON.stringify(HELPER)};
|
||||
|
||||
export default defineConfig({
|
||||
testDir: ".",
|
||||
testMatch: "probe.spec.ts",
|
||||
...flakyJudgement(),
|
||||
${projects.length === 0 ? "" : `projects: ${JSON.stringify(projects.map((name) => ({ name })))},`}
|
||||
workers: 1,
|
||||
outputDir: "results",
|
||||
reporter: [["list"], flakyJudgementReporter, ["junit", { outputFile: ${JSON.stringify(junit)}, includeRetries: true }]],
|
||||
});
|
||||
`,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(root, "probe.spec.ts"),
|
||||
`import { appendFileSync } from "node:fs";
|
||||
import { expect, test as base } from "@playwright/test";
|
||||
|
||||
const test = base.extend({
|
||||
attempt: async ({}, use, testInfo) => {
|
||||
appendFileSync(${JSON.stringify(attempts)}, String(testInfo.retry));
|
||||
await use(testInfo.retry);
|
||||
},
|
||||
failsOnFirstSetup: async ({ attempt }, use) => {
|
||||
if (attempt === 0) throw new Error("setup failed", { cause: new Error("port taken") });
|
||||
await use(attempt);
|
||||
},
|
||||
});
|
||||
|
||||
${body}
|
||||
`,
|
||||
);
|
||||
// The child's environment is this test's: not the CI, reporter or color
|
||||
// variables of whoever runs Vitest.
|
||||
const environment = {
|
||||
PATH: process.env["PATH"],
|
||||
HOME: process.env["HOME"],
|
||||
TMPDIR: process.env["TMPDIR"],
|
||||
FORCE_COLOR: "0",
|
||||
...(ci === undefined ? {} : { CI: ci }),
|
||||
};
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[PLAYWRIGHT_CLI, "test", "--config", path.join(root, "probe.config.ts")],
|
||||
{ cwd: root, env: environment as unknown as NodeJS.ProcessEnv, encoding: "utf8" },
|
||||
);
|
||||
const xml = await readFile(junit, "utf8").catch(() => "");
|
||||
return {
|
||||
status: result.status,
|
||||
output: `${result.stdout}${result.stderr}`,
|
||||
attempts: await readFile(attempts, "utf8").catch(() => ""),
|
||||
xml,
|
||||
};
|
||||
}
|
||||
|
||||
const FLAKY = `test("probe", async ({ attempt }) => {
|
||||
expect(attempt).toBe(1);
|
||||
});`;
|
||||
|
||||
describe("Playwright flaky judgement", { timeout: childProcessTimeout(RUN_MS) }, () => {
|
||||
it("reports a test that passes on its retry as flaky and fails the run in CI", async () => {
|
||||
const run = await runProbe(FLAKY, "true");
|
||||
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.attempts).toBe("01");
|
||||
expect(run.output).toMatch(/^\s*1 flaky$/mu);
|
||||
expect(run.output).toContain("(retry #1)");
|
||||
// The list reporter prints why this one failed. The judgement does not again.
|
||||
expect(run.output).not.toContain("failed an attempt");
|
||||
expect(count(run.xml, /<testcase\b/gu)).toBe(1);
|
||||
expect(count(run.xml, /<flakyFailure\b/gu)).toBe(1);
|
||||
expect(run.xml).not.toMatch(/<failure\b/u);
|
||||
});
|
||||
|
||||
// What JUnit leaves of a flaky test. Counting <flakyFailure> alone misses most.
|
||||
it.each([
|
||||
["a failed expect", FLAKY, ["flakyFailure"]],
|
||||
[
|
||||
"a timeout",
|
||||
`test("probe", async ({ attempt }) => {\n if (attempt === 1) return;\n test.setTimeout(200);\n await new Promise(() => {});\n});`,
|
||||
["flakyError"],
|
||||
],
|
||||
["a throw", `test("probe", async ({ attempt }) => {\n if (attempt === 0) throw new Error("boom");\n});`, ["flakyError"]],
|
||||
["a crash", `test("probe", async ({ attempt }) => {\n if (attempt === 0) process.exit(3);\n});`, ["flakyError"]],
|
||||
[
|
||||
"an expected failure that passed",
|
||||
`test("probe", async ({ attempt }) => {\n test.fail();\n expect(attempt).toBe(0);\n});`,
|
||||
[],
|
||||
],
|
||||
])("records in JUnit a flaky test that began with %s", async (_, body, children) => {
|
||||
const run = await runProbe(body, "true");
|
||||
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.output).toMatch(/^\s*1 flaky$/mu);
|
||||
expect([...run.xml.matchAll(/<(flaky\w+)\b/gu)].map((match) => match[1])).toEqual(children);
|
||||
expect(run.xml).not.toMatch(/<(?:failure|error)\b/u);
|
||||
});
|
||||
|
||||
it("runs a test that always fails twice in CI and reports it failed", async () => {
|
||||
const run = await runProbe(`test("probe", async ({ attempt }) => {\n expect(attempt).toBe(-1);\n});`, "true");
|
||||
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.attempts).toBe("01");
|
||||
expect(run.output).toMatch(/^\s*1 failed$/mu);
|
||||
expect(run.output).toContain("Retry #1");
|
||||
expect(count(run.xml, /<testcase\b/gu)).toBe(1);
|
||||
expect(count(run.xml, /<failure\b/gu)).toBe(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["no CI", undefined],
|
||||
["an empty CI", ""],
|
||||
["CI=false", "false"],
|
||||
])("does not retry with %s", async (_, ci) => {
|
||||
const run = await runProbe(FLAKY, ci);
|
||||
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.attempts).toBe("0");
|
||||
expect(run.output).toMatch(/^\s*1 failed$/mu);
|
||||
expect(run.output).not.toMatch(/retry #1/iu);
|
||||
});
|
||||
|
||||
// Playwright judges every attempt by the expected status of the last one.
|
||||
// A test.fail() only the retry reaches turns the first failure into an
|
||||
// expected one: the test ends "expected", not flaky, so failOnFlakyTests
|
||||
// alone passes a run that fails without a retry. preload-use.spec.ts calls
|
||||
// test.fail() in the body, after its fixtures.
|
||||
it.each([
|
||||
[
|
||||
"a fixture fails before the test.fail() its body calls",
|
||||
`test("probe", async ({ failsOnFirstSetup }) => {\n test.fail();\n expect(failsOnFirstSetup).toBe(-1);\n});`,
|
||||
],
|
||||
[
|
||||
"the expected failure passes and only that attempt expects one",
|
||||
`test("probe", async ({ attempt }) => {\n test.fail(attempt === 0);\n});`,
|
||||
],
|
||||
])("fails the run in CI, as without a retry, when %s", async (_, body) => {
|
||||
expect((await runProbe(body, undefined)).status).not.toBe(0);
|
||||
const run = await runProbe(body, "true");
|
||||
|
||||
expect(run.attempts).toBe("01");
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.output).toContain("failed an attempt before the retry changed what it expects");
|
||||
});
|
||||
|
||||
// For these the list reporter prints "3 passed" and no error, and the JUnit
|
||||
// file has no failure: what the judgement prints is all the gate log has.
|
||||
it.each([
|
||||
[
|
||||
"a fixture failed",
|
||||
`test("probe", async ({ failsOnFirstSetup }) => {\n test.fail();\n expect(failsOnFirstSetup).toBe(-1);\n});`,
|
||||
[/Error: setup failed/u, /^\s+at .*probe\.spec\.ts:\d+:\d+/mu, /port taken/u],
|
||||
],
|
||||
[
|
||||
"an expect failed",
|
||||
`test("probe", async ({ attempt }) => {\n if (attempt === 0) expect(attempt).toBe(2);\n test.fail();\n expect(attempt).toBe(-1);\n});`,
|
||||
[/expect\(received\)\.toBe\(expected\)/u, /^\s*Expected: 2$/mu],
|
||||
],
|
||||
[
|
||||
"the expected failure passed",
|
||||
`test("probe", async ({ attempt }) => {\n test.fail(attempt === 0);\n});`,
|
||||
[/Expected to fail, but passed\./u],
|
||||
],
|
||||
[
|
||||
"what was thrown is not an Error",
|
||||
`test("probe", async ({ attempt }) => {\n if (attempt === 0) throw "the port was taken";\n test.fail();\n expect(attempt).toBe(-1);\n});`,
|
||||
[/the port was taken/u],
|
||||
],
|
||||
])("names the project and why the hidden attempt failed when %s", async (_, body, causes) => {
|
||||
const projects = ["first", "second", "third"];
|
||||
const run = await runProbe(body, "true", projects);
|
||||
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.output).toMatch(/^\s*3 passed\b/mu);
|
||||
// Playwright records errors with color codes; the list reporter strips them.
|
||||
expect(run.output).not.toContain("\u001b");
|
||||
const header = /^ *\d+\) \[(\w+)\] › .*probe\.spec\.ts:\d+:\d+ › probe/gmu;
|
||||
const blocks = [...run.output.matchAll(header)].map((match, index, all) => ({
|
||||
project: match[1]!,
|
||||
text: run.output.slice(match.index, all[index + 1]?.index),
|
||||
}));
|
||||
expect(blocks.map((block) => block.project).sort(), run.output).toEqual(projects);
|
||||
for (const block of blocks) {
|
||||
for (const cause of causes) expect(block.text, block.project).toMatch(cause);
|
||||
}
|
||||
// ci:gate quotes the first failure block, not only the last lines of the log.
|
||||
const command = "$ corepack pnpm test:e2e";
|
||||
const summary = formatGateFailure({
|
||||
gateId: "FE-GATE-008",
|
||||
gateName: "e2e",
|
||||
logPath: "gate.txt",
|
||||
failedCommand: command,
|
||||
output: [command, run.output],
|
||||
tailLines: 1,
|
||||
});
|
||||
expect(summary).toContain("first failure in the log:");
|
||||
expect(summary).toContain(`[${blocks[0]!.project}]`);
|
||||
for (const cause of causes) expect(summary).toMatch(cause);
|
||||
});
|
||||
|
||||
it("says why the hidden attempt failed when another test fails the run", async () => {
|
||||
const run = await runProbe(
|
||||
`test("hidden", async ({ failsOnFirstSetup }) => {
|
||||
test.fail();
|
||||
expect(failsOnFirstSetup).toBe(-1);
|
||||
});
|
||||
test("broken", async ({ attempt }) => {
|
||||
expect(attempt).toBe(-1);
|
||||
});`,
|
||||
"true",
|
||||
);
|
||||
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.output).toMatch(/^\s*1 failed$/mu);
|
||||
expect(run.output).toContain("Error: setup failed");
|
||||
expect(count(run.output, /failed an attempt/gu)).toBe(1);
|
||||
});
|
||||
|
||||
// This one is flaky, but the list reporter has no line for it: the last
|
||||
// attempt expects a skip and the first one left no error.
|
||||
it("says why when the retry skips a test whose expected failure passed", async () => {
|
||||
const run = await runProbe(
|
||||
`test("probe", async ({ attempt }) => {\n test.fail(attempt === 0);\n test.skip(attempt === 1);\n});`,
|
||||
"true",
|
||||
);
|
||||
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.output).toMatch(/^\s*1 flaky$/mu);
|
||||
expect(run.output).toContain("Expected to fail, but passed.");
|
||||
});
|
||||
|
||||
it("fails the run in CI when the retry skips the test that failed", async () => {
|
||||
const run = await runProbe(
|
||||
`test("probe", async ({ attempt }) => {\n test.skip(attempt === 1);\n expect(attempt).toBe(1);\n});`,
|
||||
"true",
|
||||
);
|
||||
|
||||
expect(run.status, run.output).not.toBe(0);
|
||||
expect(run.attempts).toBe("01");
|
||||
expect(run.output).toMatch(/^\s*1 flaky$/mu);
|
||||
});
|
||||
|
||||
it("passes a run whose tests all end as expected on the first attempt", async () => {
|
||||
const run = await runProbe(
|
||||
`test("passes", async ({ attempt }) => {
|
||||
expect(attempt).toBe(0);
|
||||
});
|
||||
test("fails on purpose", async ({ attempt }) => {
|
||||
test.fail();
|
||||
expect(attempt).toBe(1);
|
||||
});
|
||||
test("is left out", async ({ attempt }) => {
|
||||
test.skip(attempt === 0);
|
||||
});`,
|
||||
"true",
|
||||
);
|
||||
|
||||
expect(run.status, run.output).toBe(0);
|
||||
expect(run.attempts).toBe("000");
|
||||
expect(run.output).not.toContain("failed an attempt");
|
||||
});
|
||||
});
|
||||
|
||||
// Every config at the root, read from disk: a config added later is held to
|
||||
// the same judgement, and a checkout without the capabilities config is not
|
||||
// asked for it.
|
||||
describe("Playwright configs", () => {
|
||||
const configs = readdirSync(".").filter((file) => /^playwright.*\.config\.ts$/u.test(file));
|
||||
|
||||
it("are found", () => {
|
||||
expect(configs).toContain("playwright.config.ts");
|
||||
expect(configs.length).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it.each(configs)("%s retries once in CI only, fails on a flaky test and records the retry", async (file) => {
|
||||
vi.stubEnv("CI", "true");
|
||||
const inCi = await loadConfigFile(file);
|
||||
vi.stubEnv("CI", "");
|
||||
const outsideCi = await loadConfigFile(file);
|
||||
|
||||
for (const [config, retries] of [
|
||||
[inCi, 1],
|
||||
[outsideCi, 0],
|
||||
] as const) {
|
||||
expect(config.retries).toBe(retries);
|
||||
expect(config.failOnFlakyTests).toBe(retries === 1);
|
||||
// A project's own value wins over the config's.
|
||||
for (const project of config.projects ?? []) expect(project.retries ?? config.retries).toBe(retries);
|
||||
expect(config.reporter).toContainEqual(flakyJudgementReporter);
|
||||
expect(config.reporter).toContainEqual([
|
||||
"junit",
|
||||
expect.objectContaining({ includeRetries: true }) as unknown,
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("check-test-evidence on retries", { timeout: childProcessTimeout(CHECK_MS) }, () => {
|
||||
const FIXTURES = "tests/fixtures/test-evidence/playwright-config";
|
||||
// The fixture is also the source root, so the run reads no other file.
|
||||
const check = async (config: string) => {
|
||||
await mkdir(".tmp", { recursive: true });
|
||||
const root = await mkdtemp(path.resolve(".tmp/flaky-judgement-check-"));
|
||||
folders.push(root);
|
||||
return spawnSync(
|
||||
process.execPath,
|
||||
[
|
||||
"scripts/check-test-evidence.ts",
|
||||
"--source-only",
|
||||
"--source-root",
|
||||
config,
|
||||
"--playwright-config",
|
||||
config,
|
||||
"--artifact",
|
||||
path.join(root, "report.json"),
|
||||
],
|
||||
{ encoding: "utf8" },
|
||||
);
|
||||
};
|
||||
|
||||
it.each([
|
||||
"literal-retries.fixture",
|
||||
"literal-fail-on-flaky-tests.fixture",
|
||||
"quoted-retries.fixture",
|
||||
"computed-retries.fixture",
|
||||
"shorthand-retries.fixture",
|
||||
])("rejects %s", async (fixture) => {
|
||||
const result = await check(`${FIXTURES}/${fixture}`);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain(
|
||||
`${FIXTURES}/${fixture}: retries come only from ...flakyJudgement(), so a test that passes on its retry still fails the gate`,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a config it cannot read", async () => {
|
||||
await mkdir(".tmp", { recursive: true });
|
||||
const root = await mkdtemp(path.resolve(".tmp/flaky-judgement-unreadable-"));
|
||||
folders.push(root);
|
||||
const config = path.join(root, "unreadable.fixture");
|
||||
await writeFile(config, "export default { forbidOnly: true, retries: 1\n");
|
||||
|
||||
const result = await check(config);
|
||||
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain(`${config}: cannot parse to look for retries`);
|
||||
});
|
||||
|
||||
it.each(["flaky-judgement.fixture", "retries-named-elsewhere.fixture"])("accepts %s", async (fixture) => {
|
||||
const result = await check(`${FIXTURES}/${fixture}`);
|
||||
|
||||
expect(result.stderr).toBe("");
|
||||
expect(result.status).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,9 @@
|
||||
import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { access, mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
@@ -9,6 +12,7 @@ import {
|
||||
sharedFixtureBuild,
|
||||
startSharedFixtureBuilds,
|
||||
} from "../e2e/support/shared-fixture-builds.ts";
|
||||
import { childProcessTimeout } from "../helpers/child-process-timeout.ts";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
@@ -123,3 +127,257 @@ describe("one fixture build per e2e run", () => {
|
||||
await expect(access(root!)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
});
|
||||
|
||||
// FLAKY-3 (CI-FE-0001 C9). A retry that read the first attempt's failure
|
||||
// failed without building, so a build that failed once was reported as a
|
||||
// broken test instead of a flaky one.
|
||||
describe("a fixture build and the CI retry", () => {
|
||||
const FIRST = 0;
|
||||
const RETRY = 1;
|
||||
const pause = () => new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
/** A run in which the first attempt's build of `key` failed half way. */
|
||||
async function failedFirstBuild(key: string) {
|
||||
const environment = await sharedEnvironment();
|
||||
let root = "";
|
||||
await expect(
|
||||
sharedFixtureBuild(
|
||||
key,
|
||||
"same",
|
||||
async (folder) => {
|
||||
root = folder;
|
||||
await writeFile(path.join(folder, "half-built"), "");
|
||||
throw new Error("first build failed");
|
||||
},
|
||||
environment,
|
||||
FIRST,
|
||||
),
|
||||
).rejects.toThrow(/first build failed/u);
|
||||
return { environment, failedRoot: root };
|
||||
}
|
||||
|
||||
it("C9 (가) builds again on a retry, in an empty folder, and returns that build", async () => {
|
||||
const { environment, failedRoot } = await failedFirstBuild("retry-a");
|
||||
let found: string[] | undefined;
|
||||
|
||||
const result = await sharedFixtureBuild(
|
||||
"retry-a",
|
||||
"same",
|
||||
async (root) => {
|
||||
found = await readdir(root);
|
||||
return "built again";
|
||||
},
|
||||
environment,
|
||||
RETRY,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({ value: "built again", shared: true });
|
||||
expect(found).toEqual([]);
|
||||
expect(result.root).not.toBe(failedRoot);
|
||||
expect(path.dirname(result.root)).toBe(environment[SHARED_FIXTURE_BUILD_ROOT_VARIABLE]);
|
||||
});
|
||||
|
||||
it("C9 (가) builds again when the first attempt's build fails while the retry waits for it", async () => {
|
||||
const environment = await sharedEnvironment();
|
||||
let building!: () => void;
|
||||
const started = new Promise<void>((resolve) => {
|
||||
building = resolve;
|
||||
});
|
||||
const first = sharedFixtureBuild(
|
||||
"retry-wait",
|
||||
"same",
|
||||
async () => {
|
||||
building();
|
||||
await pause();
|
||||
throw new Error("first build failed");
|
||||
},
|
||||
environment,
|
||||
FIRST,
|
||||
);
|
||||
await started;
|
||||
const retry = sharedFixtureBuild("retry-wait", "same", async () => "built again", environment, RETRY);
|
||||
|
||||
await expect(first).rejects.toThrow(/first build failed/u);
|
||||
await expect(retry).resolves.toMatchObject({ value: "built again" });
|
||||
});
|
||||
|
||||
it("C9 (나) fails a retry whose build fails too, and the retries after it", async () => {
|
||||
const { environment } = await failedFirstBuild("retry-b");
|
||||
let builds = 0;
|
||||
const retry = () =>
|
||||
sharedFixtureBuild(
|
||||
"retry-b",
|
||||
"same",
|
||||
async () => {
|
||||
builds += 1;
|
||||
throw new Error("second build failed");
|
||||
},
|
||||
environment,
|
||||
RETRY,
|
||||
);
|
||||
|
||||
await expect(retry()).rejects.toThrow(/^second build failed$/u);
|
||||
await expect(retry()).rejects.toThrow(/retry-b failed in another worker:[\s\S]*second build failed/u);
|
||||
expect(builds).toBe(1);
|
||||
});
|
||||
|
||||
it("C9 (다) gives the first attempts one build and its failure", async () => {
|
||||
const environment = await sharedEnvironment();
|
||||
let builds = 0;
|
||||
const first = () =>
|
||||
sharedFixtureBuild(
|
||||
"retry-c",
|
||||
"same",
|
||||
async () => {
|
||||
builds += 1;
|
||||
await pause();
|
||||
throw new Error("first build failed");
|
||||
},
|
||||
environment,
|
||||
FIRST,
|
||||
);
|
||||
|
||||
const together = await Promise.allSettled([first(), first(), first()]);
|
||||
const late = await Promise.allSettled([first()]);
|
||||
|
||||
expect(builds).toBe(1);
|
||||
for (const attempt of [...together, ...late]) {
|
||||
expect(attempt).toMatchObject({
|
||||
status: "rejected",
|
||||
reason: { message: expect.stringContaining("first build failed") as unknown },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["succeeds", "fails"])(
|
||||
"C9 (라) never builds twice at once in one folder for two retries, when the build %s",
|
||||
async (outcome) => {
|
||||
const { environment } = await failedFirstBuild("retry-d");
|
||||
const building = new Map<string, number>();
|
||||
let mostAtOnce = 0;
|
||||
let builds = 0;
|
||||
const retry = () =>
|
||||
sharedFixtureBuild(
|
||||
"retry-d",
|
||||
"same",
|
||||
async (root) => {
|
||||
builds += 1;
|
||||
building.set(root, (building.get(root) ?? 0) + 1);
|
||||
mostAtOnce = Math.max(mostAtOnce, building.get(root)!);
|
||||
await pause();
|
||||
building.set(root, building.get(root)! - 1);
|
||||
if (outcome === "fails") throw new Error("second build failed");
|
||||
return root;
|
||||
},
|
||||
environment,
|
||||
RETRY,
|
||||
);
|
||||
|
||||
const both = await Promise.allSettled([retry(), retry()]);
|
||||
|
||||
expect(mostAtOnce).toBe(1);
|
||||
expect(builds).toBe(1);
|
||||
expect(both.map((attempt) => attempt.status)).toEqual(
|
||||
outcome === "fails" ? ["rejected", "rejected"] : ["fulfilled", "fulfilled"],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("C9 (마) does not build again on a retry when the first attempt's build succeeded", async () => {
|
||||
const environment = await sharedEnvironment();
|
||||
const first = await sharedFixtureBuild("retry-e", "same", async () => "built once", environment, FIRST);
|
||||
let builds = 0;
|
||||
|
||||
const retry = await sharedFixtureBuild(
|
||||
"retry-e",
|
||||
"same",
|
||||
async () => {
|
||||
builds += 1;
|
||||
return "built twice";
|
||||
},
|
||||
environment,
|
||||
RETRY,
|
||||
);
|
||||
|
||||
expect(builds).toBe(0);
|
||||
expect(retry).toEqual(first);
|
||||
});
|
||||
});
|
||||
|
||||
/** Longest desktop run of a test below, over four runs, two of them with coverage (2026-11-22). */
|
||||
const RUN_MS = 2_264;
|
||||
|
||||
// Only Playwright knows which attempt asks: the retry number reaches the
|
||||
// helper through a describe's beforeAll, as in preload-use.spec.ts.
|
||||
describe("a fixture build in a Playwright run", { timeout: childProcessTimeout(RUN_MS) }, () => {
|
||||
it.each([
|
||||
["once", 1, /^\s*3 flaky$/mu],
|
||||
["twice", 2, /^\s*3 failed$/mu],
|
||||
] as const)("C9 judges a build that fails %s by the retry's own build", async (_, failingBuilds, summary) => {
|
||||
await mkdir(".tmp", { recursive: true });
|
||||
const root = await mkdtemp(path.resolve(".tmp/shared-builds-run-"));
|
||||
roots.push(root);
|
||||
const log = path.join(root, "builds");
|
||||
const source = (file: string) => JSON.stringify(pathToFileURL(path.resolve(file)).href);
|
||||
await writeFile(
|
||||
path.join(root, "probe.config.ts"),
|
||||
`import { defineConfig } from "@playwright/test";
|
||||
import { flakyJudgement, flakyJudgementReporter } from ${source("scripts/lib/playwright-flaky-judgement.ts")};
|
||||
|
||||
export default defineConfig({
|
||||
testDir: ".",
|
||||
testMatch: "probe.spec.ts",
|
||||
globalSetup: ${JSON.stringify(path.resolve("tests/e2e/support/e2e-global-setup.ts"))},
|
||||
...flakyJudgement(),
|
||||
workers: 3,
|
||||
projects: [{ name: "first" }, { name: "second" }, { name: "third" }],
|
||||
outputDir: "results",
|
||||
reporter: [["list"], flakyJudgementReporter],
|
||||
});
|
||||
`,
|
||||
);
|
||||
await writeFile(
|
||||
path.join(root, "probe.spec.ts"),
|
||||
`import { appendFileSync, readFileSync } from "node:fs";
|
||||
import { test } from "@playwright/test";
|
||||
import { sharedFixtureBuild } from ${source("tests/e2e/support/shared-fixture-builds.ts")};
|
||||
|
||||
test.describe("with a build", () => {
|
||||
test.beforeAll(async () => {
|
||||
await sharedFixtureBuild("probe", "same", async () => {
|
||||
appendFileSync(${JSON.stringify(log)}, "b");
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
if (readFileSync(${JSON.stringify(log)}, "utf8").length <= ${failingBuilds}) throw new Error("build failed");
|
||||
return "built";
|
||||
});
|
||||
});
|
||||
test("uses the build", () => {});
|
||||
test("uses it again", () => {});
|
||||
});
|
||||
test("needs no build", () => {});
|
||||
`,
|
||||
);
|
||||
const result = spawnSync(
|
||||
process.execPath,
|
||||
[createRequire(import.meta.url).resolve("@playwright/test/cli"), "test", "--config", path.join(root, "probe.config.ts")],
|
||||
{
|
||||
cwd: root,
|
||||
// The child's environment is this test's, not the runner's.
|
||||
env: {
|
||||
PATH: process.env["PATH"],
|
||||
HOME: process.env["HOME"],
|
||||
TMPDIR: process.env["TMPDIR"],
|
||||
FORCE_COLOR: "0",
|
||||
CI: "true",
|
||||
} as unknown as NodeJS.ProcessEnv,
|
||||
encoding: "utf8",
|
||||
},
|
||||
);
|
||||
const output = `${result.stdout}${result.stderr}`;
|
||||
|
||||
expect(result.status, output).not.toBe(0);
|
||||
expect(output).toMatch(summary);
|
||||
// One build for the first attempts and one for the retries, whatever the projects.
|
||||
expect(await readFile(log, "utf8"), output).toBe("bb");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user