From 30e50ab9b347e4e9c067989a7fa543727c69c72a Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 20:23:15 -0800 Subject: [PATCH] Revert "Set flaky tests aside automatically" (#2987): it broke main's tests Main's CI has failed since #2987 merged (push run 47477429817; merge groups 47477444820 and 47477446193): tests/upstream-upgrade-checks.test.ts rejects the non-literal GH_TOKEN it added to CI's test step, and shards 1 and 5 fail. It returns fixed in a new PR. --- .github/workflows/ci.yml | 50 +- .github/workflows/flaky-tests.yml | 60 -- .github/workflows/publish-release.yml | 3 - .github/zizmor.yml | 6 +- scripts/ci-changes.ts | 2 - scripts/ci-run-tests.test.ts | 3 - scripts/ci-run-tests.ts | 28 +- scripts/ci-watch.test.ts | 8 - scripts/ci-watch.ts | 9 +- scripts/flaky-tests-watch.ts | 588 ------------------ .../flaky-tests.fixtures/broken.fixture.ts | 6 - scripts/flaky-tests.fixtures/flaky.fixture.ts | 19 - .../load-error.fixture.ts | 7 - scripts/flaky-tests.test.ts | 481 -------------- scripts/flaky-tests.ts | 482 -------------- scripts/test-ci.ts | 22 +- 16 files changed, 16 insertions(+), 1758 deletions(-) delete mode 100644 .github/workflows/flaky-tests.yml delete mode 100644 scripts/flaky-tests-watch.ts delete mode 100644 scripts/flaky-tests.fixtures/broken.fixture.ts delete mode 100644 scripts/flaky-tests.fixtures/flaky.fixture.ts delete mode 100644 scripts/flaky-tests.fixtures/load-error.fixture.ts delete mode 100644 scripts/flaky-tests.test.ts delete mode 100644 scripts/flaky-tests.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e60d3cfa7..ff60a19f54 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -447,8 +447,6 @@ jobs: contents: read # To cancel this run at its first failure (.github/actions/stop-on-failure). actions: write - # To read the tests set aside (open flaky-test issues, scripts/flaky-tests.ts). - issues: read env: PLAYWRIGHT_IMAGE: mcr.microsoft.com/playwright:v1.62.1-noble@sha256:dcc5531e97840b9b5e794f2814476b21571c5124a3fca2267d73041f56e7580e steps: @@ -502,9 +500,6 @@ jobs: # onboarding frame reads the generated app config, which `bun test` alone doesn't write (the # test script's pretest does). - run: bun run generate:app-config - # Under scripts/flaky-tests.ts, like every real-browser list and the suite's shards: a test - # that fails runs once more, one that then passes is flaky and named in the run's notes, and a - # test set aside (an open flaky-test issue) still runs but does not fail the job. - run: | # One file per line, sorted: pull requests that each add a file then merge cleanly. files=( @@ -554,15 +549,12 @@ jobs: extension/tests/idle-worker.browser.test.ts extension/tests/recording-mark.browser.test.ts ) - bun scripts/flaky-tests.ts run -- \ docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 \ "$PLAYWRIGHT_IMAGE" \ - bun test --parallel --retry=1 "${files[@]}" - env: - GH_TOKEN: ${{ github.token }} + bun test --parallel "${files[@]}" # On a failure, cancels the run at once (.github/actions/stop-on-failure). - if: failure() uses: $/.github/actions/stop-on-failure @@ -716,8 +708,6 @@ jobs: contents: read # To cancel this run at its first failure (.github/actions/stop-on-failure). actions: write - # To read the tests set aside (open flaky-test issues, scripts/flaky-tests.ts). - issues: read env: PLAYWRIGHT_IMAGE: mcr.microsoft.com/playwright:v1.62.1-noble@sha256:dcc5531e97840b9b5e794f2814476b21571c5124a3fca2267d73041f56e7580e TEST_WORKERS: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository && '2' || '8' }} @@ -880,15 +870,12 @@ jobs: app/tests/work-folded-layout.test.tsx app/tests/workspace-snapshots-layout.test.tsx ) - bun scripts/flaky-tests.ts run -- \ docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES="$BROWSER_ENGINE" \ "$PLAYWRIGHT_IMAGE" \ - bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" --retry=1 --shard="$TEST_SHARD" --timings="scripts/browser-timings/$BROWSER_ENGINE.json" --update-timings "${files[@]}" - env: - GH_TOKEN: ${{ github.token }} + bun test --parallel="$TEST_WORKERS" --timeout="$TEST_TIMEOUT_MS" --shard="$TEST_SHARD" --timings="scripts/browser-timings/$BROWSER_ENGINE.json" --update-timings "${files[@]}" # This shard's own durations, which the run wrote over the engine's record: download every # shard's and merge them to refresh it (scripts/browser-timings.ts). - if: ${{ !cancelled() }} @@ -901,16 +888,13 @@ jobs: # Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard. # Only that test: the rest of the file runs in Chromium in the job above. Once, on the first shard. - if: matrix.engine == 'WebKit' && matrix.shard == 1 - env: - GH_TOKEN: ${{ github.token }} run: | - bun scripts/flaky-tests.ts run -- \ docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=webkit \ "$PLAYWRIGHT_IMAGE" \ - bun test --retry=1 app/tests/connect-your-ai.test.tsx -t "copies with one press" + bun test app/tests/connect-your-ai.test.tsx -t "copies with one press" # On a failure, cancels the run at once (.github/actions/stop-on-failure). - if: failure() uses: $/.github/actions/stop-on-failure @@ -930,8 +914,6 @@ jobs: contents: read # To cancel this run at its first failure (.github/actions/stop-on-failure). actions: write - # To read the tests set aside (open flaky-test issues, scripts/flaky-tests.ts). - issues: read env: PLAYWRIGHT_IMAGE: mcr.microsoft.com/playwright:v1.62.1-noble@sha256:dcc5531e97840b9b5e794f2814476b21571c5124a3fca2267d73041f56e7580e steps: @@ -946,34 +928,27 @@ jobs: working-directory: desktop # A list, as in the jobs above, so scripts/ci-changes.ts can tell this job covers the file and a # change to it does not run it a second time in `tests (changed files)`. Paths from desktop/. - # Under scripts/flaky-tests.ts, as the lists above. - - env: - GH_TOKEN: ${{ github.token }} - run: | + - run: | files=( src/setupLayout.approved.browser.test.ts src/setupLayout.browser.test.ts src/setupLayout.moveToCloud.browser.test.ts ) - bun scripts/flaky-tests.ts run --root desktop -- \ docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE/desktop" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 \ "$PLAYWRIGHT_IMAGE" \ - bun test --parallel --retry=1 "${files[@]}" + bun test --parallel "${files[@]}" # Connect your AI's key field and tab row, in WebKit, the engine the Mac window draws with. # Only those tests: the rest of the file runs in Chromium in the step above. - - env: - GH_TOKEN: ${{ github.token }} - run: | - bun scripts/flaky-tests.ts run --root desktop -- \ + - run: | docker run --rm --ipc=host \ --volume "$GITHUB_WORKSPACE:$GITHUB_WORKSPACE" --workdir "$GITHUB_WORKSPACE/desktop" \ --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINE=webkit \ "$PLAYWRIGHT_IMAGE" \ - bun test --retry=1 src/setupLayout.browser.test.ts -t "the key field and the tab row" + bun test src/setupLayout.browser.test.ts -t "the key field and the tab row" # On a failure, cancels the run at once (.github/actions/stop-on-failure). - if: failure() uses: $/.github/actions/stop-on-failure @@ -997,8 +972,6 @@ jobs: contents: read # To cancel this run at its first failure (.github/actions/stop-on-failure). actions: write - # To read the tests set aside (open flaky-test issues, scripts/flaky-tests.ts). - issues: read strategy: # Every shard runs to the end, so one red run names every failing test, not just the first # shard's. On a pull request the first failure anywhere stops the whole run instead @@ -1027,11 +1000,8 @@ jobs: - run: bun install --frozen-lockfile working-directory: desktop # This shard's tests, failing on a failed test or on a count it cannot read. The floor under the - # count is the suite's, so the `tests` job checks it on the sum of the shards. A failed test - # runs once more, and a test set aside does not fail the shard (scripts/flaky-tests.ts). + # count is the suite's, so the `tests` job checks it on the sum of the shards. - run: bun run test:ci - env: - GH_TOKEN: ${{ github.token }} # The shard's count, and how long each of its files took. - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: @@ -1105,8 +1075,6 @@ jobs: contents: read # To cancel this run at its first failure (.github/actions/stop-on-failure). actions: write - # To read the tests set aside (open flaky-test issues, scripts/flaky-tests.ts). - issues: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -1136,8 +1104,6 @@ jobs: BROWSER_TESTS: ${{ needs.changes.outputs.browser_tests }} WEBKIT_TESTS: ${{ needs.changes.outputs.webkit_tests }} DESKTOP_BROWSER_TESTS: ${{ needs.changes.outputs.desktop_browser_tests }} - # The tests set aside, read from the open flaky-test issues (scripts/flaky-tests.ts). - GH_TOKEN: ${{ github.token }} run: bun scripts/ci-run-tests.ts # On a failure, cancels the run at once (.github/actions/stop-on-failure). - if: failure() diff --git a/.github/workflows/flaky-tests.yml b/.github/workflows/flaky-tests.yml deleted file mode 100644 index e70a05b3da..0000000000 --- a/.github/workflows/flaky-tests.yml +++ /dev/null @@ -1,60 +0,0 @@ -name: Flaky tests - -# After every run of CI: reads the "Flaky tests" notes its test steps left (scripts/flaky-tests.ts) -# and keeps one `flaky-test` issue per flaky test (scripts/flaky-tests-watch.ts). A test that failed -# and then passed on its retry opens its issue, with an owner and a review date, and is set aside -# while the issue is open: it still runs, and its failures do not fail CI. A test set aside that -# passes 60 runs in a row first time is released, and its issue closed. It reads runs and their -# notes through the API only; nothing here checks out or runs a pull request's code, and runs from -# forks are left alone. -on: - workflow_run: - workflows: [CI] - types: [completed] - workflow_dispatch: - inputs: - dry_run: - description: Say what would change, and change nothing. - type: boolean - default: true - -permissions: - contents: read - -# One at a time, so two never write one issue at once. A run that finds another waiting replaces it, -# and reads every run that finished since the last one that succeeded, so nothing is lost. -concurrency: - group: flaky-tests - cancel-in-progress: false - -jobs: - watch: - name: flaky tests - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: read - # To list the runs that finished, and where this workflow last left off. - actions: read - # To read the notes the test steps left on their jobs. - checks: read - # To open, update, reopen and close the flaky-test issues. - issues: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.4.3 - no-cache: true - - name: Flaky tests - env: - GH_TOKEN: ${{ github.token }} - WATCHED: CI - DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} - run: | - set -euo pipefail - args=() - if [ "$DRY_RUN" = true ]; then args+=(--dry-run); fi - bun scripts/flaky-tests-watch.ts "${args[@]}" diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index c07a3748c9..db61e6d1d6 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -404,9 +404,6 @@ jobs: # CI's `release note` asks for it, to read a pull request's description. It runs on a pull # request only, so on this push it is skipped and reads nothing. pull-requests: read - # CI's test jobs ask for it, to read the tests set aside (open flaky-test issues, - # scripts/flaky-tests.ts). - issues: read # The images, built once from the commit that passed the checks above, and tagged with this # release's version and `latest`, with the server, computer and supervisor pinned at the tag this diff --git a/.github/zizmor.yml b/.github/zizmor.yml index f2d4c25782..f19aa05cf1 100644 --- a/.github/zizmor.yml +++ b/.github/zizmor.yml @@ -20,12 +20,8 @@ rules: # nothing from the run, and leaves runs from forks alone (scripts/ci-watch.ts). Contributor CI # needs it to look as soon as a run of CI or Desktop starts or finishes, rather than polling on a # timer. It checks out only scripts/contributor-ci.ts from the default branch, never the run's - # code, downloads no artifact, and acts on runs through the API alone. Flaky tests needs it to - # read the notes CI's test steps left once a run finishes. It checks out only the default branch's - # own code, downloads no artifact, runs nothing from the run, and leaves runs from forks alone - # (scripts/flaky-tests-watch.ts). + # code, downloads no artifact, and acts on runs through the API alone. dangerous-triggers: ignore: - ci-watch.yml - contributor-ci.yml - - flaky-tests.yml diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 6f6dd07106..c51a427599 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -896,8 +896,6 @@ function fullBrowserFiles( flag, ) || /^--timeout=(?:[1-9]\d*|"\$[A-Z_][A-Z0-9_]*")$/.test(flag) || - // A failed test run once more still runs every file (scripts/flaky-tests.ts). - /^--retry=[1-9]\d*$/.test(flag) || (completeShards && flag === '--shard="$TEST_SHARD"') || // Recorded durations move a file between shards, never out of them, as long // as every shard of an engine reads the same record: a fixed path, or one named diff --git a/scripts/ci-run-tests.test.ts b/scripts/ci-run-tests.test.ts index a1fff57956..31fd84f24d 100644 --- a/scripts/ci-run-tests.test.ts +++ b/scripts/ci-run-tests.test.ts @@ -127,12 +127,10 @@ describe("changed desktop browser tests", () => { "desktop/src/other.browser.test.ts", ]); expect(result.status).toBe(0); - // Each run retries a failed test once (scripts/flaky-tests.ts). expect(result.calls).toEqual([ { args: [ "test", - "--retry=1", "./src/setupLayout.browser.test.ts", "./src/other.browser.test.ts", ], @@ -145,7 +143,6 @@ describe("changed desktop browser tests", () => { "test", "-t", "the key field and the tab row", - "--retry=1", "./src/setupLayout.browser.test.ts", ], cwd: result.cwd, diff --git a/scripts/ci-run-tests.ts b/scripts/ci-run-tests.ts index 156ae243f4..ed15643fd0 100644 --- a/scripts/ci-run-tests.ts +++ b/scripts/ci-run-tests.ts @@ -12,14 +12,6 @@ */ import { existsSync, lstatSync } from "node:fs"; import { isBunTest, unusualPath } from "./ci-changes"; -import { - judge, - parseBunOutput, - type Quarantine, - readableBunEnv, - readQuarantine, - report, -} from "./flaky-tests"; import { testsRan } from "./test-floor"; /** A path from the changes job, held to being a test file inside this checkout. */ @@ -47,9 +39,6 @@ export function testPaths(json: string | undefined, name: string): string[] { }); } -/** The tests set aside (open flaky-test issues), read once for every group. */ -let quarantine: Promise | undefined; - async function runGroup( label: string, command: string[], @@ -58,25 +47,16 @@ async function runGroup( ): Promise { if (files.length === 0) return true; console.log(`\n${label}: ${files.join(" ")}`); - quarantine ??= readQuarantine(); - // A failed test runs once more; one that then passes is flaky, and named in the run's notes, and - // a test set aside does not fail the group (scripts/flaky-tests.ts). - const proc = Bun.spawn([...command, "--retry=1", ...files], { + const proc = Bun.spawn([...command, ...files], { cwd: options.cwd, - env: readableBunEnv({ ...process.env, ...options.env }), + env: { ...process.env, ...options.env }, stdout: "inherit", stderr: "pipe", }); const stderr = await new Response(proc.stderr).text(); process.stderr.write(stderr); - const setAside = await quarantine; - const verdict = judge( - parseBunOutput(stderr, options.cwd ?? ""), - await proc.exited, - setAside.tests, - ); - process.stdout.write(report(verdict, setAside)); - if (verdict.blocking) return false; + const status = await proc.exited; + if (status !== 0) return false; const count = testsRan(stderr); if (!count) { console.error( diff --git a/scripts/ci-watch.test.ts b/scripts/ci-watch.test.ts index fa60a66d92..38461c751e 100644 --- a/scripts/ci-watch.test.ts +++ b/scripts/ci-watch.test.ts @@ -67,14 +67,6 @@ describe("the tests a failed job's log names", () => { ]); }); - test("leave out the go a retry adds, as the notes of a run name a test", () => { - expect( - failingTests( - "2026-12-04T10:00:00.0000000Z (fail) a group > a test (attempt 2) [12.00ms]\n", - ), - ).toEqual(["a group > a test"]); - }); - test("are none in a log with no failed test", () => { expect( failingTests( diff --git a/scripts/ci-watch.ts b/scripts/ci-watch.ts index df8abe908c..d88acd4827 100644 --- a/scripts/ci-watch.ts +++ b/scripts/ci-watch.ts @@ -146,14 +146,7 @@ export function failingTests(log: string): string[] { line, ); const cargo = /^test (\S+) \.\.\. FAILED$/.exec(line); - // Named as scripts/flaky-tests.ts names a test, so both write to one issue: without the go a - // retry adds. - const name = ( - bun?.[1] ?? - pytest?.[1] ?? - playwright?.[1] ?? - cargo?.[1] - )?.replace(/ \((?:attempt \d+|retry #\d+)\)$/, ""); + const name = bun?.[1] ?? pytest?.[1] ?? playwright?.[1] ?? cargo?.[1]; if (name) found.add(name.trim()); } return [...found]; diff --git a/scripts/flaky-tests-watch.ts b/scripts/flaky-tests-watch.ts deleted file mode 100644 index c8ed44fd0c..0000000000 --- a/scripts/flaky-tests-watch.ts +++ /dev/null @@ -1,588 +0,0 @@ -#!/usr/bin/env bun -/** - * Keeps one `flaky-test` issue per flaky test, after each run of a watched workflow - * (.github/workflows/flaky-tests.yml). An open issue this opened, reopened or took on carries its - * state block, and sets its test aside (scripts/flaky-tests.ts): the test still runs, and its - * failure does not fail CI. An open issue without the block (ci-watch.ts's, or one from before this) - * sets nothing aside until a run records its test failing and then passing: then this takes it on. - * - * It reads the "Flaky tests" notices the test steps left on the runs that finished since it last - * looked, oldest first, and for each test they name: - * - * - FAILED, THEN PASSED, or FAILED WHILE SET ASIDE: opens the test's issue with an owner (the last - * person to change its file) and a review date, or reopens it, and starts its count of clean runs - * again from nothing. - * - SET ASIDE, PASSED: counts one more run in a row that passed it on the first go. At 60 in a row - * it closes the issue: the test is released, and its failures count again. 60 clean runs is the - * count at which a test that still failed one go in twenty would almost surely (95%) have failed - * one of them, the 5% Airtable quarantines a test at. Closing the issue by hand releases it too. - * - On an issue whose review date has come, it asks the owner to look again, once, and sets the - * next date. - * - * Each run is counted once per issue (its id is kept in the issue), so a run read twice changes - * nothing. The workflow runs one of these at a time; one that finds another waiting reads from where - * the last one that finished left off, so a run dropped from the queue loses nothing. - * - * Runs from forks are left alone. Env: GITHUB_REPOSITORY, GH_TOKEN (actions: read, checks: read, - * issues: write), WATCHED (the workflows' names, comma-separated). `--dry-run` says what it would - * do and does nothing. - */ -import { appendFileSync } from "node:fs"; -import { - LABEL, - NOTE_TITLE, - type Observation, - type Outcome, - parseNote, - RELEASE_AFTER, - REVIEW_DAYS, - STATE_MARK, - TITLE_PREFIX, -} from "./flaky-tests"; - -export type State = { - v: 1; - /** The test's file, from the repository's root, when a run named it. */ - file?: string; - /** The GitHub login the issue is assigned to. */ - owner?: string | null; - /** The day its owner is asked to look at it again (YYYY-MM-DD). */ - review: string; - /** The day it was set aside, this time. */ - since: string; - /** Runs in a row that passed it on the first go. */ - streak: number; - /** Runs it failed in (and then passed, or failed while set aside), since it was set aside. */ - failures: number; - /** The last run it failed in. */ - last?: { run: number; url: string; outcome: Outcome }; - /** The runs already counted, newest last. */ - runs: number[]; - /** The review date its owner was last asked about. */ - reminded?: string; -}; - -export type Issue = { - number: number; - title: string; - state: "open" | "closed"; - body: string | null; - created_at: string; - assignees?: { login: string }[]; -}; - -/** A finished run, and what its notices said. */ -export type RunNotes = { - id: number; - url: string; - observations: Observation[]; -}; - -export type Action = - | { - kind: "open"; - title: string; - body: string; - assignees: string[]; - } - | { - kind: "update"; - number: number; - title: string; - body: string; - state?: "open" | "closed"; - assignees?: string[]; - comment?: string; - }; - -const STATE_BLOCK = new RegExp(``, "s"); -const KEEP_RUNS = 120; - -export function readState(body: string | null): State | undefined { - const json = STATE_BLOCK.exec(body ?? "")?.[1]; - if (!json) return undefined; - try { - const state = JSON.parse(json) as State; - return state.v === 1 ? state : undefined; - } catch { - return undefined; - } -} - -export function day(date: Date): string { - return date.toISOString().slice(0, 10); -} - -function addDays(date: Date, days: number): string { - return day(new Date(date.getTime() + days * 86_400_000)); -} - -/** The issue's body: what it means, where the test stands, and the state the next run reads. */ -export function renderBody(state: State): string { - const owner = state.owner - ? `@${state.owner}${state.file ? ` (the last person to change \`${state.file}\`)` : ""}` - : state.file - ? `nobody yet: no person has changed \`${state.file}\`` - : "nobody yet: no run has named the test's file"; - const last = state.last - ? `, last in [run ${state.last.run}](${state.last.url})` - : ""; - return [ - "A test that failed and then passed with no change to the code. While this issue is open the test is **set aside**: it still runs in CI and its results are counted here, but its failures do not fail a pull request or the merge queue (scripts/flaky-tests.ts).", - "", - `- **Owner:** ${owner}`, - `- **Set aside since:** ${state.since}`, - `- **Review by:** ${state.review}`, - `- **Runs it failed in since then:** ${state.failures}${last}`, - `- **Runs in a row it passed first time:** ${state.streak} of ${RELEASE_AFTER}`, - "", - `It is released by itself, and this issue closed, once it passes ${RELEASE_AFTER} runs in a row first time. Closing this by hand releases it too. It reopens if the test fails that way again.`, - "", - ``, - ].join("\n"); -} - -/** The latest commit's author of a file who is a person: the commits API's list, newest first. */ -export function ownerOf( - commits: { author: { login: string; type: string } | null }[], -): string | null { - for (const commit of commits) { - const author = commit.author; - if (author && author.type === "User" && !author.login.endsWith("[bot]")) { - return author.login; - } - } - return null; -} - -type Working = { - issue?: Issue; - title: string; - state?: State; - /** Fields to change, when anything did. */ - changed: boolean; - reopen: boolean; - close: boolean; - comments: string[]; - assignees?: string[]; -}; - -/** - * What to do with the issues, given what the runs said, oldest run first. `owners` holds the owner - * of each file a run named (null for none). Pure: it reads and changes nothing. - */ -export function plan( - issues: Issue[], - runs: RunNotes[], - owners: Map, - now: Date, -): Action[] { - const today = day(now); - const byTitle = new Map(); - for (const issue of [...issues].sort((a, b) => a.number - b.number)) { - if (!byTitle.has(issue.title)) byTitle.set(issue.title, issue); - } - const work = new Map(); - const working = (title: string): Working => { - let found = work.get(title); - if (!found) { - const issue = byTitle.get(title); - found = { - issue, - title, - state: readState(issue?.body ?? null), - changed: false, - reopen: false, - close: false, - comments: [], - }; - work.set(title, found); - } - return found; - }; - const fresh = (file: string, since: string): State => ({ - v: 1, - file: file || undefined, - owner: file ? (owners.get(file) ?? null) : null, - review: addDays(now, REVIEW_DAYS), - since, - streak: 0, - failures: 0, - runs: [], - }); - - /** - * An open issue this did not write yet (ci-watch.ts opens them too, for a job that failed and then - * passed when re-run, and some are older than this): it set nothing aside. A run that records its - * test failing and then passing takes it on, with an owner, a review date and a count from nothing, - * and from then on it sets its test aside. Otherwise fills in a file and owner the state lacks. - */ - const adopt = ( - w: Working, - observation: Observation, - run: RunNotes, - ): State => { - if (!w.state) { - w.state = fresh(observation.file, today); - w.comments.push( - `In [run ${run.id}](${run.url}) it failed, then passed on its retry. Set aside from now until it passes ${RELEASE_AFTER} runs in a row first time${w.state.owner ? `; @${w.state.owner}, it is yours to fix by ${w.state.review}` : ""}.`, - ); - } else if (!w.state.file && observation.file) { - w.state.file = observation.file; - w.state.owner ??= owners.get(observation.file) ?? null; - } - if (w.state.owner && !w.issue?.assignees?.length) { - w.assignees = [w.state.owner]; - } - return w.state; - }; - - for (const run of runs) { - // One verdict per test per run: a run that failed it anywhere failed it. - const worst = new Map(); - for (const observation of run.observations) { - const seen = worst.get(observation.name); - if (!seen || seen.outcome === "quarantined-passed") { - worst.set(observation.name, observation); - } - } - for (const observation of worst.values()) { - const w = working(`${TITLE_PREFIX}${observation.name}`); - const open = w.issue - ? (w.issue.state === "open" || w.reopen) && !w.close - : w.state !== undefined; - if (w.state?.runs.includes(run.id)) continue; - if (observation.outcome === "quarantined-passed") { - // Released, or closed by hand, since the run read the list, or never set aside by this: - // nothing to count. - if (!open || !w.state) continue; - adopt(w, observation, run); - // Released, then reopened by hand or by ci-watch.ts: set aside again, counted afresh. - if (w.state.streak >= RELEASE_AFTER) w.state.streak = 0; - w.state.streak += 1; - w.state.runs = [...w.state.runs, run.id].slice(-KEEP_RUNS); - w.changed = true; - if (w.state.streak >= RELEASE_AFTER) { - w.close = true; - w.reopen = false; - w.comments.push( - `Passed ${w.state.streak} runs in a row first time, the last of them [run ${run.id}](${run.url}). Released: its failures fail CI again. This reopens if it fails that way again.`, - ); - } - continue; - } - // Failed, then passed; or failed while set aside. - const said = - observation.outcome === "flaky" - ? "failed, then passed on its retry" - : "failed while set aside"; - if (!open) { - const wasClosed = w.issue !== undefined; - w.state = { - ...fresh(observation.file, today), - // A test that comes back keeps its owner and file. - ...(w.state?.owner ? { owner: w.state.owner } : {}), - ...(w.state?.file ? { file: w.state.file } : {}), - failures: 0, - runs: w.state?.runs ?? [], - }; - if (!w.state.owner && w.state.file) { - w.state.owner = owners.get(w.state.file) ?? null; - } - w.reopen = wasClosed; - w.close = false; - w.assignees = w.state.owner ? [w.state.owner] : []; - w.comments.push( - `In [run ${run.id}](${run.url}) it ${said}. Set aside${wasClosed ? " again" : ""} until it passes ${RELEASE_AFTER} runs in a row first time${w.state.owner ? `; @${w.state.owner}, it is yours to fix by ${w.state.review}` : ""}.`, - ); - } else { - // Only a fail-then-pass takes an issue on: a test it never set aside cannot fail set aside. - if (!w.state && observation.outcome !== "flaky") continue; - adopt(w, observation, run); - } - if (!w.state) continue; - w.state.streak = 0; - w.state.failures += 1; - w.state.last = { - run: run.id, - url: run.url, - outcome: observation.outcome, - }; - w.state.runs = [...w.state.runs, run.id].slice(-KEEP_RUNS); - w.changed = true; - } - } - - // An open issue whose review date has come asks its owner to look again, once. - for (const issue of byTitle.values()) { - if (issue.state !== "open" || !issue.title.startsWith(TITLE_PREFIX)) { - continue; - } - const w = working(issue.title); - if (!w.state || w.close || w.state.review > today) continue; - if (w.state.reminded === w.state.review) continue; - const who = w.state.owner ? `@${w.state.owner}, ` : ""; - w.comments.push( - `${who}this test has been set aside since ${w.state.since} and its review date (${w.state.review}) has come. It has failed in ${w.state.failures} run(s) since then and passed the last ${w.state.streak} first time. Fix it, or close this issue to make its failures count again. Next review: ${addDays(now, REVIEW_DAYS)}.`, - ); - w.state.reminded = w.state.review; - w.state.review = addDays(now, REVIEW_DAYS); - w.changed = true; - } - - const actions: Action[] = []; - for (const w of work.values()) { - if (!w.changed || !w.state) continue; - const body = renderBody(w.state); - if (!w.issue) { - actions.push({ - kind: "open", - title: w.title, - body: [body, ...w.comments].join("\n\n"), - assignees: w.assignees ?? [], - }); - continue; - } - actions.push({ - kind: "update", - number: w.issue.number, - title: w.title, - body, - ...(w.close ? { state: "closed" as const } : {}), - ...(w.reopen ? { state: "open" as const } : {}), - ...(w.assignees?.length ? { assignees: w.assignees } : {}), - ...(w.comments.length ? { comment: w.comments.join("\n\n") } : {}), - }); - } - return actions; -} - -// --------------------------------------------------------------------------------------------- - -function gh(args: string[], input?: string): string { - const result = Bun.spawnSync(["gh", "api", ...args], { - stdin: input === undefined ? "ignore" : new TextEncoder().encode(input), - stdout: "pipe", - stderr: "pipe", - }); - if (result.exitCode !== 0) { - throw new Error( - `gh api ${args.join(" ")}: ${result.stderr.toString().trim()}`, - ); - } - return result.stdout.toString(); -} - -const json = (args: string[]): T => JSON.parse(gh(args)) as T; - -type ApiRun = { - id: number; - name: string; - html_url: string; - check_suite_id: number; - created_at: string; - updated_at: string; - status: string; - head_repository?: { full_name: string } | null; -}; - -/** The runs of the watched workflows that finished since `since`, oldest first, none from forks. */ -function finishedRuns( - repository: string, - watched: string[], - since: Date, -): ApiRun[] { - // A run finishes after it starts: look back a while further for the ones created earlier. - const created = new Date(since.getTime() - 3 * 3_600_000).toISOString(); - const runs: ApiRun[] = []; - for (let page = 1; page <= 10; page++) { - const batch = json<{ workflow_runs: ApiRun[] }>([ - `repos/${repository}/actions/runs?status=completed&created=%3E%3D${encodeURIComponent(created)}&per_page=100&page=${page}`, - ]).workflow_runs; - runs.push(...batch); - if (batch.length < 100) break; - } - return runs - .filter( - (run) => - watched.includes(run.name) && - Date.parse(run.updated_at) >= since.getTime() && - (!run.head_repository || run.head_repository.full_name === repository), - ) - .sort((a, b) => Date.parse(a.updated_at) - Date.parse(b.updated_at)); -} - -/** What a run's "Flaky tests" notices said. */ -function notesOf(repository: string, run: ApiRun): Observation[] { - const checks = json< - { - check_runs: { id: number; output: { annotations_count: number } }[]; - }[] - >([ - "--paginate", - "--slurp", - `repos/${repository}/check-suites/${run.check_suite_id}/check-runs?filter=all&per_page=100`, - ]).flatMap((page) => page.check_runs); - const observations: Observation[] = []; - for (const check of checks) { - if (!check.output.annotations_count) continue; - const annotations = json< - { title: string | null; annotation_level: string; message: string }[][] - >([ - "--paginate", - "--slurp", - `repos/${repository}/check-runs/${check.id}/annotations?per_page=100`, - ]).flat(); - for (const annotation of annotations) { - if (annotation.title === NOTE_TITLE) { - observations.push(...parseNote(annotation.message)); - } - } - } - return observations; -} - -/** When the last run of this workflow that finished well started: where this one picks up. */ -function lastLooked(repository: string, workflowFile: string): Date { - const fallback = new Date(Date.now() - 3 * 3_600_000); - // A dry run changed nothing, so only a run after a watched one counts. Before this workflow's - // first run on the default branch there is none, and GitHub does not know the workflow yet. - let runs: { id: number; event: string; run_started_at: string }[] = []; - try { - runs = json<{ workflow_runs: typeof runs }>([ - `repos/${repository}/actions/workflows/${workflowFile}/runs?status=success&event=workflow_run&per_page=5`, - ]).workflow_runs.filter( - (run) => - String(run.id) !== process.env.GITHUB_RUN_ID && - run.event === "workflow_run", - ); - } catch { - return fallback; - } - const started = runs[0]?.run_started_at; - if (!started) return fallback; - // A little overlap: a run counted twice changes nothing. - const from = new Date(Date.parse(started) - 15 * 60_000); - // Never further back than a day. - return from.getTime() < Date.now() - 86_400_000 - ? new Date(Date.now() - 86_400_000) - : from; -} - -function apply(repository: string, action: Action): string { - if (action.kind === "open") { - const fields = [ - "-f", - `title=${action.title}`, - "-f", - `body=${action.body}`, - "-f", - `labels[]=${LABEL}`, - ...action.assignees.flatMap((login) => ["-f", `assignees[]=${login}`]), - ]; - const created = json<{ number: number }>([ - `repos/${repository}/issues`, - "--method", - "POST", - ...fields, - ]); - return `opened #${created.number}: ${action.title}`; - } - const fields = [ - "-f", - `body=${action.body}`, - ...(action.state ? ["-f", `state=${action.state}`] : []), - ...(action.state === "closed" ? ["-f", "state_reason=completed"] : []), - ...(action.assignees ?? []).flatMap((login) => [ - "-f", - `assignees[]=${login}`, - ]), - ]; - gh([ - `repos/${repository}/issues/${action.number}`, - "--method", - "PATCH", - ...fields, - ]); - if (action.comment) { - gh([ - `repos/${repository}/issues/${action.number}/comments`, - "--method", - "POST", - "-f", - `body=${action.comment}`, - ]); - } - const did = - action.state === "closed" - ? "released (closed)" - : action.state === "open" - ? "reopened" - : "updated"; - return `${did} #${action.number}: ${action.title}`; -} - -if (import.meta.main) { - const dryRun = process.argv.includes("--dry-run"); - const repository = process.env.GITHUB_REPOSITORY ?? ""; - const watched = (process.env.WATCHED ?? "") - .split(",") - .map((name) => name.trim()) - .filter(Boolean); - if (!repository || !watched.length) { - console.error("GITHUB_REPOSITORY and WATCHED must be set."); - process.exit(2); - } - const since = lastLooked(repository, "flaky-tests.yml"); - const runs = finishedRuns(repository, watched, since).map((run) => ({ - id: run.id, - url: run.html_url, - observations: notesOf(repository, run), - })); - const issues = json([ - "--paginate", - "--slurp", - `repos/${repository}/issues?labels=${LABEL}&state=all&per_page=100`, - ]) - .flat() - .filter((issue) => !("pull_request" in issue)); - // The owner of each file a run named: the last person to change it. - const owners = new Map(); - for (const file of new Set( - runs.flatMap((run) => run.observations.map((o) => o.file)).filter(Boolean), - )) { - try { - owners.set( - file, - ownerOf( - json([ - `repos/${repository}/commits?path=${encodeURIComponent(file)}&per_page=20`, - ]), - ), - ); - } catch { - owners.set(file, null); - } - } - const actions = plan(issues, runs, owners, new Date()); - const said: string[] = [ - `### Flaky tests: ${runs.length} run(s) finished since ${since.toISOString()}`, - ]; - for (const run of runs) { - if (run.observations.length) { - said.push( - `- [run ${run.id}](${run.url}): ${run.observations.length} note(s)`, - ); - } - } - for (const action of actions) { - said.push( - `- ${dryRun ? `would ${action.kind === "open" ? "open" : `change #${action.number}`}: ${action.title}` : apply(repository, action)}`, - ); - } - if (!actions.length) said.push("- No issue to change."); - console.log(said.join("\n")); - if (process.env.GITHUB_STEP_SUMMARY) { - appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${said.join("\n")}\n`); - } -} diff --git a/scripts/flaky-tests.fixtures/broken.fixture.ts b/scripts/flaky-tests.fixtures/broken.fixture.ts deleted file mode 100644 index fe5cff8d62..0000000000 --- a/scripts/flaky-tests.fixtures/broken.fixture.ts +++ /dev/null @@ -1,6 +0,0 @@ -import { expect, test } from "bun:test"; - -/** Run by scripts/flaky-tests.test.ts, never by the suite: a test that fails on every go. */ -test("a broken test > fails every time", () => { - expect("what it does").toBe("what it should do"); -}); diff --git a/scripts/flaky-tests.fixtures/flaky.fixture.ts b/scripts/flaky-tests.fixtures/flaky.fixture.ts deleted file mode 100644 index a6c0693f2d..0000000000 --- a/scripts/flaky-tests.fixtures/flaky.fixture.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { describe, expect, test } from "bun:test"; - -/** - * Run by scripts/flaky-tests.test.ts through `bun scripts/flaky-tests.ts run -- bun test --retry=1`, - * never by the suite (no `.test.` in its name). A retry runs in the same process, so the count of - * goes carries over from the first to the second. - */ -let goes = 0; - -describe("a flaky group", () => { - test("fails once, then passes", () => { - goes += 1; - expect(goes).toBeGreaterThan(1); - }); - - test("passes every time", () => { - expect(1 + 1).toBe(2); - }); -}); diff --git a/scripts/flaky-tests.fixtures/load-error.fixture.ts b/scripts/flaky-tests.fixtures/load-error.fixture.ts deleted file mode 100644 index 5e64d148b1..0000000000 --- a/scripts/flaky-tests.fixtures/load-error.fixture.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { test } from "bun:test"; - -/** Run by scripts/flaky-tests.test.ts, never by the suite: a file that fails while it loads. */ -throw new Error("this file fails while it loads"); - -// biome-ignore lint/correctness/noUnreachable: the point of the fixture -test("never registered", () => {}); diff --git a/scripts/flaky-tests.test.ts b/scripts/flaky-tests.test.ts deleted file mode 100644 index 2e5469700f..0000000000 --- a/scripts/flaky-tests.test.ts +++ /dev/null @@ -1,481 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from "bun:test"; -import { mkdtempSync, readFileSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { - marked, - notices, - parseBunOutput, - parseNote, - RELEASE_AFTER, - readableBunEnv, -} from "./flaky-tests"; -import { - type Issue, - ownerOf, - plan, - type RunNotes, - readState, - renderBody, -} from "./flaky-tests-watch"; - -/** - * Flaky tests set aside (scripts/flaky-tests.ts, scripts/flaky-tests-watch.ts), through real - * `bun test` runs of the files in scripts/flaky-tests.fixtures, wrapped as CI wraps its test steps, - * and the quarantine read from an issues endpoint that answers as GitHub's does. - */ - -const ROOT = join(import.meta.dir, ".."); -const FIXTURES = "scripts/flaky-tests.fixtures"; -const REPOSITORY = "CopilotKit/OpenBot"; - -/** The open flaky-test issues the fake GitHub holds. */ -let openIssues: { number: number; title: string; body: string }[] = []; - -/** An issue the watch opened from a recorded fail-then-pass: its body carries the state block. */ -const watched = (number: number, name: string) => ({ - number, - title: `Flaky test: ${name}`, - body: renderBody({ - v: 1, - file: "scripts/flaky-tests.fixtures/broken.fixture.ts", - owner: "someone", - review: "2026-12-18", - since: "2026-12-04", - streak: 0, - failures: 1, - runs: [1], - }), -}); - -/** An issue from before the watch, as ci-watch.ts writes them: no state block. */ -const older = (number: number, name: string) => ({ - number, - title: `Flaky test: ${name}`, - body: "A test that failed and then passed on the same commit, with no change to the code. Each comment below is one time it happened, with the run and the job. Fix the cause and close this; it reopens if the test fails that way again.\n\nFailed in [tests (shard 2 of 5)](https://github.com/CopilotKit/OpenBot/actions/runs/1/job/2), then passed.", -}); -let server: ReturnType; -let summaryDir: string; - -beforeAll(() => { - server = Bun.serve({ - port: 0, - fetch(request) { - const url = new URL(request.url); - if ( - url.pathname !== `/repos/${REPOSITORY}/issues` || - url.searchParams.get("labels") !== "flaky-test" || - url.searchParams.get("state") !== "open" || - request.headers.get("authorization") !== "Bearer test-token" - ) { - return new Response("Not Found", { status: 404 }); - } - // The issues API's shape: a page of issues, pull requests among them. - const page = Number(url.searchParams.get("page") ?? 1); - const body = - page === 1 - ? [ - ...openIssues.map((issue) => ({ - number: issue.number, - title: issue.title, - body: issue.body, - state: "open", - html_url: `https://github.com/${REPOSITORY}/issues/${issue.number}`, - labels: [{ name: "flaky-test" }], - })), - { - number: 9999, - title: "Flaky test: a pull request, not an issue", - state: "open", - html_url: `https://github.com/${REPOSITORY}/pull/9999`, - pull_request: { url: "https://api.github.com/..." }, - }, - ] - : []; - return Response.json(body); - }, - }); - summaryDir = mkdtempSync(join(tmpdir(), "flaky-tests-")); -}); - -afterAll(() => { - server.stop(true); - rmSync(summaryDir, { recursive: true, force: true }); -}); - -/** CI's wrapped step: `bun scripts/flaky-tests.ts run -- bun test --retry=1 `. */ -async function wrapped(files: string[], quarantine: boolean) { - const summary = join(summaryDir, `${crypto.randomUUID()}.md`); - const env: Record = { - ...readableBunEnv(), - GITHUB_STEP_SUMMARY: summary, - GITHUB_API_URL: `http://127.0.0.1:${server.port}`, - }; - delete env.GITHUB_ACTIONS; - if (quarantine) { - env.GITHUB_REPOSITORY = REPOSITORY; - env.GH_TOKEN = "test-token"; - } else { - delete env.GITHUB_REPOSITORY; - delete env.GH_TOKEN; - delete env.GITHUB_TOKEN; - } - const proc = Bun.spawn( - [ - "bun", - "scripts/flaky-tests.ts", - "run", - "--", - "bun", - "test", - "--retry=1", - ...files.map((file) => `./${FIXTURES}/${file}`), - ], - { cwd: ROOT, env, stdout: "pipe", stderr: "pipe" }, - ); - const [stdout, stderr] = await Promise.all([ - new Response(proc.stdout).text(), - new Response(proc.stderr).text(), - ]); - const exitCode = await proc.exited; - let written = ""; - try { - written = readFileSync(summary, "utf8"); - } catch {} - return { exitCode, stdout, stderr, summary: written }; -} - -/** The note lines a step's `::notice title=Flaky tests::` commands carry, as GitHub stores them. */ -function notesIn(stdout: string) { - return stdout - .split("\n") - .filter((line) => line.startsWith("::notice title=Flaky tests::")) - .flatMap((line) => - parseNote( - decodeURIComponent( - line - .slice("::notice title=Flaky tests::".length) - .replaceAll("%0D", "\r"), - ), - ), - ); -} - -describe("a CI test step wrapped by scripts/flaky-tests.ts", () => { - test("a test that fails and then passes on its retry passes the run, and is named as flaky", async () => { - const run = await wrapped(["flaky.fixture.ts"], false); - expect(run.exitCode).toBe(0); - expect(notesIn(run.stdout)).toEqual([ - { - outcome: "flaky", - name: "a flaky group > fails once, then passes", - file: `${FIXTURES}/flaky.fixture.ts`, - }, - ]); - // Without a token nothing is set aside, and the step says so. - expect(run.stdout).toContain("could not read the tests set aside"); - expect(run.summary).toContain( - "Failed, then passed on its retry: a flaky group > fails once, then passes", - ); - }, 60_000); - - test("a test that fails every time still fails the run", async () => { - const run = await wrapped(["broken.fixture.ts"], false); - expect(run.exitCode).toBe(1); - expect(run.stderr).toContain("(fail) a broken test > fails every time"); - expect(run.stdout).toContain("1 failing test(s) are not set aside"); - }, 60_000); - - test("a test set aside that fails does not fail the run; one that passes is counted", async () => { - openIssues = [ - watched(101, "a broken test > fails every time"), - watched(102, "a flaky group > passes every time"), - ]; - const run = await wrapped(["broken.fixture.ts", "flaky.fixture.ts"], true); - expect(run.exitCode).toBe(0); - expect(notesIn(run.stdout)).toEqual([ - { - outcome: "quarantined-failed", - name: "a broken test > fails every time", - file: `${FIXTURES}/broken.fixture.ts`, - }, - { - outcome: "flaky", - name: "a flaky group > fails once, then passes", - file: `${FIXTURES}/flaky.fixture.ts`, - }, - { - outcome: "quarantined-passed", - name: "a flaky group > passes every time", - file: `${FIXTURES}/flaky.fixture.ts`, - }, - ]); - expect(run.stdout).toContain( - "every test that failed is set aside, so the run passes", - ); - // Every test set aside is listed in the run's summary, the pull request's issue left out. - expect(run.summary).toContain("2 tests set aside"); - expect(run.summary).toContain( - `[#101](https://github.com/${REPOSITORY}/issues/101) a broken test > fails every time`, - ); - expect(run.summary).not.toContain("#9999"); - }, 60_000); - - test("a failure bun cannot tie to a test still fails the run, though the test that failed is set aside", async () => { - openIssues = [watched(101, "a broken test > fails every time")]; - const run = await wrapped( - ["broken.fixture.ts", "load-error.fixture.ts"], - true, - ); - expect(run.exitCode).toBe(1); - expect(run.stdout).toContain("error(s) outside a test"); - }, 60_000); - - test("an issue from before the watch, without its mark, sets nothing aside; one the watch marked does", async () => { - // The open "Flaky test:" issues ci-watch.ts filed before this keep blocking. - openIssues = [older(101, "a broken test > fails every time")]; - const old = await wrapped(["broken.fixture.ts"], true); - expect(old.exitCode).toBe(1); - expect(old.stdout).toContain("Flaky tests: 0 set aside"); - expect(old.stdout).toContain("1 failing test(s) are not set aside"); - expect(notesIn(old.stdout)).toEqual([]); - - // The same issue once the watch took it on from a recorded fail-then-pass. - openIssues = [watched(101, "a broken test > fails every time")]; - const taken = await wrapped(["broken.fixture.ts"], true); - expect(taken.exitCode).toBe(0); - expect(notesIn(taken.stdout)).toEqual([ - { - outcome: "quarantined-failed", - name: "a broken test > fails every time", - file: `${FIXTURES}/broken.fixture.ts`, - }, - ]); - }, 60_000); -}); - -describe("reading bun's output", () => { - test("names on GitHub Actions come in log groups, and a run in a folder is named from the root", () => { - const run = parseBunOutput( - [ - "::group::src/setupLayout.browser.test.ts:", - "(pass) the setup window > holds still (attempt 2) [812.40ms]", - "(fail) the setup window > the key field [5001.00ms]", - "(skip) the setup window > only on a Mac", - "::endgroup::", - "", - " 1 pass", - " 1 skip", - " 1 fail", - "Ran 3 tests across 1 file. [6.00s]", - ].join("\n"), - "desktop", - ); - expect(run.tests).toEqual([ - { - file: "desktop/src/setupLayout.browser.test.ts", - name: "the setup window > holds still", - status: "pass", - attempt: 2, - }, - { - file: "desktop/src/setupLayout.browser.test.ts", - name: "the setup window > the key field", - status: "fail", - attempt: 1, - }, - { - file: "desktop/src/setupLayout.browser.test.ts", - name: "the setup window > only on a Mac", - status: "skip", - attempt: 1, - }, - ]); - expect(run.counts).toEqual({ pass: 1, skip: 1, fail: 1 }); - }); - - test("a note round-trips through the notice command, and a long list splits into several", () => { - const observations = Array.from({ length: 400 }, (_, index) => ({ - outcome: "quarantined-passed" as const, - name: `a test with a long name, number ${index} ${"x".repeat(100)}`, - file: "app/tests/a.test.tsx", - })); - const commands = notices(observations); - expect(commands.length).toBeGreaterThan(1); - expect(notesIn(commands.join("\n"))).toEqual(observations); - }); -}); - -describe("the watch (scripts/flaky-tests-watch.ts)", () => { - const now = new Date("2026-12-04T12:00:00Z"); - const owners = new Map([["app/tests/home.test.tsx", "someone"]]); - const name = "home > holds still"; - const title = `Flaky test: ${name}`; - const runOf = ( - id: number, - outcome: RunNotes["observations"][0]["outcome"], - ) => ({ - id, - url: `https://github.com/${REPOSITORY}/actions/runs/${id}`, - observations: [{ outcome, name, file: "app/tests/home.test.tsx" }], - }); - const applied = (issue: Issue, actions: ReturnType): Issue => { - const action = actions.find( - (a) => a.kind === "update" && a.number === issue.number, - ); - if (action?.kind !== "update") return issue; - return { - ...issue, - body: action.body, - state: action.state ?? issue.state, - }; - }; - - test("a new flaky test opens its issue, set aside, with its owner and a review date", () => { - const actions = plan([], [runOf(1, "flaky")], owners, now); - expect(actions).toHaveLength(1); - const [open] = actions; - if (open?.kind !== "open") throw new Error("expected an issue opened"); - expect(open.title).toBe(title); - expect(open.assignees).toEqual(["someone"]); - const state = readState(open.body); - expect(state).toMatchObject({ - owner: "someone", - file: "app/tests/home.test.tsx", - since: "2026-12-04", - review: "2026-12-18", - streak: 0, - failures: 1, - runs: [1], - }); - expect(open.body).toContain("@someone"); - }); - - test(`a test set aside is released after ${RELEASE_AFTER} runs in a row that pass it, and a flake starts the count again`, () => { - let issue: Issue = { - number: 7, - title, - state: "open", - created_at: "2026-12-01T00:00:00Z", - assignees: [{ login: "someone" }], - body: renderBody({ - v: 1, - file: "app/tests/home.test.tsx", - owner: "someone", - review: "2026-12-18", - since: "2026-12-04", - streak: 0, - failures: 1, - runs: [1], - }), - }; - // Fifty clean runs, then a flake: the count starts again, and the issue stays open. - let id = 100; - for (let i = 0; i < 50; i++) { - issue = applied( - issue, - plan([issue], [runOf(id++, "quarantined-passed")], owners, now), - ); - } - expect(readState(issue.body)?.streak).toBe(50); - issue = applied(issue, plan([issue], [runOf(id++, "flaky")], owners, now)); - expect(readState(issue.body)).toMatchObject({ streak: 0, failures: 2 }); - expect(issue.state).toBe("open"); - // A run read twice counts once. - const again = plan([issue], [runOf(id - 1, "flaky")], owners, now); - expect(again).toEqual([]); - // Then RELEASE_AFTER clean runs in a row, read a few at a time: released. - for (let i = 0; i < RELEASE_AFTER - 1; i++) { - issue = applied( - issue, - plan([issue], [runOf(id++, "quarantined-passed")], owners, now), - ); - } - expect(issue.state).toBe("open"); - const last = plan( - [issue], - [runOf(id++, "quarantined-passed")], - owners, - now, - ); - issue = applied(issue, last); - expect(issue.state).toBe("closed"); - const release = last[0]; - expect(release?.kind === "update" && release.comment).toContain( - `Passed ${RELEASE_AFTER} runs in a row first time`, - ); - // Released, a pass counts for nothing; a flake sets it aside again. - expect( - plan([issue], [runOf(id++, "quarantined-passed")], owners, now), - ).toEqual([]); - const back = plan([issue], [runOf(id++, "flaky")], owners, now); - expect(back[0]).toMatchObject({ kind: "update", number: 7, state: "open" }); - // Reopened by hand after its release: set aside again, its count starting afresh. - const reopened: Issue = { ...issue, state: "open" }; - const counted = plan( - [reopened], - [runOf(id++, "quarantined-passed")], - owners, - now, - ); - expect(counted[0]).toMatchObject({ kind: "update", number: 7 }); - expect(counted[0]).not.toHaveProperty("state"); - expect(readState(applied(reopened, counted).body)?.streak).toBe(1); - }); - - test("an issue from before the watch is taken on only by a recorded fail-then-pass, and its review date asks its owner once", () => { - const old: Issue = { - number: 8, - title, - state: "open", - created_at: "2026-11-01T00:00:00Z", - body: "A test that failed and then passed on the same commit, with no change to the code.", - }; - // It set nothing aside, so a run never counts it as passed set aside: nothing to do. - expect(plan([old], [runOf(4, "quarantined-passed")], owners, now)).toEqual( - [], - ); - // A recorded fail-then-pass marks it: from then on it sets its test aside. - const taken = plan([old], [runOf(5, "flaky")], owners, now); - expect(taken[0]).toMatchObject({ kind: "update", assignees: ["someone"] }); - const body = taken[0]?.kind === "update" ? taken[0].body : ""; - expect(marked(old.body)).toBe(false); - expect(marked(body)).toBe(true); - expect(taken[0]?.kind === "update" && taken[0].comment).toContain( - "Set aside from now", - ); - const state = readState(body); - expect(state).toMatchObject({ - since: "2026-12-04", - streak: 0, - failures: 1, - owner: "someone", - }); - - const due: Issue = { - ...old, - body: renderBody({ ...(state ?? ({} as never)), review: "2026-12-03" }), - }; - const reminded = plan([due], [], owners, now); - expect(reminded[0]).toMatchObject({ kind: "update", number: 8 }); - expect(reminded[0]?.kind === "update" && reminded[0].comment).toContain( - "@someone, this test has been set aside since 2026-12-04", - ); - const after = applied(due, reminded); - expect(readState(after.body)?.review).toBe("2026-12-18"); - expect(plan([after], [], owners, now)).toEqual([]); - }); - - test("a file's owner is the last person to change it, not a bot", () => { - expect( - ownerOf([ - { author: { login: "renovate[bot]", type: "Bot" } }, - { author: null }, - { author: { login: "someone", type: "User" } }, - ]), - ).toBe("someone"); - expect( - ownerOf([{ author: { login: "github-actions[bot]", type: "Bot" } }]), - ).toBeNull(); - }); -}); diff --git a/scripts/flaky-tests.ts b/scripts/flaky-tests.ts deleted file mode 100644 index e4ac8a7cad..0000000000 --- a/scripts/flaky-tests.ts +++ /dev/null @@ -1,482 +0,0 @@ -#!/usr/bin/env bun -/** - * Flaky tests, set aside automatically, so a test that flakes never fails a pull request or ejects - * one from the merge queue. - * - * RETRY. CI runs every test once more when it fails (`bun test --retry=1`). A test that fails and - * then passes is flaky: the run passes, and the test is named as flaky in the job's notes. - * - * QUARANTINE. Each open `flaky-test` issue titled "Flaky test: " that the watch - * (scripts/flaky-tests-watch.ts) opened, reopened or took on from a recorded fail-then-pass, and so - * carries its state block, sets that test aside. Any other such issue sets nothing aside. A test - * set aside still runs in every job it ran in before, and its result is still recorded, but its - * failure does not fail the job: when every test that failed is set aside, and nothing else went - * wrong (a file that failed to load, an error between tests), the job passes. Anything else still - * fails, as before. This is how Trunk, Buildkite Test Engine ("mute"), Datadog and Airtable treat a - * test in quarantine: it runs, and its result does not count. - * - * NOTES. Each step this wraps leaves one GitHub notice titled "Flaky tests" on the run, one line a - * test: the flaky ones, and how each test set aside did. `scripts/flaky-tests-watch.ts` reads those - * notes after the run, opens or reopens the issue for a new flaky test (owner, review date), counts - * the runs a test set aside passes in a row, and closes its issue once it has passed enough of them. - * The job's summary lists every test set aside, so none is set aside unseen. - * - * bun scripts/flaky-tests.ts run [--root ] -- - * - * runs a `bun test` command (directly, or inside `docker run`) under these rules. `--root` is the - * folder bun ran in, from the repository's root, when it was not the root itself. The quarantine is - * read from GITHUB_REPOSITORY's issues with GH_TOKEN (issues: read); without them, or when the read - * fails, nothing is set aside and every failure counts. - */ -import { appendFileSync } from "node:fs"; - -export const LABEL = "flaky-test"; -export const TITLE_PREFIX = "Flaky test: "; -/** The title of the notice each wrapped step leaves (scripts/flaky-tests-watch.ts reads it). */ -export const NOTE_TITLE = "Flaky tests"; -/** The runs in a row a test set aside has to pass, first time, to be released. */ -export const RELEASE_AFTER = 60; -/** Days from setting a test aside to the date its owner is asked to look at it again. */ -export const REVIEW_DAYS = 14; - -/** - * A test's name as an issue title holds it: no mention pings anybody, no backtick ends a code span, - * and at most 180 characters (scripts/ci-watch.ts names its issues the same way). - */ -export function identity(name: string): string { - return name.replaceAll("@", "@​").replaceAll("`", "'").slice(0, 180); -} - -// --------------------------------------------------------------------------------------------- -// What bun said. - -export type BunStatus = "pass" | "fail" | "skip" | "todo"; -export type BunTest = { - file: string; - name: string; - status: BunStatus; - /** 1 on the first go; 2 when it took the retry. */ - attempt: number; -}; -export type BunRun = { - tests: BunTest[]; - /** Bun's closing counts: `N pass`, `N fail`, `N error`. Missing when bun never got that far. */ - counts: Partial>; -}; - -const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, "g"); -const FILE_HEADER = /^([^\s()][^\s]*\.[cm]?[jt]sx?):$/; -const RESULT = - /^\((pass|fail|skip|todo)\) (.+?)(?: \(attempt (\d+)\))?(?: \[[\d.]+m?s\])?$/; -const COUNT = /^(\d+) (pass|fail|skip|todo|errors?)$/; - -/** - * The tests bun's console reporter names, and its closing counts. Each file's results follow a line - * naming the file (on GitHub Actions, as a log group); `root` is put in front of those names, so a - * run inside desktop/ names desktop/src/... . Bun names a passing test only when it is not talking - * to a coding agent (CLAUDECODE, AI_AGENT or AGENT in its environment); CI has none of those. - */ -export function parseBunOutput(text: string, root = ""): BunRun { - const prefix = root ? `${root.replace(/\/+$/, "")}/` : ""; - const tests: BunTest[] = []; - const counts: BunRun["counts"] = {}; - let file = ""; - for (const raw of text.split("\n")) { - const line = raw - .replace(ANSI, "") - .replace(/^(::group::|##\[group\])/, "") - .trim(); - const header = FILE_HEADER.exec(line); - if (header?.[1]) { - file = `${prefix}${header[1].replace(/^\.\//, "")}`; - continue; - } - const result = RESULT.exec(line); - if (result) { - tests.push({ - file, - name: result[2] ?? "", - status: result[1] as BunStatus, - attempt: Number(result[3] ?? 1), - }); - continue; - } - const count = COUNT.exec(line); - if (count) { - const kind = count[2]?.startsWith("error") - ? "error" - : (count[2] as BunStatus); - counts[kind] = Number(count[1]); - } - } - return { tests, counts }; -} - -/** - * The environment for a child `bun test` whose output is read: without the variables that make bun - * leave passing tests out of its output for a coding agent, or a flaky test would go unseen. - */ -export function readableBunEnv( - env: Record = process.env, -): Record { - const copy = { ...env }; - for (const name of ["CLAUDECODE", "AI_AGENT", "AGENT", "REPL_ID"]) { - delete copy[name]; - } - return copy; -} - -// --------------------------------------------------------------------------------------------- -// The quarantine. - -export type QuarantineEntry = { number: number; url: string }; -export type Quarantine = { - /** By identity(test name). */ - tests: Map; - /** Why nothing could be read, when nothing could. */ - error?: string; -}; - -/** - * What marks an issue scripts/flaky-tests-watch.ts opened, reopened or took on from a recorded - * fail-then-pass: the state block it keeps in the body. Only such an issue sets its test aside. - */ -export const STATE_MARK = "flaky-test-state"; - -/** Whether an issue's body carries the watch's state block. */ -export function marked(body: string | null | undefined): boolean { - return (body ?? "").includes(`