From 43c9c94a730e0340bf1d3fe5a34c855523b343d1 Mon Sep 17 00:00:00 2001 From: David McKay Date: Fri, 4 Dec 2026 21:27:30 -0800 Subject: [PATCH] Flaky tests read the issues once a run, and the watch reads only its own run The backend's Flaky tests workflow spent the repository's token for the hour, scanning hours of runs, and held up a deploy. Here: - ci.yml's `changes` reads the open flaky-test issues once a run, in one request, and hands the list to every test job; the test jobs make no request and hold no token. Any API error, a rate limit included, sets nothing aside with a warning and never fails a step. - The watch reads only the run that woke it (the workflow_run event's): its jobs, and the notes of at most 12 test jobs, then the issues and the writes only when there are notes. At most 25 requests, it stops when the token's hour has under 300 left, and it never fails. Pull requests' runs skip it; one job-level concurrency group keeps runs from piling up. --- .../actions/flaky-tests-quarantine/action.yml | 24 +- .github/workflows/ci.yml | 41 +- .github/workflows/flaky-tests.yml | 48 +- .github/workflows/publish-release.yml | 2 +- .github/zizmor.yml | 6 +- scripts/flaky-tests-watch.ts | 496 ++++++++---------- scripts/flaky-tests.test.ts | 303 ++++++++++- scripts/flaky-tests.ts | 56 +- 8 files changed, 643 insertions(+), 333 deletions(-) diff --git a/.github/actions/flaky-tests-quarantine/action.yml b/.github/actions/flaky-tests-quarantine/action.yml index 404a9913cb..6686241e59 100644 --- a/.github/actions/flaky-tests-quarantine/action.yml +++ b/.github/actions/flaky-tests-quarantine/action.yml @@ -1,12 +1,18 @@ name: Flaky tests set aside description: >- - Reads the tests set aside (the open flaky-test issues scripts/flaky-tests-watch.ts marked) once, - with the job's token, and writes them to flaky-tests-quarantine.json in the runner's temporary - folder, where the job's test steps read them (scripts/flaky-tests.ts). The test steps hold no - token and never ask GitHub themselves, so neither does a test they run. A read that fails writes - why, sets nothing aside, and fails nothing. + Writes the tests set aside, as CI's `changes` job read them once for the whole run (the open + flaky-test issues scripts/flaky-tests-watch.ts marked), to flaky-tests-quarantine.json in the + runner's temporary folder, where the job's test steps read them (scripts/flaky-tests.ts). It asks + GitHub nothing: the test steps hold no token, and neither does a test they run. An empty or + missing list sets nothing aside. -# The caller checks the repository out and sets up Bun first, and grants `issues: read`. +# The caller checks the repository out first. + +inputs: + list: + description: The tests set aside, as JSON (`changes`'s `flaky_tests` output). + required: false + default: "" runs: using: composite @@ -14,5 +20,7 @@ runs: - name: The tests set aside shell: bash env: - GH_TOKEN: ${{ github.token }} - run: bun scripts/flaky-tests.ts quarantine "$RUNNER_TEMP/flaky-tests-quarantine.json" + LIST: ${{ inputs.list }} + run: | + if [ -n "$LIST" ]; then printf '%s\n' "$LIST"; else echo '{"tests":{}}'; fi \ + > "$RUNNER_TEMP/flaky-tests-quarantine.json" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e376fecffd..7f30eb97a6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -79,7 +79,11 @@ jobs: # To read which jobs passed on the commits this one sits on, and to cancel this run at its # first failure (.github/actions/stop-on-failure). actions: write + # To read the tests set aside (the open flaky-test issues), once for the whole run. + issues: read outputs: + # The tests set aside, as JSON, for every test job's flaky-tests-quarantine step. + flaky_tests: ${{ steps.flaky.outputs.list }} static: ${{ steps.decide.outputs.static }} api: ${{ steps.decide.outputs.api }} mobile: ${{ steps.decide.outputs.mobile }} @@ -131,6 +135,17 @@ jobs: # main's own run of the same push. WORKFLOW_NAME: ${{ github.workflow }} run: bun scripts/ci-changes.ts ci + # The tests set aside, read here once for the run with one request, and handed to each test + # job, whose steps hold no token (scripts/flaky-tests.ts). A read that fails, a rate limit + # included, sets nothing aside with a warning and never fails this job. + - id: flaky + name: The tests set aside + env: + GH_TOKEN: ${{ github.token }} + run: | + list="$RUNNER_TEMP/flaky-tests-quarantine.json" + bun scripts/flaky-tests.ts quarantine "$list" || echo '{"tests":{},"error":"the read did not finish"}' > "$list" + echo "list=$(cat "$list")" >> "$GITHUB_OUTPUT" # On a failure, cancels the run at once (.github/actions/stop-on-failure). - if: failure() uses: $/.github/actions/stop-on-failure @@ -447,8 +462,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: @@ -459,9 +472,11 @@ jobs: with: bun-version: 1.4.3 - run: bun install --frozen-lockfile - # The tests set aside, read once with the job's token; the test steps hold none - # (.github/actions/flaky-tests-quarantine). As in every job that runs tests. + # The tests set aside, as `changes` read them for the run, written where the test steps read + # them; they hold no token (.github/actions/flaky-tests-quarantine). As in every test job. - uses: $/.github/actions/flaky-tests-quarantine + with: + list: ${{ needs.changes.outputs.flaky_tests }} # The app's real-browser tests: a running step's words # under reduced motion, where onboarding's Back lands beside the Mac window's buttons, the name # step's orb drawn whole under the step dashes, onboarding's reels playing each scene on their @@ -717,8 +732,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' }} @@ -736,6 +749,8 @@ jobs: - run: bun install --frozen-lockfile - run: bun run generate:app-config - uses: $/.github/actions/flaky-tests-quarantine + with: + list: ${{ needs.changes.outputs.flaky_tests }} - run: | # One file per line, sorted: pull requests that each add a file then merge cleanly. files=( @@ -928,8 +943,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: @@ -943,6 +956,8 @@ jobs: - run: bun install --frozen-lockfile working-directory: desktop - uses: $/.github/actions/flaky-tests-quarantine + with: + list: ${{ needs.changes.outputs.flaky_tests }} # 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. @@ -992,8 +1007,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 @@ -1021,10 +1034,12 @@ jobs: # pinned by the desktop lockfile rather than the root one. - run: bun install --frozen-lockfile working-directory: desktop - # The tests set aside, read once with the job's token (.github/actions/flaky-tests-quarantine). + # The tests set aside, as `changes` read them for the run (.github/actions/flaky-tests-quarantine). # A `uses` step: the upstream upgrade runs this job's `run` steps without it, and the suite # below, which they run, holds no token. - uses: $/.github/actions/flaky-tests-quarantine + with: + list: ${{ needs.changes.outputs.flaky_tests }} # 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). @@ -1102,8 +1117,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: @@ -1118,6 +1131,8 @@ jobs: - run: bun install --frozen-lockfile working-directory: desktop - uses: $/.github/actions/flaky-tests-quarantine + with: + list: ${{ needs.changes.outputs.flaky_tests }} - name: Install Chromium if: needs.changes.outputs.browser_tests != '[]' || needs.changes.outputs.desktop_browser_tests != '[]' run: bunx playwright-core install --with-deps --no-shell chromium diff --git a/.github/workflows/flaky-tests.yml b/.github/workflows/flaky-tests.yml index 40e071b473..c96ad72343 100644 --- a/.github/workflows/flaky-tests.yml +++ b/.github/workflows/flaky-tests.yml @@ -1,18 +1,28 @@ name: Flaky tests -# Every 20 minutes: reads the "Flaky tests" notes CI's test steps left on the runs that finished since -# it last looked (scripts/flaky-tests.ts), and keeps one `flaky-test` issue per flaky test +# After each run of CI from the merge queue or on main: reads the "Flaky tests" notes that one run's +# 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. On a timer rather than after every run, and within a set number of requests: the -# repository's token is shared by every workflow. 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. +# its issue closed. +# +# It reads only the run that woke it, in at most 25 requests (two when the run left no note), and +# stops when the token's hour runs low: the repository's token is shared by every workflow. A rate +# limit or an API error is a warning; this never fails. Pull requests' runs are left to the queue's: +# a pull request's own change may be what fails, and the queue tests the same tests on main. +# 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: - schedule: - - cron: "*/20 * * * *" + workflow_run: + workflows: [CI] + types: [completed] workflow_dispatch: inputs: + run: + description: The id of a run to read. + required: true + type: string dry_run: description: Say what would change, and change nothing. type: boolean @@ -21,20 +31,19 @@ on: permissions: contents: read -# One at a time, so two never write one issue at once. -concurrency: - group: flaky-tests - cancel-in-progress: false - jobs: watch: name: flaky tests + # A run of the merge queue or of main, or one asked for by hand; a pull request's needs nothing. + if: github.event_name == 'workflow_dispatch' || github.event.workflow_run.event == 'merge_group' || github.event.workflow_run.event == 'push' runs-on: ubuntu-24.04 - timeout-minutes: 10 + timeout-minutes: 5 + # One at a time, so two never write one issue at once, and none piles up behind another. + concurrency: + group: flaky-tests + cancel-in-progress: false 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. @@ -43,6 +52,10 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + sparse-checkout: | + scripts/flaky-tests.ts + scripts/flaky-tests-watch.ts + sparse-checkout-cone-mode: false - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: bun-version: 1.4.3 @@ -50,12 +63,13 @@ jobs: - name: Flaky tests env: GH_TOKEN: ${{ github.token }} - WATCHED: CI # The jobs that run tests: only their notes are read. JOBS: ^(tests \(|app \(real browser) + RUN_ID: ${{ inputs.run }} DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} run: | - set -euo pipefail + set -uo pipefail args=() + if [ -n "$RUN_ID" ]; then args+=(--run "$RUN_ID"); fi 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..37f19b3858 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -404,7 +404,7 @@ 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, + # CI's `changes` asks for it, to read the tests set aside (open flaky-test issues, # scripts/flaky-tests.ts). issues: read diff --git a/.github/zizmor.yml b/.github/zizmor.yml index f19aa05cf1..23e191d56e 100644 --- a/.github/zizmor.yml +++ b/.github/zizmor.yml @@ -20,8 +20,12 @@ 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. + # code, downloads no artifact, and acts on runs through the API alone. Flaky tests needs it to read + # the notes one finished run of the merge queue or main left. It checks out only two scripts from + # the default branch, never the run's code, downloads no artifact, runs nothing from the run, and + # leaves runs from forks and pull requests alone (scripts/flaky-tests-watch.ts). dangerous-triggers: ignore: - ci-watch.yml - contributor-ci.yml + - flaky-tests.yml diff --git a/scripts/flaky-tests-watch.ts b/scripts/flaky-tests-watch.ts index 5db557d88e..32f691f61a 100644 --- a/scripts/flaky-tests-watch.ts +++ b/scripts/flaky-tests-watch.ts @@ -6,8 +6,8 @@ * 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: + * It reads the "Flaky tests" notices the test steps left on the ONE run that just finished (the + * workflow_run event's), 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 @@ -20,17 +20,17 @@ * 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 on a timer, one at a time, and reads from where the last one that - * finished left off. It never makes more than MAX_REQUESTS requests to GitHub: the repository's - * token is shared by every workflow, and a first sweep that read every job of every run used - * thousands. Past that it keeps the newest runs and says how many older ones it left unread. + * nothing. The repository's token is shared by every workflow (a sweep that scanned hours of runs + * spent it and held up a deploy on 5 December), so one watch reads only its own run, makes at most + * MAX_REQUESTS requests, stops when the token's hour runs low (LEAVE_FOR_OTHERS), and never fails: + * a rate limit or an API error is a warning, and the watch ends green. * - * Runs from forks are left alone. Env: GITHUB_REPOSITORY, GH_TOKEN (actions: read, checks: read, - * issues: write), WATCHED (the workflows' names, comma-separated), JOBS (a regular expression for - * the names of the jobs that run tests, whose notes are read; unset, every job's). `--dry-run` says - * what it would do and does nothing. + * Runs from forks are left alone. Env: GITHUB_REPOSITORY, GITHUB_EVENT_PATH (a workflow_run event), + * GH_TOKEN (checks: read, issues: write), JOBS (a regular expression for the names of the jobs + * that run tests, whose notes are read; unset, every job's). `--run ` reads that run instead of + * the event's; `--dry-run` says what it would do and does nothing. */ -import { appendFileSync } from "node:fs"; +import { appendFileSync, readFileSync } from "node:fs"; import { LABEL, NOTE_TITLE, @@ -362,221 +362,150 @@ export function plan( // --------------------------------------------------------------------------------------------- -/** The most requests one sweep makes to GitHub (a `--paginate` call counts once a page it may read). */ -export const MAX_REQUESTS = 400; -/** Kept back from reading notes, for the issues, the owners and the writes. */ -const KEPT_FOR_ISSUES = 80; -let requests = 0; +/** The most requests one watch of one run makes to GitHub, whatever the run. */ +export const MAX_REQUESTS = 25; +/** The most jobs of one run whose notes are read, and the most owners looked up. */ +const MAX_JOBS = 12; +const MAX_OWNERS = 3; +/** + * When the token's hour has fewer requests left than this, the watch stops and says so: the + * repository's token is shared by every workflow, and a deploy needs it more than this does. + */ +export const LEAVE_FOR_OTHERS = 300; -function gh(args: string[], input?: string): string { - requests += args.includes("--paginate") ? 2 : 1; - 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()}`, - ); +/** Thrown when a watch has made all the requests it may. */ +class Spent extends Error {} + +/** GitHub's REST API, counted: never more than MAX_REQUESTS requests, nor below LEAVE_FOR_OTHERS. */ +export class GitHub { + requests = 0; + constructor( + private readonly api: string, + private readonly token: string, + ) {} + + async call(method: string, path: string, body?: unknown): Promise { + if (this.requests >= MAX_REQUESTS) { + throw new Spent(`it made the ${MAX_REQUESTS} requests one watch may`); + } + this.requests += 1; + const response = await fetch(`${this.api}/${path}`, { + method, + headers: { + Authorization: `Bearer ${this.token}`, + Accept: "application/vnd.github+json", + ...(body === undefined ? {} : { "Content-Type": "application/json" }), + }, + body: body === undefined ? undefined : JSON.stringify(body), + signal: AbortSignal.timeout(15_000), + }); + const remaining = Number(response.headers.get("x-ratelimit-remaining")); + if (!response.ok) { + throw new Error( + `${method} ${path}: HTTP ${response.status}${remaining === 0 ? " (rate limit)" : ""}`, + ); + } + const result = (await response.json()) as T; + if (Number.isFinite(remaining) && remaining < LEAVE_FOR_OTHERS) { + throw new Spent( + `the token has ${remaining} requests left this hour, kept for other workflows`, + ); + } + return result; } - return result.stdout.toString(); } -const json = (args: string[]): T => JSON.parse(gh(args)) as T; - -type ApiRun = { +/** The run that finished, as the workflow_run event names it. */ +export type FinishedRun = { id: number; - name: string; html_url: string; check_suite_id: number; - created_at: string; - updated_at: string; - status: string; + event: string; head_repository?: { full_name: string } | null; }; /** - * The runs of the watched workflows that finished since `since`, oldest first, none from forks. - * Asked workflow by workflow, so the runs of every other workflow (this one's, CI watch's) are - * never paged through. + * What one finished run's "Flaky tests" notices said: the run's jobs (one or two requests), then + * the notes of at most MAX_JOBS of the jobs `jobs` names that carry an annotation (one request + * each). Nothing else is read. */ -function finishedRuns( +export async function notesOf( + github: GitHub, repository: string, - watched: string[], - since: Date, -): ApiRun[] { - const workflows = json<{ workflows: { id: number; name: string }[] }>([ - `repos/${repository}/actions/workflows?per_page=100`, - ]).workflows.filter((workflow) => watched.includes(workflow.name)); - // 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 (const workflow of workflows) { - for (let page = 1; page <= 10; page++) { - const batch = json<{ workflow_runs: ApiRun[] }>([ - `repos/${repository}/actions/workflows/${workflow.id}/runs?status=completed&created=%3E%3D${encodeURIComponent(created)}&per_page=100&page=${page}`, - ]).workflow_runs; - runs.push(...batch); - if (batch.length < 100) break; + run: FinishedRun, + jobs: RegExp, +): Promise { + type Check = { + id: number; + name: string; + output: { annotations_count: number }; + }; + const checks: Check[] = []; + for (let page = 1; page <= 2; page++) { + const listed = await github.call<{ + total_count: number; + check_runs: Check[]; + }>( + "GET", + `repos/${repository}/check-suites/${run.check_suite_id}/check-runs?filter=latest&per_page=100&page=${page}`, + ); + checks.push(...listed.check_runs); + if (checks.length >= listed.total_count || !listed.check_runs.length) { + break; } } - return runs + const read = checks .filter( - (run) => - Date.parse(run.updated_at) >= since.getTime() && - (!run.head_repository || run.head_repository.full_name === repository), + (check) => check.output.annotations_count > 0 && jobs.test(check.name), ) - .sort((a, b) => Date.parse(a.updated_at) - Date.parse(b.updated_at)); -} - -/** GET from GitHub's API, with GH_TOKEN, or `gh`'s own when run by hand. */ -async function apiGet(path: string): Promise { - requests += 1; - const token = - process.env.GH_TOKEN || - Bun.spawnSync(["gh", "auth", "token"]).stdout.toString().trim(); - const api = (process.env.GITHUB_API_URL || "https://api.github.com").replace( - /\/+$/, - "", - ); - const response = await fetch(`${api}/${path}`, { - headers: { - Authorization: `Bearer ${token}`, - Accept: "application/vnd.github+json", - }, - signal: AbortSignal.timeout(30_000), - }); - if (!response.ok) throw new Error(`GET ${path}: HTTP ${response.status}`); - return (await response.json()) as T; -} - -/** Calls `work` on every item, `width` at a time. */ -async function inTurns( - items: T[], - width: number, - work: (item: T) => Promise, -): Promise { - const results: R[] = new Array(items.length); - let next = 0; - await Promise.all( - Array.from({ length: Math.min(width, items.length) }, async () => { - while (next < items.length) { - const index = next++; - results[index] = await work(items[index] as T); - } - }), - ); - return results; -} - -/** - * What a run's "Flaky tests" notices said. Only the jobs whose name `jobs` matches are read (the - * jobs that run tests): every job of a run can carry an annotation of its own (a deprecation - * warning, a failure), and reading each one's took longer than the workflow has. - */ -async function notesOf( - repository: string, - run: ApiRun, - jobs: RegExp, -): Promise { - const checks = json< - { - check_runs: { - id: number; - name: string; - 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 read = checks.filter( - (check) => check.output.annotations_count > 0 && jobs.test(check.name), - ); - const annotations = await inTurns(read, 8, (check) => - apiGet<{ title: string | null; message: string }[]>( - `repos/${repository}/check-runs/${check.id}/annotations?per_page=100`, - ), - ); - return annotations - .flat() - .filter((annotation) => annotation.title === NOTE_TITLE) - .flatMap((annotation) => parseNote(annotation.message)); -} - -/** 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 (dispatched by hand) changed nothing, so only a run on the timer counts. Before this - // workflow's first run on the default branch there is none, and GitHub does not know it 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=schedule&per_page=5`, - ]).workflow_runs.filter( - (run) => - String(run.id) !== process.env.GITHUB_RUN_ID && - run.event === "schedule", + .slice(0, MAX_JOBS); + const observations: Observation[] = []; + for (const check of read) { + const annotations = await github.call< + { title: string | null; message: string }[] + >( + "GET", + `repos/${repository}/check-runs/${check.id}/annotations?per_page=50`, ); - } catch { - return fallback; + for (const annotation of annotations) { + if (annotation.title === NOTE_TITLE) { + observations.push(...parseNote(annotation.message)); + } + } } - 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; + return observations; } -function apply(repository: string, action: Action): string { +async function apply( + github: GitHub, + repository: string, + action: Action, +): Promise { 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", + const created = await github.call<{ number: number }>( "POST", - ...fields, - ]); + `repos/${repository}/issues`, + { + title: action.title, + body: action.body, + labels: [LABEL], + assignees: action.assignees, + }, + ); 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, - ]); + await github.call("PATCH", `repos/${repository}/issues/${action.number}`, { + body: action.body, + ...(action.state ? { state: action.state } : {}), + ...(action.state === "closed" ? { state_reason: "completed" } : {}), + ...(action.assignees?.length ? { assignees: action.assignees } : {}), + }); if (action.comment) { - gh([ - `repos/${repository}/issues/${action.number}/comments`, - "--method", + await github.call( "POST", - "-f", - `body=${action.comment}`, - ]); + `repos/${repository}/issues/${action.number}/comments`, + { body: action.comment }, + ); } const did = action.state === "closed" @@ -587,85 +516,118 @@ function apply(repository: string, action: Action): string { 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); +/** + * Watches one finished run: reads its notes, and when it has any, the flaky-test issues (one + * request), the owners of new tests' files (at most MAX_OWNERS), and writes what plan() says. + * Within MAX_REQUESTS in all. Returns what it did, a line each. + */ +export async function watchRun( + github: GitHub, + repository: string, + run: FinishedRun, + options: { jobs: RegExp; dryRun: boolean; now: Date }, +): Promise { + if (run.head_repository && run.head_repository.full_name !== repository) { + return ["A run from a fork: left alone."]; } - // The jobs that run tests, by name (JOBS, a regular expression); unset, every job. - const jobs = new RegExp(process.env.JOBS || "."); - const since = lastLooked(repository, "flaky-tests.yml"); - const finished = finishedRuns(repository, watched, since); - // Newest first, within the sweep's requests; then oldest first, as plan() counts them. - const runs: RunNotes[] = []; - let unread = 0; - for (const run of [...finished].reverse()) { - if (requests >= MAX_REQUESTS - KEPT_FOR_ISSUES) { - unread += 1; - continue; - } - runs.unshift({ - id: run.id, - url: run.html_url, - observations: await notesOf(repository, run, jobs), - }); + const observations = await notesOf(github, repository, run, options.jobs); + if (!observations.length) { + return [`[Run ${run.id}](${run.html_url}) left no note on a flaky test.`]; } - 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 said = [ + `[Run ${run.id}](${run.html_url}) left ${observations.length} note(s).`, + ]; + const issues = ( + await github.call<(Issue & { pull_request?: unknown })[]>( + "GET", + `repos/${repository}/issues?labels=${LABEL}&state=all&sort=updated&direction=desc&per_page=100`, + ) + ).filter((issue) => !issue.pull_request); + const known = new Set(issues.map((issue) => issue.title)); 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`, - ]), + const unowned = [ + ...new Set( + observations + .filter((o) => o.file && !known.has(`${TITLE_PREFIX}${o.name}`)) + .map((o) => o.file), + ), + ]; + for (const file of unowned.slice(0, MAX_OWNERS)) { + owners.set( + file, + ownerOf( + await github.call( + "GET", + `repos/${repository}/commits?path=${encodeURIComponent(file)}&per_page=10`, ), - ); - } catch { - owners.set(file, null); - } + ), + ); } - const actions = plan(issues, runs, owners, new Date()); - const said: string[] = [ - `### Flaky tests: read ${runs.length} run(s) that finished since ${since.toISOString()}`, - ]; - if (unread) { + const actions = plan( + issues, + [{ id: run.id, url: run.html_url, observations }], + owners, + options.now, + ); + for (const action of actions) { said.push( - `- ${unread} older run(s) left unread: the sweep keeps to ${MAX_REQUESTS} requests to GitHub.`, + options.dryRun + ? `would ${action.kind === "open" ? "open" : `change #${action.number}`}: ${action.title}` + : await apply(github, repository, action), ); } - 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) { + if (!actions.length) said.push("No issue to change."); + return said; +} + +if (import.meta.main) { + const dryRun = process.argv.includes("--dry-run"); + const repository = process.env.GITHUB_REPOSITORY ?? ""; + const said: string[] = []; + let github: GitHub | undefined; + try { + const token = + process.env.GH_TOKEN || + Bun.spawnSync(["gh", "auth", "token"]).stdout.toString().trim(); + github = new GitHub( + (process.env.GITHUB_API_URL || "https://api.github.com").replace( + /\/+$/, + "", + ), + token, + ); + // The jobs that run tests, by name (JOBS, a regular expression); unset, every job. + const jobs = new RegExp(process.env.JOBS || "."); + const runArgument = process.argv.indexOf("--run"); + const run: FinishedRun = + runArgument > 0 + ? await github.call( + "GET", + `repos/${repository}/actions/runs/${process.argv[runArgument + 1]}`, + ) + : ( + JSON.parse( + readFileSync(process.env.GITHUB_EVENT_PATH ?? "", "utf8"), + ) as { workflow_run: FinishedRun } + ).workflow_run; said.push( - `- ${dryRun ? `would ${action.kind === "open" ? "open" : `change #${action.number}`}: ${action.title}` : apply(repository, action)}`, + ...(await watchRun(github, repository, run, { + jobs, + dryRun, + now: new Date(), + })), ); + } catch (error) { + // Never fails: a rate limit, an API error or a spent budget is said, and the run stays green. + const message = (error as Error).message; + said.push(`Stopped: ${message}.`); + console.log(`::warning title=Flaky tests watch::Stopped: ${message}.`); } - if (!actions.length) said.push("- No issue to change."); - said.push(`- ${requests} request(s) to GitHub.`); - console.log(said.join("\n")); + said.push(`${github?.requests ?? 0} request(s) to GitHub.`); + const text = `### Flaky tests\n\n${said.map((line) => `- ${line}`).join("\n")}\n`; + console.log(text); if (process.env.GITHUB_STEP_SUMMARY) { - appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${said.join("\n")}\n`); + appendFileSync(process.env.GITHUB_STEP_SUMMARY, text); } + process.exit(0); } diff --git a/scripts/flaky-tests.test.ts b/scripts/flaky-tests.test.ts index 2612ef7c3d..5f2b9f9c94 100644 --- a/scripts/flaky-tests.test.ts +++ b/scripts/flaky-tests.test.ts @@ -11,12 +11,16 @@ import { readableBunEnv, } from "./flaky-tests"; import { + GitHub, type Issue, + LEAVE_FOR_OTHERS, + MAX_REQUESTS, ownerOf, plan, type RunNotes, readState, renderBody, + watchRun, } from "./flaky-tests-watch"; /** @@ -58,12 +62,35 @@ let server: ReturnType; let summaryDir: string; /** Every request the fake GitHub was sent. */ let requests = 0; +/** When set, the fake answers as GitHub does once the token's hour is spent. */ +let rateLimited = false; beforeAll(() => { server = Bun.serve({ port: 0, fetch(request) { requests += 1; + if (rateLimited) { + // GitHub's answer to a token past its primary rate limit. + return Response.json( + { + message: + "API rate limit exceeded for installation. If you reach out to GitHub Support for help, please include the request ID.", + documentation_url: + "https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting", + status: "403", + }, + { + status: 403, + headers: { + "x-ratelimit-limit": "1000", + "x-ratelimit-remaining": "0", + "x-ratelimit-used": "1000", + "x-ratelimit-resource": "core", + }, + }, + ); + } const url = new URL(request.url); if ( url.pathname !== `/repos/${REPOSITORY}/issues` || @@ -322,9 +349,11 @@ describe("the token stays out of the test steps", () => { jobs: Record< string, { + needs?: string | string[]; steps?: { uses?: string; run?: string; + with?: Record; env?: Record; }[]; } @@ -334,6 +363,14 @@ describe("the token stays out of the test steps", () => { const jobs = Object.entries(workflow.jobs).filter(([, job]) => (job.steps ?? []).some((step) => runsTests.test(step.run ?? "")), ); + // Regression, 5 December: each test job read the issues itself, a request a job, and with the + // watch the repository's token ran out. `changes` reads them once a run, for every job. + const reads = Object.entries(workflow.jobs).filter(([, job]) => + (job.steps ?? []).some((step) => + /flaky-tests\.ts quarantine/.test(step.run ?? ""), + ), + ); + expect(reads.map(([id]) => id)).toEqual(["changes"]); expect(jobs.map(([id]) => id).sort()).toEqual([ "app-browser", "app-browser-desktop", @@ -347,9 +384,16 @@ describe("the token stays out of the test steps", () => { (step) => step.uses === "$/.github/actions/flaky-tests-quarantine", ); const first = steps.findIndex((step) => runsTests.test(step.run ?? "")); - expect({ id, listFirst: list >= 0 && list < first }).toEqual({ + expect({ + id, + listFirst: list >= 0 && list < first, + from: steps[list]?.with?.list, + needs: [job.needs ?? []].flat().includes("changes"), + }).toEqual({ id, listFirst: true, + from: `${"$"}{{ needs.changes.outputs.flaky_tests }}`, + needs: true, }); for (const step of steps) { if (!runsTests.test(step.run ?? "")) continue; @@ -362,20 +406,34 @@ describe("the token stays out of the test steps", () => { }); }); -test("the watch reads the notes of every job that runs tests, and of no other", () => { +test("the watch reads the notes of every job that runs tests, and of no other, after a queue or main run, one at a time", () => { // Reading every job's annotations took the backend's first sweep past its time; the watch reads // only the jobs JOBS names, so it must name each one a note can come from. const watch = Bun.YAML.parse( readFileSync(join(ROOT, ".github/workflows/flaky-tests.yml"), "utf8"), ) as { on: Record; - jobs: { watch: { steps: { env?: Record }[] } }; + jobs: { + watch: { + if: string; + concurrency: { group: string; "cancel-in-progress": boolean }; + steps: { env?: Record }[]; + }; + }; }; - // On a timer, not after every run: one sweep per run used the token's requests over and over. + // Woken by one finished run, which is all it reads; never a scan of past runs on a timer. expect(Object.keys(watch.on).sort()).toEqual([ - "schedule", "workflow_dispatch", + "workflow_run", ]); + expect(watch.jobs.watch.if).not.toContain("pull_request"); + expect(watch.jobs.watch.if).toContain( + "github.event.workflow_run.event == 'merge_group'", + ); + expect(watch.jobs.watch.concurrency).toEqual({ + group: "flaky-tests", + "cancel-in-progress": false, + }); const pattern = watch.jobs.watch.steps.find((step) => step.env?.JOBS)?.env ?.JOBS; expect(pattern).toBeDefined(); @@ -393,6 +451,241 @@ test("the watch reads the notes of every job that runs tests, and of no other", } }); +describe("the repository's token is shared: a rate limit never fails CI", () => { + test("a read of the tests set aside that GitHub refuses for its rate limit sets nothing aside, warns, and the step passes", async () => { + // Regression, 5 December: the token's hour ran out and held up a deploy. The read must cost one + // request, and a refusal must cost the test steps nothing. + openIssues = [watched(101, "a flaky group > passes every time")]; + rateLimited = true; + try { + const list = join(summaryDir, `${crypto.randomUUID()}.json`); + const before = requests; + const read = Bun.spawn( + ["bun", "scripts/flaky-tests.ts", "quarantine", list], + { + cwd: ROOT, + env: childEnv({ + GITHUB_REPOSITORY: REPOSITORY, + GH_TOKEN: "test-token", + }), + stdout: "pipe", + stderr: "pipe", + }, + ); + const said = await new Response(read.stdout).text(); + expect(await read.exited).toBe(0); + expect(requests - before).toBe(1); + expect(said).toContain("::warning title=Tests set aside::"); + expect(said).toContain("HTTP 403 (rate limit)"); + expect(JSON.parse(readFileSync(list, "utf8"))).toEqual({ + tests: {}, + error: "GitHub answered HTTP 403 (rate limit)", + }); + // The test step, with that list: nothing set aside, and a run that passes still passes. + const run = await wrapped(["flaky.fixture.ts"], false); + expect(run.exitCode).toBe(0); + } finally { + rateLimited = false; + } + }, 60_000); +}); + +describe("the watch of one finished run makes a bounded number of requests", () => { + /** A fake GitHub for one run of CI: its jobs, their notes, the issues, and every write. */ + const FAKE_REPOSITORY = "CopilotKit/OpenBot"; + let fake: ReturnType; + let calls: string[] = []; + let jobs = 0; + let notes = 0; + let warnings = false; + let remaining = 4000; + + beforeAll(() => { + fake = Bun.serve({ + port: 0, + async fetch(request) { + const url = new URL(request.url); + calls.push(`${request.method} ${url.pathname}`); + const headers = { "x-ratelimit-remaining": String(remaining) }; + if (remaining === 0) { + return Response.json( + { message: "API rate limit exceeded for installation." }, + { status: 403, headers }, + ); + } + const path = url.pathname.replace(`/repos/${FAKE_REPOSITORY}`, ""); + if (path === "/check-suites/7/check-runs") { + // The check runs API's shape: a page of a run's jobs, a hundred at most. + const page = Number(url.searchParams.get("page") ?? 1); + // Every third job runs tests; each job that ran a test set aside carries the note, and + // when `warnings`, every job carries a warning of its own as well. + const all = Array.from({ length: jobs }, (_, index) => ({ + id: 1000 + index, + name: + index % 3 === 0 + ? `tests (shard ${index} of ${jobs})` + : `component dockerfile (agent-${index})`, + output: { + annotations_count: + (index % 3 === 0 && index < notes * 3 ? 1 : 0) + + (warnings ? 1 : 0), + }, + })); + return Response.json( + { + total_count: all.length, + check_runs: all.slice((page - 1) * 100, page * 100), + }, + { headers }, + ); + } + const annotations = /^\/check-runs\/(\d+)\/annotations$/.exec(path); + if (annotations) { + const id = Number(annotations[1]); + return Response.json( + [ + { + title: "Node.js 20 is deprecated", + annotation_level: "warning", + message: "…", + }, + ...(id - 1000 < notes * 3 + ? [ + { + title: "Flaky tests", + annotation_level: "notice", + message: `Set aside, passed: test ${id} (in app/tests/t${id}.test.tsx)`, + }, + ] + : []), + ], + { headers }, + ); + } + if (path === "/issues" && request.method === "GET") { + return Response.json( + Array.from({ length: notes }, (_, index) => ({ + number: 10 + index, + title: `Flaky test: test ${1000 + index * 3}`, + state: "open", + created_at: "2026-12-01T00:00:00Z", + body: renderBody({ + v: 1, + review: "2026-12-30", + since: "2026-12-01", + streak: 1, + failures: 1, + runs: [1], + }), + })), + { headers }, + ); + } + if (/^\/issues\/\d+(\/comments)?$/.test(path)) { + return Response.json({ number: 1 }, { headers }); + } + return Response.json( + { message: "Not Found" }, + { status: 404, headers }, + ); + }, + }); + }); + afterAll(() => fake.stop(true)); + + const run = { + id: 5, + html_url: "https://github.com/CopilotKit/OpenBot/actions/runs/5", + check_suite_id: 7, + event: "merge_group", + }; + const watch = async () => { + calls = []; + const github = new GitHub(`http://127.0.0.1:${fake.port}`, "t"); + const said = await watchRun(github, FAKE_REPOSITORY, run, { + jobs: /^tests \(/, + dryRun: false, + now: new Date("2026-12-05T00:00:00Z"), + }).catch((error: Error) => [`Stopped: ${error.message}`]); + return { github, said }; + }; + + test("a run that left no note costs one request", async () => { + jobs = 45; + notes = 0; + warnings = false; + const { github, said } = await watch(); + // The jobs' list, and nothing else: no job that runs tests carries an annotation. + expect(calls).toEqual([ + "GET /repos/CopilotKit/OpenBot/check-suites/7/check-runs", + ]); + expect(github.requests).toBe(1); + expect(said.join("\n")).toContain("left no note"); + }); + + test(`a run of 150 jobs, every one annotated and every test job with notes, stays within ${MAX_REQUESTS} requests`, async () => { + jobs = 150; + notes = 50; + warnings = true; + const { github, said } = await watch(); + expect(calls.length).toBe(github.requests); + expect(calls.length).toBeLessThanOrEqual(MAX_REQUESTS); + // Two pages of jobs, at most 12 jobs' notes, the issues once, and then the writes until the + // budget is spent, which ends the watch with a warning rather than more requests. + expect(calls.filter((call) => call.endsWith("/check-runs")).length).toBe(2); + expect( + calls.filter((call) => call.endsWith("/annotations")).length, + ).toBeLessThanOrEqual(12); + expect( + calls.filter((call) => call === "GET /repos/CopilotKit/OpenBot/issues"), + ).toHaveLength(1); + expect(said.join("\n")).toContain( + `the ${MAX_REQUESTS} requests one watch may`, + ); + }); + + test(`a token with fewer than ${LEAVE_FOR_OTHERS} requests left this hour stops the watch at its first`, async () => { + jobs = 45; + notes = 5; + remaining = LEAVE_FOR_OTHERS - 1; + try { + const { said } = await watch(); + expect(calls).toHaveLength(1); + expect(said.join("\n")).toContain("kept for other workflows"); + } finally { + remaining = 4000; + } + }); + + test("the watch never fails: a rate limit is a warning, and it exits 0", async () => { + const dir = mkdtempSync(join(tmpdir(), "flaky-watch-")); + const event = join(dir, "event.json"); + await Bun.write(event, JSON.stringify({ workflow_run: run })); + remaining = 0; + try { + const proc = Bun.spawn(["bun", "scripts/flaky-tests-watch.ts"], { + cwd: ROOT, + env: { + ...childEnv(), + GITHUB_API_URL: `http://127.0.0.1:${fake.port}`, + GITHUB_REPOSITORY: FAKE_REPOSITORY, + GITHUB_EVENT_PATH: event, + GH_TOKEN: "t", + JOBS: "^tests \\(", + }, + stdout: "pipe", + stderr: "pipe", + }); + const said = await new Response(proc.stdout).text(); + expect(await proc.exited).toBe(0); + expect(said).toContain("::warning title=Flaky tests watch::Stopped:"); + } finally { + remaining = 4000; + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + 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( diff --git a/scripts/flaky-tests.ts b/scripts/flaky-tests.ts index 033156e4a1..2698f35093 100644 --- a/scripts/flaky-tests.ts +++ b/scripts/flaky-tests.ts @@ -23,11 +23,12 @@ * * bun scripts/flaky-tests.ts quarantine * - * reads the tests set aside from GITHUB_REPOSITORY's issues with GH_TOKEN (issues: read) and writes - * them to . Each test job does that once, first, in a step of its own - * (.github/actions/flaky-tests-quarantine), to flaky-tests-quarantine.json in the runner's temporary - * folder, where the test steps read it (FLAKY_TESTS_QUARANTINE names another file). When the read - * fails, the file says why, nothing is set aside, and every failure counts. + * reads the tests set aside from GITHUB_REPOSITORY's issues with GH_TOKEN (issues: read), in one + * request, and writes them to . CI does that once a run, in ci.yml's `changes`, and hands the + * list to each test job, whose flaky-tests-quarantine step (.github/actions/flaky-tests-quarantine) + * writes it to flaky-tests-quarantine.json in the runner's temporary folder, where the test steps + * read it (FLAKY_TESTS_QUARANTINE names another file). When the read fails, a rate limit included, + * the file says why, nothing is set aside, every failure counts, and the step still passes. * * bun scripts/flaky-tests.ts run [--root ] -- * @@ -225,10 +226,12 @@ export function readQuarantine( /** * The open `flaky-test` issues named "Flaky test: " that the watch opened, reopened or took - * on (marked()), every page of them, read from GitHub with GH_TOKEN (issues: read). An issue without - * the mark (ci-watch.ts's, or one from before the watch) sets nothing aside until a run records its - * test failing and then passing. A failure to read them is said, not thrown: CI then sets nothing - * aside, and every failure counts. + * on (marked()), read from GitHub with GH_TOKEN (issues: read) in ONE request: the first hundred, + * newest first. CI makes it once a run (ci.yml's `changes`), so a run costs one request however + * many jobs it has. An issue without the mark (ci-watch.ts's, or one from before the watch) sets + * nothing aside until a run records its test failing and then passing. Any failure to read them (a + * rate limit, an error, no answer within 10 seconds) is said, never thrown: nothing is set aside, + * and every failure counts. */ export async function fetchQuarantine( env: Record = process.env, @@ -247,21 +250,21 @@ export async function fetchQuarantine( }; } try { - for (let page = 1; page <= 10; page++) { + { const response = await fetch( - `${api}/repos/${repository}/issues?labels=${LABEL}&state=open&per_page=100&page=${page}`, + `${api}/repos/${repository}/issues?labels=${LABEL}&state=open&per_page=100`, { headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json", }, - signal: AbortSignal.timeout(20_000), + signal: AbortSignal.timeout(10_000), }, ); if (!response.ok) { return { tests: new Map(), - error: `GitHub answered HTTP ${response.status}`, + error: `GitHub answered HTTP ${response.status}${response.headers.get("x-ratelimit-remaining") === "0" ? " (rate limit)" : ""}`, }; } const issues = (await response.json()) as IssueListing[]; @@ -280,7 +283,6 @@ export async function fetchQuarantine( tests.set(name, { number: issue.number, url: issue.html_url }); } } - if (issues.length < 100) break; } } catch (error) { return { tests: new Map(), error: (error as Error).message }; @@ -535,19 +537,31 @@ export async function writeQuarantine( tests: Object.fromEntries(quarantine.tests), ...(quarantine.error ? { error: quarantine.error } : {}), }; - writeFileSync(path, `${JSON.stringify(file, null, 2)}\n`); + // One line: CI hands it on as a job output. + writeFileSync(path, `${JSON.stringify(file)}\n`); return quarantine; } if (import.meta.main) { const args = process.argv.slice(2); if (args[0] === "quarantine" && args[1]) { - const quarantine = await writeQuarantine(args[1]); - console.log( - quarantine.error - ? `Flaky tests: could not read the tests set aside (${quarantine.error}); every failure counts.` - : `Flaky tests: ${quarantine.tests.size} set aside (open ${LABEL} issues the watch marked).`, - ); + // Never fails its step: a list that cannot be read sets nothing aside, with a warning. + try { + const quarantine = await writeQuarantine(args[1]); + console.log( + quarantine.error + ? `::warning title=Tests set aside::Could not read the tests set aside (${quarantine.error}); nothing is set aside in this run, and every failure counts.` + : `Flaky tests: ${quarantine.tests.size} set aside (open ${LABEL} issues the watch marked).`, + ); + } catch (error) { + writeFileSync( + args[1], + `${JSON.stringify({ tests: {}, error: (error as Error).message })}\n`, + ); + console.log( + `::warning title=Tests set aside::Could not read the tests set aside (${(error as Error).message}); nothing is set aside in this run.`, + ); + } process.exit(0); } const split = args.indexOf("--");