oficina / equipo Public

CI: retry a failed test once, record the flake, calm the cold start

Every lane, the quarantine and runner-host retry a failed test once
where it failed. A pass on the retry stays green and prints
FLAKE <package>:<test> <lane> <commit> <seconds>s <load>; red means it
failed twice. More than 10 failures in a lane, or a build failure, is
not retried. scripts/ci-flakes.py reads the FLAKE lines back through
amadan ci status, keeps a history of the runs it saw, and names the
tests with 3 flakes in 7 days, with the quarantine line and the amadan
commands to file each as an Issue.

For the cold start: the compile step now also compiles the test
packages (go list -export -test) and builds rastrillo and the static
check tools, so 24 shards do not each build them; each shard's go
commands run 8 actions at once, the static checks on 8 threads; and the
shards that are not sensitive to load start once the machine has calmed
down, 30 seconds late at most.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 9a903eb2fd693ea6711e0ff346ec9707b49b922c parent 5570e5a
6 files changed, +631 −59
  • .amadan/ci.d/20-check@24 +6 −2
  • Makefile +19 −7
  • internal/testci/flakes_test.go +139 −0
  • scripts/ci-flakes.py +202 −0
  • scripts/ci-quarantine.txt +7 −4
  • scripts/ci-test.py +258 −46
diff --git a/.amadan/ci.d/20-check@24 b/.amadan/ci.d/20-check@24
index 6857abbc..8a61b450 100755
--- a/.amadan/ci.d/20-check@24
+++ b/.amadan/ci.d/20-check@24
@@ -2,9 +2,13 @@
# Everything but perf, as 24 shards side by side; AMADAN_SHARD picks one
# (scripts/ci-test.py: LANES, then EXTRA_SHARDS). Eighteen test lanes of
# about a minute each. Then the quarantine: known flaky tests
-# (scripts/ci-quarantine.txt), each retried once on failure, a pass on the
-# retry reported as a flake. Then runner-host: the exact bubblewrap build,
+# (scripts/ci-quarantine.txt), kept out of the lanes. Then runner-host: the exact bubblewrap build,
# the pinned programs, real namespaces and the cgroup move, uncached. Then
# the static checks: build, vet, format, budgets, references and the
# migration check; staticcheck; govulncheck; gitleaks.
+#
+# A failed test is retried once where it failed. A pass on the retry stays
+# green and prints "FLAKE <package>:<test> <lane> <commit> <seconds>s
+# <load>"; red means it failed twice. scripts/ci-flakes.py reads the FLAKE
+# lines back and names the tests that keep flaking.
exec "$(dirname "$0")/../../scripts/ci-box.py" run make ci-shard
diff --git a/Makefile b/Makefile
index d61a8bd4..b963dfb0 100644
--- a/Makefile
+++ b/Makefile
@@ -88,7 +88,13 @@ budget:
# LANE=headless-work runs one; scripts/ci-test.py lanes lists them), with
# test-quarantine, runner-host and the static checks as further shards.
# Known flaky tests are quarantined (scripts/ci-quarantine.txt): skipped
-# here, run by test-quarantine with one retry, and reported as flakes.
+# here and run by test-quarantine.
+#
+# A failed test is retried once, in the lane where it failed. A pass on
+# the retry keeps the lane green and prints a FLAKE line (the test, the
+# lane, the commit, how long the failed attempt took, the load average);
+# red means it failed twice. scripts/ci-flakes.py reads those lines back
+# from CI and names the tests that keep flaking.
test:
RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py all
@@ -102,11 +108,16 @@ ci-shard:
# start. Go does not share a compile between processes that start
# together: 23 shards on an empty cache each compiled the same packages,
# and every one of them took as long as the whole job used to. After this
-# the shards find their packages in the cache. Nothing is linked, so with
-# a warm cache it takes a few seconds.
+# the shards find their packages, their test packages and the tools the
+# static checks run in the cache: on an empty cache the shards building
+# those side by side held the load near 100 on 32 CPUs, and tests timed
+# out. No test is linked, so with a warm cache it takes a few seconds.
ci-compile:
go build ./...
- python3 scripts/ci-test.py compile
+ RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py compile
+ go run $(STATICCHECK) -version
+ go run $(GOVULNCHECK) -version
+ go run $(GITLEAKS) version
test-quarantine:
python3 scripts/ci-test.py quarantine
@@ -193,10 +204,10 @@ runner-prerequisites:
runner-namespace-test:
@test "$$(/usr/bin/bwrap --version)" = "bubblewrap 0.11.0"
- CGO_ENABLED=0 go test ./internal/runner/containment -run '^TestNamespace' -count=1
+ CGO_ENABLED=0 RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py retried runner-host -run '^TestNamespace' -count=1 ./internal/runner/containment
runner-adapter-test: runner-prerequisites
- CGO_ENABLED=0 go test ./internal/runner/provider/... ./internal/runner/checks -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1
+ CGO_ENABLED=0 RASTRILLO='$(RASTRILLO)' python3 scripts/ci-test.py retried runner-host -run 'TestDirect|TestProvider|TestCheckSandbox' -count=1 ./internal/runner/provider/... ./internal/runner/checks
runner-dead-references:
python3 scripts/runner-dead-references.py
@@ -205,7 +216,8 @@ runner-dead-references:
# exact bubblewrap build, the pinned Codex program, real namespaces, and a
# process moved between two delegated cgroups. Uncached, every time. On
# hosted CI the machine is the CI box (scripts/ci-box.py), which is made
-# to pass for a runner host.
+# to pass for a runner host. Its tests have the same one retry as the
+# lanes (scripts/ci-test.py retried).
runner-host: runner-adapter-test runner-namespace-test
# ci is the one gate: what a runner executes and what you run before
diff --git a/internal/testci/flakes_test.go b/internal/testci/flakes_test.go
new file mode 100644
index 00000000..54236952
--- /dev/null
+++ b/internal/testci/flakes_test.go
@@ -0,0 +1,139 @@
+package testci_test
+
+import (
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/testci"
+)
+
+// loadCITest is a python prelude that loads scripts/ci-test.py as m.
+const loadCITest = `
+import importlib.util, json, sys
+spec = importlib.util.spec_from_file_location("citest", "../../scripts/ci-test.py")
+m = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(m)
+`
+
+func python(t *testing.T, env []string, args ...string) string {
+ t.Helper()
+ cmd := exec.Command("python3", args...)
+ cmd.Env = append(os.Environ(), env...)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("python3 %v: %v: %s", args, err, out)
+ }
+ return string(out)
+}
+
+// The retry reads which tests failed from what rastrillo budget test
+// prints, and retries the deepest failed subtests: a parent fails only
+// because one of them did. A test that never finished counts; go test's
+// own "--- FAIL:" lines inside a test's output do not name a package and
+// are not read as failures.
+func TestRetryNamesTheFailedTests(t *testing.T) {
+ testci.Files(t, "../../scripts/ci-test.py")
+ report := strings.Join([]string{
+ "--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless",
+ "--- FAIL: TestHeadless (45.10s)",
+ "--- FAIL amadan.net/oficina/equipo/internal/headless TestHeadless/1_first_token",
+ " --- FAIL: TestHeadless/1_first_token (45.02s)",
+ "--- FAIL amadan.net/oficina/equipo/internal/runner TestStuck (never finished)",
+ "--- FAIL amadan.net/oficina/equipo/internal/runner (package output)",
+ "panic: test timed out",
+ "--- FAIL amadan.net/oficina/equipo/internal/wire (package output)",
+ "setup failed",
+ "",
+ }, "\n")
+ out := python(t, nil, "-c", loadCITest+`
+out = json.loads(sys.argv[1])
+found = {p: m.leaves(ts) for p, ts in m.failures(out).items()}
+print(json.dumps({"found": found, "seconds": m.failed_seconds(out, "TestHeadless/1_first_token"), "unknown": m.failed_seconds(out, "TestStuck")}))
+`, mustJSON(t, report))
+ var got struct {
+ Found map[string][]string
+ Seconds, Unknown string
+ }
+ if err := json.Unmarshal([]byte(out), &got); err != nil {
+ t.Fatalf("%v: %s", err, out)
+ }
+ want := map[string][]string{
+ "./internal/headless": {"TestHeadless/1_first_token"},
+ "./internal/runner": {"TestStuck"},
+ "./internal/wire": {},
+ }
+ if !reflect.DeepEqual(got.Found, want) {
+ t.Errorf("failed tests = %v, want %v", got.Found, want)
+ }
+ if got.Seconds != "45.02s" || got.Unknown != "unknown" {
+ t.Errorf("failed attempt took %q and %q, want 45.02s and unknown", got.Seconds, got.Unknown)
+ }
+}
+
+func mustJSON(t *testing.T, v any) string {
+ t.Helper()
+ raw, err := json.Marshal(v)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(raw)
+}
+
+// A FLAKE line as scripts/ci-test.py prints it is what
+// scripts/ci-flakes.py reads back. Three flakes of one test inside the
+// week make it a repeat offender, with the quarantine line and the amadan
+// commands to file; two do not.
+func TestFlakeLinesAreReadBack(t *testing.T) {
+ testci.Files(t, "../../scripts/ci-test.py", "../../scripts/ci-flakes.py", "../../scripts/ci-quarantine.txt")
+ dir := t.TempDir()
+ var logs []string
+ for i, commit := range []string{strings.Repeat("a", 40), strings.Repeat("b", 40), strings.Repeat("c", 40)} {
+ line := python(t, []string{"AMADAN_COMMIT=" + commit}, "-c", loadCITest+`
+print("some output before")
+print(m.flake_line("./internal/headless", "TestHeadless/1_first_token", "headless-rest", "45.02s", "31.50"))
+print(m.flake_line("./internal/thintest", "TestOnce", "thintest", "unknown", "unknown")) if sys.argv[1] == "0" else None
+`, string(rune('0'+i)))
+ if !strings.Contains(line, "\nFLAKE ./internal/headless:TestHeadless/1_first_token headless-rest "+commit+" 45.02s 31.50\n") {
+ t.Fatalf("the FLAKE line is not on a line of its own with its five fields:\n%s", line)
+ }
+ path := filepath.Join(dir, "run"+string(rune('0'+i))+".log")
+ if err := os.WriteFile(path, []byte(line), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ logs = append(logs, "-log", path)
+ }
+ base := []string{"../../scripts/ci-flakes.py", "-no-fetch", "-history", filepath.Join(dir, "history.jsonl")}
+
+ out := python(t, nil, append(base, logs...)...)
+ for _, want := range []string{
+ "3 ./internal/headless TestHeadless/1_first_token",
+ "1 ./internal/thintest TestOnce",
+ "REPEAT OFFENDER ./internal/headless TestHeadless/1_first_token: 3 flakes in 7 days",
+ "amadan discuss new oficina/equipo -title 'Flaky test: ./internal/headless TestHeadless/1_first_token' -body -",
+ "amadan discuss type oficina/equipo <id> -type Issue",
+ "testci.Quarantine(t)",
+ } {
+ if !strings.Contains(out, want) {
+ t.Errorf("three flakes: output lacks %q:\n%s", want, out)
+ }
+ }
+ if strings.Contains(out, "REPEAT OFFENDER ./internal/thintest") {
+ t.Errorf("one flake made a repeat offender:\n%s", out)
+ }
+
+ // The history holds what was read: the same logs again add nothing.
+ again := python(t, nil, append(base, logs...)...)
+ if !strings.Contains(again, "3 ./internal/headless TestHeadless/1_first_token") {
+ t.Errorf("reading the same runs twice changed the count:\n%s", again)
+ }
+
+ two := python(t, nil, append([]string{"../../scripts/ci-flakes.py", "-no-fetch", "-history", filepath.Join(dir, "two.jsonl")}, logs[:4]...)...)
+ if !strings.Contains(two, "2 ./internal/headless TestHeadless/1_first_token") || strings.Contains(two, "REPEAT OFFENDER") {
+ t.Errorf("two flakes: want the count and no repeat offender:\n%s", two)
+ }
+}
diff --git a/scripts/ci-flakes.py b/scripts/ci-flakes.py
new file mode 100755
index 00000000..d2efad5e
--- /dev/null
+++ b/scripts/ci-flakes.py
@@ -0,0 +1,202 @@
+#!/usr/bin/env python3
+"""List the tests that keep flaking on CI.
+
+ scripts/ci-flakes.py main and every branch git knows on origin
+ scripts/ci-flakes.py -branch B ... these branches only
+ scripts/ci-flakes.py -log FILE ... a saved job log, as one more run
+
+A test that fails and then passes on its one retry leaves a line in the
+job's log (scripts/ci-test.py prints it):
+
+ FLAKE <package>:<test> <lane> <commit> <seconds>s <load>
+
+This reads those lines back through `amadan ci status REPO -branch B
+-json` and counts them per test over the last -days days (7).
+
+amadan keeps one run per branch, the latest, so each time it runs this
+adds the runs it sees to a history file (-history, by default
+~/.cache/equipo/ci-flakes.jsonl) and counts over that file's last -runs
+runs (200). Run it after a push, or daily, from the same account; a run
+it never saw is not counted.
+
+A test with -times flakes (3) inside the window is a repeat offender. For
+each one this prints the line to add to scripts/ci-quarantine.txt and the
+two amadan commands that file it as a discussion of type Issue. It files
+nothing itself: whoever runs it does, with the commands as printed.
+"""
+import argparse
+import json
+import os
+import re
+import shlex
+import subprocess
+import sys
+import time
+
+# The line scripts/ci-test.py prints (FLAKE there): keep the two in step.
+FLAKE = re.compile(r"^FLAKE (\./\S+):(Test\S*) (\S+) ([0-9a-f]{40}|unknown) (\d+(?:\.\d+)?s|unknown) (\d+(?:\.\d+)?|unknown)$", re.M)
+
+QUARANTINE = "scripts/ci-quarantine.txt"
+
+
+def root():
+ return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+
+
+def flakes(log):
+ return [dict(zip(("package", "test", "lane", "commit", "seconds", "load"), m.groups())) for m in FLAKE.finditer(log)]
+
+
+def origin_branches():
+ """main, then every other branch git has seen on origin."""
+ try:
+ out = subprocess.check_output(
+ ["git", "-C", root(), "for-each-ref", "--format=%(refname:lstrip=3)", "refs/remotes/origin"], text=True)
+ except (OSError, subprocess.CalledProcessError):
+ out = ""
+ names = [b for b in out.split() if b not in ("HEAD", "main")]
+ return ["main"] + sorted(names)
+
+
+def fetch(repo, branch):
+ """The branch's latest run as amadan reports it, or None with the
+ reason: no such branch, no run yet, still running."""
+ cmd = ["amadan", "ci", "status", repo, "-branch", branch, "-json"]
+ try:
+ p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=120)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ return None, str(e)
+ try:
+ status = json.loads(p.stdout)
+ except ValueError:
+ return None, (p.stderr or p.stdout).strip() or "no JSON"
+ if status.get("state") not in ("success", "failure"):
+ return None, "state " + str(status.get("state"))
+ return {
+ "run": "%s %s %s" % (branch, status.get("sha", ""), status.get("updated_at", "")),
+ "branch": branch, "commit": status.get("sha", ""), "state": status["state"],
+ "at": int(status.get("updated_at") or time.time()),
+ "flakes": flakes(status.get("log", "")),
+ }, ""
+
+
+def from_log(path):
+ with open(path, errors="replace") as f:
+ found = flakes(f.read())
+ return {"run": "log " + os.path.abspath(path), "branch": "", "commit": found[0]["commit"] if found else "",
+ "state": "", "at": int(time.time()), "flakes": found}
+
+
+def load_history(path):
+ runs = {}
+ try:
+ with open(path) as f:
+ for line in f:
+ if line.strip():
+ run = json.loads(line)
+ runs[run["run"]] = run
+ except FileNotFoundError:
+ pass
+ return runs
+
+
+def save_history(path, runs, keep):
+ kept = sorted(runs.values(), key=lambda r: r["at"])[-keep:]
+ os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
+ tmp = path + ".tmp"
+ with open(tmp, "w") as f:
+ for run in kept:
+ f.write(json.dumps(run, sort_keys=True) + "\n")
+ os.replace(tmp, path)
+ return kept
+
+
+def quarantined():
+ listed = set()
+ try:
+ with open(os.path.join(root(), QUARANTINE)) as f:
+ for line in f:
+ fields = line.split(None, 2)
+ if len(fields) >= 2 and fields[0].startswith("./"):
+ listed.add((fields[0], fields[1]))
+ except FileNotFoundError:
+ pass
+ return listed
+
+
+def offender(repo, package, test, hits, days):
+ """What to do about a repeat offender, as text."""
+ title = "Flaky test: %s %s" % (package, test)
+ lines = ["", "REPEAT OFFENDER %s %s: %d flakes in %d days" % (package, test, len(hits), days),
+ "1. Quarantine it. Make the test call testci.Quarantine(t) first, and add to " + QUARANTINE + ":",
+ "",
+ "%s %s Flaked %d times in %d days on hosted CI (scripts/ci-flakes.py). Leaves when the discussion below is closed with the cause fixed." % (package, test, len(hits), days),
+ "",
+ "2. File it, with these two commands as they are (the second with the id the first prints):",
+ "",
+ "amadan discuss new %s -title %s -body - <<'BODY'" % (repo, shlex.quote(title)),
+ "%s %s flaked %d times in %d days on hosted CI: it failed, then passed on its one retry." % (package, test, len(hits), days),
+ "It is quarantined in " + QUARANTINE + " until the cause is fixed.",
+ ""]
+ for at, branch, f in hits:
+ lines.append("- %s commit %s branch %s lane %s failed attempt %s load %s" % (
+ time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(at)), f["commit"][:12], branch or "?", f["lane"], f["seconds"], f["load"]))
+ lines += ["", "The failed attempt's output is in that run's job log, above its FLAKE line.", "BODY",
+ "amadan discuss type %s <id> -type Issue" % repo]
+ return "\n".join(lines)
+
+
+def main(argv):
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("-repo", default="oficina/equipo")
+ ap.add_argument("-branch", action="append", help="a branch to read; repeat it. Default: main and every origin branch")
+ ap.add_argument("-log", action="append", default=[], help="a saved job log to read as one more run; repeat it")
+ ap.add_argument("-days", type=int, default=7)
+ ap.add_argument("-times", type=int, default=3, help="flakes inside the window that make a repeat offender")
+ ap.add_argument("-runs", type=int, default=200, help="runs the history keeps")
+ ap.add_argument("-history", default=os.path.join(os.path.expanduser("~"), ".cache", "equipo", "ci-flakes.jsonl"))
+ ap.add_argument("-no-fetch", action="store_true", help="read only the history and -log files")
+ args = ap.parse_args(argv)
+
+ runs = load_history(args.history)
+ seen = len(runs)
+ if not args.no_fetch:
+ for branch in args.branch or origin_branches():
+ run, why = fetch(args.repo, branch)
+ if run is None:
+ if args.branch:
+ print("%s: not read: %s" % (branch, why))
+ continue
+ runs.setdefault(run["run"], run)
+ for path in args.log:
+ run = from_log(path)
+ runs.setdefault(run["run"], run)
+ kept = save_history(args.history, runs, args.runs)
+
+ since = time.time() - args.days * 86400
+ window = [r for r in kept if r["at"] >= since]
+ by_test = {}
+ for run in window:
+ for f in run["flakes"]:
+ by_test.setdefault((f["package"], f["test"]), []).append((run["at"], run["branch"], f))
+ print("%d runs in the last %d days (%d new this time, %d kept in %s)" % (
+ len(window), args.days, len(runs) - seen, len(kept), args.history))
+ if not by_test:
+ print("no flakes")
+ return 0
+ listed = quarantined()
+ print("flakes, package, test, lanes, last seen")
+ ranked = sorted(by_test.items(), key=lambda kv: (-len(kv[1]), kv[0]))
+ for (package, test), hits in ranked:
+ note = " (quarantined)" if (package, test) in listed else ""
+ print("%d %s %s %s %s%s" % (
+ len(hits), package, test, ",".join(sorted({f["lane"] for _, _, f in hits})),
+ time.strftime("%Y-%m-%d", time.gmtime(max(at for at, _, _ in hits))), note))
+ for (package, test), hits in ranked:
+ if len(hits) >= args.times and (package, test) not in listed:
+ print(offender(args.repo, package, test, sorted(hits, key=lambda h: h[0]), args.days))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/scripts/ci-quarantine.txt b/scripts/ci-quarantine.txt
index 279f6be1..ca0f37c8 100644
--- a/scripts/ci-quarantine.txt
+++ b/scripts/ci-quarantine.txt
@@ -1,9 +1,12 @@
# Quarantined flaky tests: one per line, the package, the test (or
# Test/Subtest) and why. A listed test calls testci.Quarantine(t) first.
-# The normal test lanes skip it; make test-quarantine (CI step
-# test-quarantine) runs it, retries a failure once, and reports a pass on
-# the retry as a flake. A quarantine is a holding pen, not a fix: each
-# line says what would let it leave. CI-PROGRESS.md has the history.
+# The normal test lanes skip it; make test-quarantine (the quarantine
+# shard of the check step) runs it. Every lane retries a failed test once
+# and prints a FLAKE line when the retry passes; this file is for the
+# repeat offenders. scripts/ci-flakes.py names them: a test that flakes 3
+# times in 7 days gets a line here and an amadan discussion of type Issue
+# on oficina/equipo. A quarantine is a holding pen, not a fix: each line
+# says what would let it leave. CI-PROGRESS.md has the history.
#
# package test why
diff --git a/scripts/ci-test.py b/scripts/ci-test.py
index 86126811..103e62b6 100755
--- a/scripts/ci-test.py
+++ b/scripts/ci-test.py
@@ -6,6 +6,7 @@
scripts/ci-test.py shard the shard AMADAN_SHARD names (make ci-shard)
scripts/ci-test.py quarantine the quarantined tests (make test-quarantine)
scripts/ci-test.py compile compile every package once (make ci-compile)
+ scripts/ci-test.py retried LANE ARGS... go test ARGS, with the one retry
scripts/ci-test.py lanes print each lane and its packages
The slow packages each have a lane of their own and "rest" holds every
@@ -16,6 +17,15 @@ pass or fail in that shard's own log. The quarantine, the runner host
checks (make runner-host) and the static checks are shards of the same
step, after the lanes.
+A failed test is retried once, where it failed, and a pass on the retry
+is a flake: the step stays green and prints one line,
+
+ FLAKE <package>:<test> <lane> <commit> <seconds>s <load>
+
+with the time the failed attempt took and the machine's load average when
+it failed. Red means the test failed twice. scripts/ci-flakes.py reads
+those lines back from CI and names the tests that keep flaking.
+
Results are cached: go test replays a pass for a package whose test
binary, declared files and environment are unchanged (internal/testci
covers the inputs go test cannot see). UNCACHED lists what must run
@@ -32,6 +42,8 @@ import shlex
import subprocess
import sys
import tempfile
+import threading
+import time
from concurrent.futures import ThreadPoolExecutor
MODULE = "amadan.net/oficina/equipo"
@@ -100,6 +112,38 @@ TEST_TOOL_DIRS = {"try-bin": "~/.local/share/equipo/try/bin"}
QUARANTINE = "scripts/ci-quarantine.txt"
+# More failures than this in one lane is a broken change, not a flake:
+# nothing is retried and the lane is red.
+RETRY_LIMIT = 10
+
+# The shards of a step all start at once on one machine. On an empty
+# cache that was 24 go builds on 32 CPUs, a load near 100 for the whole
+# step, and tests with a 45 second wait in them timed out (the first
+# token, the transfer, containment proofs). Three things keep it down.
+#
+# The compile step builds what shards would otherwise each build: the test
+# packages and the tools (run_compile, make ci-compile).
+#
+# Each shard's go commands run at most BUILD_JOBS actions at once (go's
+# -p, 32 by default here); the static checks, which only compute, also
+# keep to CHECK_CPUS threads.
+#
+# The shards named in LATE start after the load-sensitive lanes are under
+# way: they wait SETTLE seconds, then until tasks have waited for a CPU
+# less than BUSY percent of the last ten seconds, LATE seconds at most. A
+# warm run is never busy, so there it costs SETTLE seconds of shards that
+# finish early anyway. A late shard is named by its lane, or by its first
+# make target.
+BUILD_JOBS = 8
+BUILD_JOBS_MANY = 16 # for the lane of many small packages, where -p is also how many test at once
+CHECK_CPUS = 8
+SETTLE, BUSY = 5, 15.0
+LATE = {
+ "equipotest-a": 30, "equipotest-d": 30, "equipotest-r": 30, "equipotest-rest": 30,
+ "plan3test": 30, "rest": 30,
+ "runner-dead-references": 30, "staticcheck": 30, "govulncheck": 30, "gitleaks": 30,
+}
+
def root():
return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -207,8 +251,9 @@ def rastrillo():
"RASTRILLO", "go run amadan.net/rastrillo/rastrillo/cmd/rastrillo"))
-def budget_test(packages, env, flags=()):
- """One rastrillo budget test over packages; returns its exit status."""
+def budget_test(packages, env, lane, flags=()):
+ """One rastrillo budget test over packages, a failed test retried once;
+ returns its exit status."""
status = 0
cached = [p for p in packages if p not in UNCACHED]
uncached = [p for p in packages if p in UNCACHED]
@@ -217,19 +262,38 @@ def budget_test(packages, env, flags=()):
continue
for p in group if extra else []:
print(f"uncached: {p}: {UNCACHED[p]}", flush=True)
- cmd = rastrillo() + ["budget", "test", "-tags", TAGS, "-timeout", TIMEOUT] + extra + list(flags) + group
- print("+ " + " ".join(shlex.quote(c) for c in cmd), flush=True)
- status = run_reporting_misses(cmd, env) or status
+ base = ["-tags", TAGS, "-timeout", TIMEOUT] + extra + list(flags)
+ status = run_retrying(rastrillo() + ["budget", "test"] + base + group, env, lane, base) or status
return status
+def run_retrying(cmd, env, lane, base):
+ """Run a rastrillo budget test; retry what failed once, with go test
+ and the flags in base. Returns the exit status after the retry."""
+ print("+ " + " ".join(shlex.quote(c) for c in cmd), flush=True)
+ status, out = run_reporting_misses(cmd, env)
+ if status == 0:
+ return 0
+ return retry_failures(out, env, lane, base)
+
+
def run_reporting_misses(cmd, env):
"""Run cmd with go's test cache debugging on, and print one line per
package that missed the cache because its inputs changed, instead of
- go's ID-by-ID trace."""
+ go's ID-by-ID trace. Returns the exit status and what cmd printed."""
env = dict(env)
env["GODEBUG"] = ",".join(filter(None, [env.get("GODEBUG", ""), "gocachetest=1"]))
- p = subprocess.Popen(cmd, env=env, stderr=subprocess.PIPE, text=True, bufsize=1)
+ p = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, bufsize=1, errors="replace")
+ printed = []
+
+ def copy():
+ for line in p.stdout:
+ printed.append(line)
+ sys.stdout.write(line)
+ sys.stdout.flush()
+ copier = threading.Thread(target=copy)
+ copier.start()
missed = set()
for line in p.stderr:
if not line.startswith("testcache: "):
@@ -242,32 +306,80 @@ def run_reporting_misses(cmd, env):
if m and m.group(1) not in missed and m.group(2).startswith("test output not found"):
missed.add(m.group(1))
print(f"cache miss: {m.group(1)}: its inputs changed", flush=True)
- return p.wait()
+ copier.join()
+ return p.wait(), "".join(printed)
def run_lane(name):
packages = lane_packages(name)
print(f"test lane {name}: {' '.join(packages)}", flush=True)
- return budget_test(packages, budget_env(environment(False)), lane_flags(name))
+ return budget_test(packages, budget_env(environment(False)), name, lane_flags(name))
def run_all():
env = budget_env(environment(False))
if not UNCACHED:
# One go test over ./... lets rastrillo also flag a stale time record.
- cmd = rastrillo() + ["budget", "test", "-tags", TAGS, "-timeout", TIMEOUT, "./..."]
- print("+ " + " ".join(cmd), flush=True)
- return subprocess.call(cmd, env=env)
- return budget_test(all_packages(), env)
+ base = ["-tags", TAGS, "-timeout", TIMEOUT]
+ return run_retrying(rastrillo() + ["budget", "test"] + base + ["./..."], env, "all", base)
+ return budget_test(all_packages(), env, "all")
+
+
+def run_retried(lane, args):
+ """go test args through rastrillo, untimed, with the one retry: for the
+ make targets that run go test themselves (runner-host)."""
+ base = [a for a in args if not a.startswith("./")]
+ return run_retrying(rastrillo() + ["budget", "test", "-no-time"] + args, dict(os.environ), lane, base)
def run_compile():
- """Compile every package, as the tests build them, and link nothing:
- what stays is the build cache the shards then share. Each shard still
- compiles its own test files and links its own binary."""
- cmd = ["go", "build", "-tags", TAGS, "./..."]
- print("+ " + " ".join(cmd), flush=True)
- return subprocess.call(cmd)
+ """Compile every package and its tests, as the lanes build them, and
+ link no test: what stays is the build cache the shards then share.
+ Each shard still links its own test binary."""
+ for cmd in (["go", "build", "-tags", TAGS, "./..."],
+ # -export compiles each package and, with -test, its tests:
+ # the lanes of one package would each compile them again.
+ ["go", "list", "-export", "-test", "-tags", TAGS, "-f", "", "./..."]):
+ print("+ " + " ".join(cmd), flush=True)
+ started = time.time()
+ status = subprocess.call(cmd, stdout=subprocess.DEVNULL)
+ print(f" {time.time() - started:.1f}s", flush=True)
+ if status:
+ return status
+ # The lanes run rastrillo with go run, which keeps the program it
+ # built. What budget size says is the budget target's to judge.
+ subprocess.call(rastrillo() + ["budget", "size"], stdout=subprocess.DEVNULL)
+ return 0
+
+
+def load_average():
+ try:
+ with open("/proc/loadavg") as f:
+ return f.read().split()[0]
+ except (OSError, IndexError):
+ return "unknown"
+
+
+def cpu_waiting():
+ """The share of the last ten seconds some task waited for a CPU."""
+ try:
+ with open("/proc/pressure/cpu") as f:
+ return float(f.readline().split("avg10=")[1].split()[0])
+ except (OSError, IndexError, ValueError):
+ return 0.0
+
+
+def stagger(name):
+ """Start a shard named in LATE once the machine has calmed down."""
+ limit = LATE.get(name)
+ if not limit:
+ return
+ started = time.time()
+ time.sleep(min(SETTLE, limit))
+ while time.time() - started < limit and cpu_waiting() >= BUSY:
+ time.sleep(1)
+ print(f"stagger: {name} started {time.time() - started:.0f}s late; cpu waiting {cpu_waiting():.1f}%, "
+ f"load {load_average()}", flush=True)
def machine_load():
@@ -293,19 +405,27 @@ def run_shard():
if count != shards or not 0 <= index < count:
sys.exit(f"ci-test: shard {index} of {count}, but there are {len(LANES)} lanes and "
f"{len(EXTRA_SHARDS)} extra shards; name the step 20-check@{shards}")
+ name = LANES[index][0] if index < len(LANES) else EXTRA_SHARDS[index - len(LANES)][0]
+ jobs = BUILD_JOBS_MANY if name == "rest" else BUILD_JOBS
+ os.environ["GOFLAGS"] = " ".join(filter(None, [os.environ.get("GOFLAGS", ""), f"-p={jobs}"]))
+ stagger(name)
if index < len(LANES):
- status = run_lane(LANES[index][0])
+ status = run_lane(name)
machine_load()
return status
targets = EXTRA_SHARDS[index - len(LANES)]
print(f"shard {index}: make {' '.join(targets)}", flush=True)
- # runner-host reruns tests the lanes ran; the quarantine shard beside
- # it is where a quarantined one of them runs, with its retry.
- env = dict(os.environ, EQUIPO_QUARANTINE="skip") if targets == ["runner-host"] else None
- return subprocess.call(["make", "--no-print-directory"] + targets, env=env)
-
+ env = dict(os.environ)
+ if targets == ["runner-host"]:
+ # runner-host reruns tests the lanes ran; the quarantine shard beside
+ # it is where a quarantined one of them runs.
+ env["EQUIPO_QUARANTINE"] = "skip"
+ elif targets != ["test-quarantine"]:
+ env["GOMAXPROCS"] = str(CHECK_CPUS) # a static check: it only computes
+ status = subprocess.call(["make", "--no-print-directory"] + targets, env=env)
+ machine_load()
+ return status
-# The quarantine.
def quarantined():
"""(package, test) pairs from the quarantine file."""
@@ -322,43 +442,129 @@ def quarantined():
return entries
-def run_pattern(tests):
- """A -run pattern for tests under one top-level test."""
- top = {t.split("/", 1)[0] for t in tests}
- assert len(top) == 1
- subs = [t.split("/", 1)[1] for t in tests if "/" in t]
- pattern = "^" + re.escape(top.pop()) + "$"
- if subs:
- if len(subs) != len(tests):
- sys.exit(f"{QUARANTINE}: list a test or some of its subtests, not both: {tests}")
- pattern += "/^(" + "|".join(re.escape(s) for s in subs) + ")$"
- return pattern
-
-
-def go_test(package, tests, env, fresh):
- cmd = ["go", "test", "-tags", TAGS, "-timeout", TIMEOUT, "-v", "-run", run_pattern(tests)]
+def go_test(package, tests, env, base, fresh=True):
+ """go test -v of tests in package (all of it when tests is empty), with
+ the flags in base. Returns the command, its output, and the tests that
+ passed and that failed."""
+ cmd = ["go", "test"] + list(base) + ["-v"]
+ if tests:
+ cmd += ["-run", test_pattern(tests)]
if fresh:
cmd.append("-count=1")
cmd.append(package)
- with tempfile.TemporaryFile("w+") as log:
+ with tempfile.TemporaryFile("w+", errors="replace") as log:
code = subprocess.call(cmd, env=env, stdout=log, stderr=subprocess.STDOUT)
log.seek(0)
out = log.read()
+ if not tests:
+ return shlex.join(cmd), out, {WHOLE} if code == 0 else set(), set() if code == 0 else {WHOLE}
passed = {t for t in tests if re.search(r"^\s*--- PASS: " + re.escape(t) + r" \(", out, re.M)}
failed = {t for t in tests if re.search(r"^\s*--- FAIL: " + re.escape(t) + r" \(", out, re.M)}
if code != 0 and not failed:
failed = set(tests) - passed # the binary failed around them
- return " ".join(cmd), out, passed, failed
+ return shlex.join(cmd), out, passed, failed
def tail(text, n=60):
return "\n".join(text.splitlines()[-n:])
+# The one retry, and the FLAKE line.
+
+# What a flake is called when the package failed outside every test.
+WHOLE = "TestMain"
+
+FLAKE = re.compile(r"^FLAKE (\./\S+):(Test\S*) (\S+) ([0-9a-f]{40}|unknown) (\d+(?:\.\d+)?s|unknown) (\d+(?:\.\d+)?|unknown)$", re.M)
+
+
+def commit():
+ """The commit under test: amadan names it, git knows it anywhere else."""
+ named = os.environ.get("AMADAN_COMMIT", "")
+ if re.fullmatch(r"[0-9a-f]{40}", named):
+ return named
+ try:
+ head = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL).strip()
+ except (OSError, subprocess.CalledProcessError):
+ return "unknown"
+ return head if re.fullmatch(r"[0-9a-f]{40}", head) else "unknown"
+
+
+def failed_seconds(out, test):
+ """How long test's failed attempt took, from go test's own FAIL line."""
+ m = re.search(r"^\s*--- FAIL: " + re.escape(test) + r" \((\d+(?:\.\d+)?)s\)", out, re.M)
+ return m.group(1) + "s" if m else "unknown"
+
+
+def flake_line(package, test, lane, seconds, load):
+ """The one line per flake, with a rule above and below so it is not
+ missed in a log. scripts/ci-flakes.py reads it back (FLAKE above): keep
+ the two in step."""
+ line = f"FLAKE {package}:{test} {lane} {commit()} {seconds} {load}"
+ assert FLAKE.fullmatch(line), line
+ rule = "#" * 78
+ return f"{rule}\n{line}\n{rule}\nfailed, then passed on its one retry: the step stays green and the flake is on record"
+
+
+def failures(out):
+ """What a rastrillo budget test reported as failed: {package: tests},
+ a package that failed outside every test mapped to no tests. Tests
+ that never finished (a timeout, a panic beside them) count as failed."""
+ found = {}
+ for m in re.finditer(r"^--- FAIL (\S+) \(package output\)$", out, re.M):
+ if m.group(1).startswith(MODULE):
+ found.setdefault("." + m.group(1)[len(MODULE):], [])
+ for m in re.finditer(r"^--- FAIL (\S+) (Test\S*)(?: \(never finished\))?$", out, re.M):
+ if m.group(1).startswith(MODULE):
+ found.setdefault("." + m.group(1)[len(MODULE):], []).append(m.group(2))
+ return found
+
+
+def leaves(tests):
+ """The failed tests with no failed subtest of their own: a parent only
+ fails because one of those did."""
+ return sorted(t for t in set(tests) if not any(other.startswith(t + "/") for other in tests))
+
+
+def retry_failures(out, env, lane, base):
+ """Retry once, with go test, each test the failed run in out reported.
+ A pass on the retry is a flake and prints its line; returns 0 only when
+ everything that failed passed on its retry."""
+ found = {package: leaves(tests) for package, tests in failures(out).items()}
+ count = sum(max(1, len(tests)) for tests in found.values())
+ if re.search(r"^--- BUILD FAILED ", out, re.M):
+ print("not retried: a package did not build", flush=True)
+ return 1
+ if not found:
+ print("not retried: go test failed without naming a failed test (a build, a budget)", flush=True)
+ return 1
+ if count > RETRY_LIMIT:
+ print(f"not retried: {count} tests failed, more than {RETRY_LIMIT}: a break, not a flake", flush=True)
+ return 1
+ load = load_average()
+ status = 0
+ for package, tests in sorted(found.items()):
+ cmd, retry_out, passed, failed = go_test(package, tests, env, base)
+ print(f"+ {cmd} (retry, once)", flush=True)
+ twice = []
+ for t in tests or [WHOLE]:
+ if t in passed and t not in failed:
+ print(flake_line(package, t, lane, failed_seconds(out, t), load), flush=True)
+ else:
+ twice.append(t)
+ print(f"FAILED TWICE {package}:{t} {lane}", flush=True)
+ if twice:
+ status = 1
+ print(tail(retry_out, 200), flush=True)
+ return status
+
+
+# The quarantine.
+
def run_group(package, tests, env):
"""Run one top-level test's quarantined entries; retry failures once."""
report = []
- cmd, out, passed, failed = go_test(package, tests, env, fresh=False)
+ base = ["-tags", TAGS, "-timeout", TIMEOUT]
+ cmd, out, passed, failed = go_test(package, tests, env, base, fresh=False)
report.append(f"+ {cmd}")
missing = set(tests) - passed - failed
flaky, broken = [], sorted(missing)
@@ -367,12 +573,13 @@ def run_group(package, tests, env):
if failed:
report.append(f"first attempt failed: {' '.join(sorted(failed))}; output tail:")
report.append(tail(out))
- retry_cmd, retry_out, retry_passed, retry_failed = go_test(package, sorted(failed), env, fresh=True)
+ load = load_average()
+ retry_cmd, retry_out, retry_passed, retry_failed = go_test(package, sorted(failed), env, base)
report.append(f"+ {retry_cmd} (retry, once)")
for t in sorted(failed):
if t in retry_passed and t not in retry_failed:
flaky.append(t)
- report.append(f"FLAKE {package} {t}: failed, then passed on the retry")
+ report.append(flake_line(package, t, "quarantine", failed_seconds(out, t), load))
else:
broken.append(t)
report.append(f"QUARANTINE FAIL {package} {t}: failed twice")
@@ -388,6 +595,9 @@ def run_quarantine():
groups = {}
for package, test in quarantined():
groups.setdefault((package, test.split("/", 1)[0]), []).append(test)
+ for (_, top), tests in groups.items():
+ if top in tests and len(tests) > 1:
+ sys.exit(f"{QUARANTINE}: list a test or some of its subtests, not both: {tests}")
print(f"quarantine: {sum(len(v) for v in groups.values())} tests from {QUARANTINE}; "
"a failure is retried once, and a pass on the retry is reported as a flake", flush=True)
with ThreadPoolExecutor(max_workers=max(1, len(groups))) as pool:
@@ -416,6 +626,8 @@ def main(argv):
return run_compile()
if argv == ["quarantine"]:
return run_quarantine()
+ if len(argv) > 2 and argv[0] == "retried":
+ return run_retried(argv[1], argv[2:])
if argv == ["lanes"]:
for name, _, _ in LANES:
print(name + ": " + " ".join(lane_packages(name) + lane_flags(name)))