Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
ci: quarantine known flaky jobs in ci-gate and scan reruns nightly (CUA-3134) (#6372)
cua-agents[bot]3cad7878d7db
diff --git a/.github/flaky/quarantine.json b/.github/flaky/quarantine.jsonindex 03f87f3190..7bd305ccc7 100644--- a/.github/flaky/quarantine.json+++ b/.github/flaky/quarantine.json@@ -1,4 +1,21 @@{- "$comment": "Known-flaky tests that may fail without blocking CI. Add an entry only with an owner, an issue and an expiry date. CI fails when an entry expires (ci-flaky-quarantine). See .github/scripts/flaky/flaky.py.",- "entries": []+ "$comment": "Known flakes that may fail without blocking CI. A `test` entry is matched inside a job by .github/scripts/flaky/flaky.py run. A `job` entry is matched by ci-gate: the job is rerun once, and if it fails again with `signature` in its log it is reported and does not fail the gate. Every entry needs an owner, an issue and an expiry date (at most 90 days; 7 days for a new flake). CI fails when an entry expires (ci-flaky-quarantine). See .github/workflows/FLAKY.md.",+ "entries": [+ {+ "job": "linux-kvm (concurrent)",+ "workflow": "Nightly: VM Space ready after boot",+ "signature": "registry: Not authorized: .*ghcr\\.io/v2/trycua/|cua-spacesd is not available in sandbox .*nothing answered at",+ "owner": "f-trycua",+ "issue": "CUA-3132",+ "expires": "2026-11-10"+ },+ {+ "job": "macOS * mock E2E",+ "workflow": "CI: jev-use",+ "signature": "database is locked",+ "owner": "f-trycua",+ "issue": "CUA-3133",+ "expires": "2026-11-10"+ }+ ]}diff --git a/.github/scripts/flaky/flaky.py b/.github/scripts/flaky/flaky.pyindex fa3ba46553..e4f5103736 100755--- a/.github/scripts/flaky/flaky.py+++ b/.github/scripts/flaky/flaky.py@@ -14,7 +14,21 @@ wraps the runner and reads its result file:expired entry.file-issuesopen or update one GitHub issue per flaky test (label `flaky`)- from the JSON artifacts that `run` wrote.+ from the JSON artifacts that `run` (or `detect`) wrote.+ gate-check+ for ci-gate: read the failed jobs of one workflow run on stdin+ ("<job id>\t<job name>" lines) and print `all` when every one+ matches an active job entry whose `signature` is in its log.+ ci-gate then reruns the failed jobs once; a quarantined job that+ fails again is reported and does not fail the gate.+ detect for the nightly flake scan: find jobs that failed and then passed+ on a rerun of the same commit, and write `file-issues` reports.++Quarantine entries (.github/flaky/quarantine.json) name either a `test` (a+test id, matched inside a job by `run`) or a `job` (a check name glob, with an+optional `workflow` name glob, matched by ci-gate). A `job` entry must also+carry a `signature`: a regex that must appear in the failed job's log, so only+the known failure is forgiven, never a new one in the same job.Result formats (--format): junit (cargo nextest), vitest (the reporter in.github/flaky/vitest-reporter.mjs), playwright (the JSON reporter), log (swift@@ -152,10 +166,22 @@ def check_entries(entries: List[dict], today: dt.date) -> Tuple[List[str], List[errors: List[str] = []expired: List[str] = []for i, entry in enumerate(entries):- label = entry.get("test", f"entry {i}")- for key in ("test", "owner", "issue", "expires"):+ label = entry.get("test") or entry.get("job") or f"entry {i}"+ kind = "job" if "job" in entry else "test"+ if "job" in entry and "test" in entry:+ errors.append(f"{label}: set `test` or `job`, not both")+ for key in (kind, "owner", "issue", "expires"):if not str(entry.get(key, "")).strip():errors.append(f"{label}: missing `{key}`")+ if kind == "job":+ signature = str(entry.get("signature") or "")+ if not signature.strip():+ errors.append(f"{label}: a `job` entry needs a `signature` regex from the failure log")+ else:+ try:+ re.compile(signature)+ except re.error as exc:+ errors.append(f"{label}: `signature` is not a valid regex ({exc})")if entry.get("issue") and not ISSUE_RE.match(entry["issue"]):errors.append(f"{label}: `issue` must be CUA-123, #123, or an issue URL, got {entry['issue']!r}")try:@@ -183,6 +209,8 @@ def active_entries(entries: List[dict], today: dt.date) -> List[dict]:def is_quarantined(test_id: str, suite: str, entries: List[dict]) -> Optional[dict]:for entry in entries:+ if "test" not in entry:+ continueif not (fnmatch.fnmatchcase(test_id, entry["test"]) or test_id.endswith("::" + entry["test"])):continueif entry.get("suite") and not fnmatch.fnmatchcase(suite, entry["suite"]):@@ -411,7 +439,7 @@ def cmd_file_issues(args: argparse.Namespace) -> int:issue = by_key.get(key)if issue is None:body = "\n".join([- f"`{clean(test_id, 300)}` passes only on retry in CI. Fix the race, or quarantine it in "+ f"`{clean(test_id, 300)}` passes only on retry in CI. Fix the cause, or quarantine it in ""`.github/flaky/quarantine.json` with an owner, this issue and an expiry date.","","Failure history is in the comments below, one per CI run.",@@ -419,7 +447,7 @@ def cmd_file_issues(args: argparse.Namespace) -> int:f"<!-- flaky-key:{key} -->",])url = gh("issue", "create", "--repo", repo, "--label", "flaky",- "--title", f"Flaky test: {clean(test_id, 200)}", "--body", body).strip()+ "--title", f"Flaky {'job' if report.get('kind') == 'job' else 'test'}: {clean(test_id, 200)}", "--body", body).strip()number = url.rsplit("/", 1)[-1]print(f"opened {url}")else:@@ -435,6 +463,108 @@ def cmd_file_issues(args: argparse.Namespace) -> int:return 0+# --- gate-check (ci-gate) -------------------------------------------------------+++def job_entry(workflow: str, job: str, entries: List[dict]) -> Optional[dict]:+ for entry in entries:+ if "job" not in entry or not entry.get("signature"):+ continue+ if not fnmatch.fnmatchcase(job, entry["job"]):+ continue+ if entry.get("workflow") and not fnmatch.fnmatchcase(workflow, entry["workflow"]):+ continue+ return entry+ return None+++def job_log(repo: str, job_id: str) -> str:+ done = subprocess.run(["gh", "api", f"repos/{repo}/actions/jobs/{job_id}/logs"],+ capture_output=True, text=True, errors="replace")+ return done.stdout if done.returncode == 0 else ""+++def cmd_gate_check(args: argparse.Namespace, fetch_log=job_log) -> int:+ today = dt.date.fromisoformat(args.today) if args.today else dt.date.today()+ path = Path(args.quarantine) if args.quarantine else QUARANTINE_FILE+ try:+ live = active_entries(json.loads(path.read_text()).get("entries", []), today)+ except (OSError, ValueError):+ live = []+ repo = os.environ.get("GITHUB_REPOSITORY", "")+ verdicts = []+ for line in sys.stdin:+ if not line.strip():+ continue+ job_id, _, name = line.rstrip("\n").partition("\t")+ entry = job_entry(args.workflow, name, live)+ hit = entry is not None and re.search(entry["signature"], fetch_log(repo, job_id)) is not None+ verdicts.append((name, entry if hit else None))+ for name, entry in verdicts:+ if entry:+ print(f"::warning title=Quarantined job ({args.workflow})::{name} failed with its known flake "+ f"(owner {entry['owner']}, {entry['issue']}, expires {entry['expires']})", file=sys.stderr)+ summary = os.environ.get("GITHUB_STEP_SUMMARY")+ if summary and any(e for _, e in verdicts):+ with open(summary, "a") as fh:+ fh.write(f"\n**Quarantined flakes in {cell(args.workflow)}**\n\n| Job | Issue | Expires |\n|---|---|---|\n")+ fh.writelines(f"| `{cell(n)}` | {e['issue']} | {e['expires']} |\n" for n, e in verdicts if e)+ print("all" if verdicts and all(e for _, e in verdicts) else "none")+ return 0+++# --- detect (nightly) -------------------------------------------------------------+++def gh_json(path: str) -> dict:+ return json.loads(gh("api", path))+++def cmd_detect(args: argparse.Namespace, api=gh_json) -> int:+ """Jobs that failed and then passed on a rerun of the same commit are flaky."""+ repo = os.environ["GITHUB_REPOSITORY"]+ since = (dt.datetime.now(dt.timezone.utc) - dt.timedelta(hours=args.since_hours)).strftime("%Y-%m-%dT%H:%M:%SZ")+ out_dir = Path(args.out)+ out_dir.mkdir(parents=True, exist_ok=True)+ found = 0+ page = 1+ while True:+ data = api(f"repos/{repo}/actions/runs?status=success&created=%3E%3D{since}&per_page=100&page={page}")+ runs = data.get("workflow_runs", [])+ for run in runs:+ attempt = int(run.get("run_attempt") or 1)+ if attempt < 2:+ continue+ before = api(f"repos/{repo}/actions/runs/{run['id']}/attempts/{attempt - 1}/jobs?per_page=100")+ failed = {j["name"] for j in before.get("jobs", []) if j.get("conclusion") in ("failure", "timed_out")}+ if not failed:+ continue+ after = api(f"repos/{repo}/actions/runs/{run['id']}/attempts/{attempt}/jobs?per_page=100")+ passed = {j["name"] for j in after.get("jobs", []) if j.get("conclusion") == "success"}+ flaky_jobs = sorted(failed & passed)+ if not flaky_jobs:+ continue+ prs = run.get("pull_requests") or []+ name = run.get("name", "")+ report = {+ "repo": repo, "run_id": str(run["id"]), "run_attempt": str(attempt), "workflow": name,+ "job": ", ".join(flaky_jobs), "ref": run.get("head_branch") or "", "sha": run.get("head_sha", ""),+ "pr": prs[0]["number"] if prs else None, "suite": name, "kind": "job",+ "flaky": [dict(id=f"{name} / {j}",+ message=f"failed on attempt {attempt - 1}, passed on attempt {attempt} of the same commit")+ for j in flaky_jobs],+ "quarantined": [],+ }+ (out_dir / f"run-{run['id']}.json").write_text(json.dumps(report, indent=2))+ found += len(flaky_jobs)+ print(f"{name}: {', '.join(flaky_jobs)} (run {run['id']}, attempt {attempt})")+ if len(runs) < 100 or page >= args.max_pages:+ break+ page += 1+ print(f"{found} flaky job(s) since {since}")+ return 0++def main(argv: Optional[List[str]] = None) -> int:# Windows runners default stdout to cp1252; test output can contain other characters.for stream_ in (sys.stdout, sys.stderr):@@ -453,8 +583,17 @@ def main(argv: Optional[List[str]] = None) -> int:issues = sub.add_parser("file-issues")issues.add_argument("--dir", required=True)issues.add_argument("--dry-run", action="store_true")+ gate = sub.add_parser("gate-check")+ gate.add_argument("--workflow", required=True)+ gate.add_argument("--quarantine", help="quarantine file (ci-gate passes the base commit's copy)")+ gate.add_argument("--today")+ detect = sub.add_parser("detect")+ detect.add_argument("--out", required=True)+ detect.add_argument("--since-hours", type=int, default=26)+ detect.add_argument("--max-pages", type=int, default=200)args = parser.parse_args(argv)- return {"run": cmd_run, "validate": cmd_validate, "file-issues": cmd_file_issues}[args.cmd](args)+ return {"run": cmd_run, "validate": cmd_validate, "file-issues": cmd_file_issues,+ "gate-check": cmd_gate_check, "detect": cmd_detect}[args.cmd](args)if __name__ == "__main__":diff --git a/.github/scripts/tests/test_ci_gate_workflow.py b/.github/scripts/tests/test_ci_gate_workflow.pyindex 7e34461e4a..fa36b910cc 100644--- a/.github/scripts/tests/test_ci_gate_workflow.py+++ b/.github/scripts/tests/test_ci_gate_workflow.py@@ -238,3 +238,53 @@ def test_gate_fails_on_a_merge_queue_ref_without_a_pull_request_number():completed = run_gate(DONE, queue_ref='refs/heads/gh-readonly-queue/main/odd')assert completed.returncode == 1assert 'build: pass' not in completed.stdout+++QUARANTINE_MOCK = MOCK.replace(" *) printf '999' ;;", """ *'--jq .run_attempt'*) cat "$STATE/attempt" ;;+ *) printf '999' ;;""").replace(""" *'head_sha='*)""", """ *'head_sha='*)+ if [[ -f "$STATE/reran" ]]; then printf '%s' "$ROWS_AFTER"; return; fi""") + '''+gh() { if [[ "$*" == *rerun-failed-jobs* ]]; then touch "$STATE/reran"; echo 2 > "$STATE/attempt"; else return 1; fi; }+'''+++def run_quarantine_gate(tmp_path, check, attempt='1', after='1\t11\tbuild\tsuccess\tcompleted'):+ stub = tmp_path / 'flaky.py'+ stub.write_text(f'import sys; sys.stdin.read(); print({check!r})\n')+ (tmp_path / 'attempt').write_text(attempt)+ return subprocess.run(+ ['bash', '-e', '-c', QUARANTINE_MOCK + SCRIPT[SCRIPT.index('sha=$PR_SHA'):]],+ env={**os.environ, 'PR_SHA': 'abc', 'QUEUE_REF': '', 'GITHUB_REPOSITORY': 'test/repo',+ 'GITHUB_RUN_ID': '99', 'ROWS': '1\t11\tbuild\tfailure\tcompleted', 'ROWS_AFTER': after,+ 'JOBS': '5\tlinux-kvm (concurrent)', 'OLDER_JOBS': '', 'ROWS_DIR': '', 'STATE': str(tmp_path),+ 'FLAKY_PY': str(stub), 'QUARANTINE_FILE': 'q.json', 'MAX_SLEEPS': '12', 'MAX_SECONDS': str(10**9)},+ capture_output=True, text=True, timeout=20,+ )+++def test_gate_reruns_a_quarantined_flake_once_and_passes_when_it_passes(tmp_path):+ done = run_quarantine_gate(tmp_path, 'all')+ assert done.returncode == 0, done.stderr+ assert (tmp_path / 'reran').exists()+ assert 'rerunning its failed jobs once' in done.stdout+ assert done.stdout.strip().splitlines()[-1] == 'build: pass'+++def test_gate_does_not_fail_on_a_quarantined_flake_that_fails_again(tmp_path):+ done = run_quarantine_gate(tmp_path, 'all', after='1\t11\tbuild\tfailure\tcompleted')+ assert done.returncode == 0, done.stderr+ assert 'build: pass (quarantined flake' in done.stdout+++def test_gate_fails_a_failure_that_is_not_quarantined(tmp_path):+ done = run_quarantine_gate(tmp_path, 'none')+ assert done.returncode == 1+ assert not (tmp_path / 'reran').exists()+ assert 'build: fail' in done.stdout+++def test_gate_reads_the_quarantine_list_from_the_base_commit():+ steps = GATE['jobs']['ci-gate']['steps']+ base = steps[0]['with']['sparse-checkout'].split()+ assert '/.github/flaky/quarantine.json' in base and '/.github/scripts/flaky/flaky.py' in base+ env = STEPS['Wait for every other workflow on the pull request head']['env']+ assert env['FLAKY_PY'].startswith('base/') and env['QUARANTINE_FILE'].startswith('base/')diff --git a/.github/scripts/tests/test_flaky.py b/.github/scripts/tests/test_flaky.pyindex 4fd59afebc..b10379b64f 100644--- a/.github/scripts/tests/test_flaky.py+++ b/.github/scripts/tests/test_flaky.py@@ -126,3 +126,80 @@ def test_parse_playwright(tmp_path):got = flaky.parse_playwright([str(path)])assert got["a.spec.ts > flows > one [chromium]"] == {"status": "flaky", "message": "x"}assert got["a.spec.ts > flows > two [chromium]"]["status"] == "failed"+++# --- job quarantine (ci-gate) and the nightly flake scan ------------------------------+++def job(**kw):+ base = {"job": "linux-kvm (concurrent)", "workflow": "Nightly: *", "signature": "Not authorized",+ "owner": "francesco", "issue": "CUA-1", "expires": "2026-11-01"}+ base.update(kw)+ return base+++def test_validate_job_entries():+ assert flaky.check_entries([job()], TODAY) == ([], [])+ assert flaky.check_entries([job(signature="")], TODAY)[0] # a job entry must name its failure+ assert flaky.check_entries([job(signature="(")], TODAY)[0]+ assert flaky.check_entries([job(test="x")], TODAY)[0]+++def test_the_repo_quarantine_list_is_valid():+ entries = json.loads(SCRIPT.parents[2].joinpath("flaky", "quarantine.json").read_text())["entries"]+ errors, _ = flaky.check_entries(entries, dt.date.fromisoformat(min(e["expires"] for e in entries)))+ assert errors == []+++def test_job_entries_never_match_tests():+ assert flaky.is_quarantined("linux-kvm (concurrent)", "s", [job()]) is None+++def gate_check(env, monkeypatch, entries, stdin, logs, workflow="Nightly: VM Space ready after boot"):+ flaky.QUARANTINE_FILE.write_text(json.dumps({"entries": entries}))+ monkeypatch.setattr(sys, "stdin", __import__("io").StringIO(stdin))+ args = flaky.argparse.Namespace(workflow=workflow, quarantine=None, today="2026-10-25")+ out = __import__("io").StringIO()+ monkeypatch.setattr(sys, "stdout", out)+ assert flaky.cmd_gate_check(args, fetch_log=lambda repo, job_id: logs.get(job_id, "")) == 0+ return out.getvalue().strip()++[email protected](("stdin", "logs", "workflow", "want"), [+ ("1\tlinux-kvm (concurrent)\n", {"1": "x registry: Not authorized y"}, "Nightly: VM Space ready after boot", "all"),+ # the job's log must show the known failure; a new failure in the same job still blocks+ ("1\tlinux-kvm (concurrent)\n", {"1": "assertion failed"}, "Nightly: VM Space ready after boot", "none"),+ # every failed job must be quarantined+ ("1\tlinux-kvm (concurrent)\n2\tlinux-kvm (sequential)\n", {"1": "Not authorized", "2": "Not authorized"},+ "Nightly: VM Space ready after boot", "none"),+ ("1\tlinux-kvm (concurrent)\n", {"1": "Not authorized"}, "CI: other", "none"),+ ("", {}, "Nightly: VM Space ready after boot", "none"),+])+def test_gate_check(env, monkeypatch, stdin, logs, workflow, want):+ assert gate_check(env, monkeypatch, [job()], stdin, logs, workflow) == want+++def test_gate_check_ignores_expired_entries(env, monkeypatch):+ assert gate_check(env, monkeypatch, [job(expires="2026-10-01")], "1\tlinux-kvm (concurrent)\n",+ {"1": "Not authorized"}) == "none"+++def test_detect_reports_jobs_that_failed_then_passed_on_a_rerun(env, monkeypatch):+ monkeypatch.setenv("GITHUB_REPOSITORY", "o/r")+ pages = {+ "runs?": {"workflow_runs": [+ {"id": 7, "name": "CI: jev-use", "run_attempt": 2, "head_sha": "abc", "head_branch": "b",+ "pull_requests": [{"number": 5}]},+ {"id": 8, "name": "CI: once", "run_attempt": 1},+ ]},+ "runs/7/attempts/1/": {"jobs": [{"name": "macOS mock E2E", "conclusion": "failure"},+ {"name": "lint", "conclusion": "success"}]},+ "runs/7/attempts/2/": {"jobs": [{"name": "macOS mock E2E", "conclusion": "success"}]},+ }+ api = lambda path: next(v for k, v in pages.items() if k in path)+ args = flaky.argparse.Namespace(out=str(env / "out"), since_hours=24, max_pages=2)+ assert flaky.cmd_detect(args, api=api) == 0+ report = json.loads((env / "out" / "run-7.json").read_text())+ assert report["kind"] == "job" and report["pr"] == 5+ assert [r["id"] for r in report["flaky"]] == ["CI: jev-use / macOS mock E2E"]+ assert not (env / "out" / "run-8.json").exists()diff --git a/.github/workflows/FLAKY.md b/.github/workflows/FLAKY.mdindex 1388fa4160..2212927f20 100644--- a/.github/workflows/FLAKY.md+++ b/.github/workflows/FLAKY.md@@ -4,6 +4,22 @@ Rule: a flake is fixed at its root cause (race, timeout, port, shared state),not with retries or raised limits. A check stays here only until its fixmerges. An entry without an owner is a bug in this file.+While the fix is in progress, a flake can be quarantined in+[`.github/flaky/quarantine.json`](../flaky/quarantine.json), with an owner, an issue+and an expiry (7 days for a new flake, never more than 90):++- A `test` entry: the test runner retries the test once, and a quarantined+ failure is reported but does not fail its job.+- A `job` entry (check name glob, workflow name glob and a `signature` regex+ from the failure log): `ci-gate` reruns the failed jobs once. If they fail+ again with that signature, the gate reports a quarantined flake and passes.+ Any other failure in the same job still fails the gate.++`ci-gate` reads the list from the base commit, so a PR cannot quarantine its+own failure. An expired entry fails `CI: flaky quarantine` on every PR. The+nightly `Flaky job scan` opens or updates a `flaky` issue for every job that+failed and then passed on a rerun of the same commit.+| Check | Symptom | Root cause | Owner | Status ||---|---|---|---|---|| `relay e2e (docker)`: `cua-relay` `tests/metering.rs` `past_the_allowance_the_session_continues_with_an_upgrade_prompt` | fails on slow runners | test slept 300 ms and assumed both streams were counted and open for 50 ms | relay (CUA-1952 fix: PR 93, injectable clock) | fix in review |diff --git a/.github/workflows/ci-gate.yml b/.github/workflows/ci-gate.ymlindex 938a7248be..58455e7692 100644--- a/.github/workflows/ci-gate.yml+++ b/.github/workflows/ci-gate.yml@@ -6,7 +6,10 @@ on:merge_group:permissions:- actions: read+ # write: only to rerun the failed jobs of a run whose every failure is a quarantined+ # flake (.github/flaky/quarantine.json), once. Fork PRs get a read-only token; their+ # quarantined failures are reported without the rerun.+ actions: writecontents: readpull-requests: read@@ -35,6 +38,8 @@ jobs:/.github/ci-areas.json/.github/scripts/ci_gate_scope.py/.github/scripts/ci_graph.py+ /.github/flaky/quarantine.json+ /.github/scripts/flaky/flaky.pyCargo.tomlpackage.jsonpnpm-workspace.yaml@@ -78,6 +83,8 @@ jobs:PR_SHA: ${{ github.event.pull_request.head.sha }}QUEUE_REF: ${{ github.event.merge_group.head_ref }}IGNORE_RE: ${{ steps.scope.outputs.ignore_re }}+ FLAKY_PY: base/.github/scripts/flaky/flaky.py+ QUARANTINE_FILE: base/.github/flaky/quarantine.jsonrun: |set -uo pipefailapi() { local out; for _ in 1 2 3 4 5 6; do out=$(gh api "$@") && { printf '%s\n' "$out"; return; }; sleep 120; done; return 1; }@@ -108,8 +115,33 @@ jobs:else echo 60fi}+ # Quarantined flakes (.github/flaky/quarantine.json, read from the base commit like the+ # selector, so a PR cannot quarantine its own failure). When every failed job of a run+ # matches a `job` entry and its log contains that entry's signature, the gate reruns the+ # failed jobs once and waits again. If they fail the same way again, the run is reported+ # as a quarantined flake and does not fail the gate. Any other failure fails it.+ retried=+ quarantine_verdict() {+ qv=+ local run=$1 name=$2 failed_jobs result attempt+ [[ -n "${FLAKY_PY:-}" && -f "$FLAKY_PY" ]] || return 0+ failed_jobs=$(api --paginate "repos/$GITHUB_REPOSITORY/actions/runs/$run/jobs?filter=latest&per_page=100" \+ --jq '.jobs[] | select(.conclusion == "failure" or .conclusion == "timed_out") | "\(.id)\t\(.name)"') || return 0+ [[ -n "$failed_jobs" ]] || return 0+ result=$(python3 "$FLAKY_PY" gate-check --workflow "$name" --quarantine "$QUARANTINE_FILE" <<<"$failed_jobs") || return 0+ [[ "$result" == all ]] || return 0+ attempt=$(api "repos/$GITHUB_REPOSITORY/actions/runs/$run" --jq .run_attempt) || return 0+ if (( attempt < 2 )) && [[ " $retried " != *" $run "* ]] \+ && gh api -X POST "repos/$GITHUB_REPOSITORY/actions/runs/$run/rerun-failed-jobs" >/dev/null; then+ retried="$retried $run"+ qv=retry+ else+ qv=quarantined+ fi+ }started=$SECONDSsleep 120+ while :; doprevious=while :; docurrent=$(runs) || exit 1@@ -120,6 +152,7 @@ jobs:sleep "$(poll_interval)"donefailed=0+ again=0for workflow in $(cut -f1 <<<"$current" | sort -u); doverdict=skippedname=$(awk -F'\t' -v w="$workflow" '$1 == w {print $3; exit}' <<<"$current")@@ -136,11 +169,19 @@ jobs:fiverdict=passif [[ ! "$conclusion" =~ ^(success|neutral)$ ]]; then- verdict=fail- failed=1+ quarantine_verdict "$run" "$name"+ case "$qv" in+ retry) verdict="quarantined flake, rerunning its failed jobs once"; again=1 ;;+ quarantined) verdict="pass (quarantined flake, not blocking; see the job summary)"+ echo "::warning title=Quarantined flake::$name failed with a known flake listed in .github/flaky/quarantine.json" ;;+ *) verdict=fail; failed=1 ;;+ esacfibreakdoneecho "$name: $verdict"done+ (( again )) || break+ sleep 30+ doneexit $faileddiff --git a/.github/workflows/flaky-detect.yml b/.github/workflows/flaky-detect.ymlnew file mode 100644index 0000000000..b1e3841fce--- /dev/null+++ b/.github/workflows/flaky-detect.yml@@ -0,0 +1,41 @@+name: "Flaky job scan"++# Nightly: finds jobs that failed and then passed when the same commit was rerun+# (any workflow, any event, the last 26 hours) and opens or updates one GitHub+# issue per job (label `flaky`) through .github/scripts/flaky/flaky.py. The issue+# says how to quarantine the job in .github/flaky/quarantine.json (an owner, the+# issue, a failure-log signature and a 7-day expiry) while the cause is fixed.+# Test-level flakes inside a job are filed by "Flaky test issues".++on:+ schedule:+ - cron: "23 5 * * *"+ workflow_dispatch:++permissions:+ actions: read+ contents: read+ issues: write++concurrency:+ group: flaky-detect+ cancel-in-progress: false++jobs:+ scan:+ name: scan reruns for flaky jobs+ runs-on: ubuntu-latest+ timeout-minutes: 30+ steps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ with:+ persist-credentials: false+ sparse-checkout: .github/scripts/flaky+ - name: Find jobs that passed only on a rerun+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 .github/scripts/flaky/flaky.py detect --out "$RUNNER_TEMP/flaky-results" --since-hours 26+ - name: Open or update the issues+ env:+ GH_TOKEN: ${{ github.token }}+ run: python3 .github/scripts/flaky/flaky.py file-issues --dir "$RUNNER_TEMP/flaky-results"diff --git a/docs/contributing/CI.md b/docs/contributing/CI.mdindex 9f5b31865d..122aae8bae 100644--- a/docs/contributing/CI.md+++ b/docs/contributing/CI.md@@ -90,6 +90,15 @@ to a relay change. Every other area lists every workflow whose own `paths:` reacor add a path to one, add it to the matching areas in `.github/ci-areas.json`. Changing the map or the gateis a `.github/**` change, so it waits for every workflow, and it takes effect only once it is on `main`.+## Flaky checks++Known flakes are listed in [`.github/flaky/quarantine.json`](../../.github/flaky/quarantine.json) and+[`.github/workflows/FLAKY.md`](../../.github/workflows/FLAKY.md). When every failed job of a workflow run+matches a `job` entry and its log contains the entry's `signature`, the gate reruns the failed jobs once. If+they pass, the run passes. If they fail again the same way, the gate reports a quarantined flake and does not+fail. The gate reads the list from the base commit. Every entry has an owner, an issue and an expiry date.+The nightly **Flaky job scan** files a `flaky` issue for each job that failed and then passed on a rerun.+## Urgent-fix laneLabel a pull request `urgent` for a production fix that cannot wait for the full suite: