#!/usr/bin/env python3 """Run the test suite, one lane of it, or the quarantined flaky tests. scripts/ci-test.py all every lane in one go test (make test) scripts/ci-test.py lane NAME one lane (make test-lane LANE=NAME) 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 scripts/ci-test.py browser print each package's browser tests scripts/ci-test.py check every test in exactly one lane (make lanes-check) The slow packages each have a lane of their own and "rest" holds every other package. The browser tests (files built only with -tags browser) have lanes of their own, BROWSER_LANES, which build with BROWSER_TAGS and run only those tests; the browser is RASTRILLO_CHROME, the Chromium scripts/ci-box.py pins. CI runs the lanes side by side as the shards of one step, .amadan/ci.d/20-check@N: amadan runs separate steps one after another, and a step's @N shards are how it runs work in parallel. A lane's packages 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 : s 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 every time, and why. Timing budgets (.rastrillo/budgets.txt) are judged only where EQUIPO_CI_DEDICATED=1, a runner with nothing else on it. On a shared runner the times are reported and do not fail the step; size budgets are enforced everywhere by make budget. """ import os import re import shlex import subprocess import sys import tempfile import threading import time from concurrent.futures import ThreadPoolExecutor MODULE = "amadan.net/oficina/equipo" TAGS = "testbuild" BROWSER_TAGS = "browser,testbuild" TIMEOUT = "15m" # Lane order is the shard index: shard 0 runs the first lane. After the # lanes come EXTRA_SHARDS. Keep the count in .amadan/ci.d/20-check@N equal # to the number of lanes plus the extra shards. # # A lane is (name, packages, tests). With tests, the lane runs only those # of its one package: "TestX" is a test, "TestX/name" one of its subtests, # and anything starting with ^ is a regular expression over test names. # A lane of the same package without tests runs everything the others do # not name, so a new test always lands somewhere. Split a package when its # lane is the slowest shard, by the times its shard prints. The seconds # beside each lane are its tests' time on a cold run on a 32 CPU hosted # machine (2026-11-12, every shard started on an empty cache); a shard # takes about 3 s more, and a LATE one its wait too. `scripts/ci-test.py # check` (make lanes-check, in the static checks) fails when a lane names # a test or package that does not exist, two lanes take the same test, or # a package lacks the lane that runs what the others do not name. HEADLESS, RUNNER, EQUIPOTEST, THINTEST = "./internal/headless", "./internal/runner", "./internal/equipotest", "./internal/thintest" LANES = [ ("headless-work", [HEADLESS], ["TestHeadless/4c_rebase", "TestHeadless/4b_ask", "TestHeadless/4c_checks_card", "TestHeadless/4_step_crash"]), # 75 ("headless-review", [HEADLESS], ["TestHeadless/4_review", "TestHeadless/2b_access", "TestHeadless/runner_crash", "TestHeadless/2b_first_message", "TestHeadless/4_checks_honest", "TestHeadless/7_stream_resume", "TestHeadless/2b_notebook", "TestHeadless/2b_move_in", "TestHeadless/2b_desk_failure", "TestHeadless/cancel"]), # 76 ("headless-connections", [HEADLESS], ["TestHeadlessConnections", "TestHeadlessTokenPasteEndToEnd", "TestHeadlessTokenConnection"]), # 76 without the quarantined ("headless-mac", [HEADLESS], ["TestMacWorker", "TestHeadlessAttachments", "TestHeadlessPrewarm", "TestHeadless/1_first_token", "TestHeadless/6_quick_messages", "TestHeadless/8_instance_restart", "TestHeadless/3_runner_offline"]), # 77 ("headless-guards", [HEADLESS], ["TestHeadlessCopyRotation", "TestHeadlessPolicyGuards", "TestHeadlessRunnerKillLeavesNoCopies", "TestHeadlessNewHouseRuleStartsFresh", "TestHeadless/3_engineering", "TestHeadless/3_step_cancel", "TestHeadless/3_step_contained", "TestHeadless/3_step_refused", "TestHeadless/3_empty_repo", "TestHeadless/3_empty_engineering", "TestHeadless/3_empty_merge", "TestHeadless/3_empty_merge_rebuilt", "TestHeadless/3_empty_fix_round"]), # 76 # TestHeadlessAssistant (18 s on a shared 16 CPU box, 2026-11-13; its # quick_website runs only where the site hosts are set) stays here: # the lane was 115 s on that box with it, about 70 s hosted. ("headless-rest", [HEADLESS], None), # 67: the rest of TestHeadless, the Assistant, Research, batching and the small ones # thintest's pages, Research and triage tests (every test but # TestContract*) take the Assistant's contract tests too, so the # other contract tests have the package's rest lane: 102 s and 93 s # on a shared 16 CPU box (2026-11-13), about a minute each hosted. ("thintest", [THINTEST], ["^Test([^C]|C[^o]|Co[^n]|Con[^t])", "^TestContract(Assistant|Outcome|Team|Handoff|HostAllowlist|HostIsPerPerson|Look|Use[A-Z]|RemoteCall|LanesRunAtOnce|NoMergeQuestionWhenGateMerges|PreviewHeldUntilPublishAnswer|PreviewNotHeldBelow19|PublishNeedsOwnerAnswer)"]), # 48 + the Assistant's ("thintest-contract", [THINTEST], None), # 57: every other contract test, and any new one ("runner-thin", ["./internal/runner/thin"], None), # 54 ("runner-bug", [RUNNER], ["TestDirectBugWorkflow", "TestEnrolKeepsTheRole"]), # 47 ("runner-plans", [RUNNER], ["TestPlanWorkflowCandidateOrder", "TestPlanWorkflowFeature", "TestCoordinatorRecoveryCallRefusalKeepsServing", "TestCoordinatorRefusalMatrix"]), # 51 ("runner-rest", [RUNNER], None), # 34 # equipotest's long tests call t.Parallel and wait together at the # end, about 15 s; a lane is its serial tests plus that wait. ("equipotest-a", [EQUIPOTEST], ["^Test[A-D]", "^TestQ"]), # 36 serial ("equipotest-e", [EQUIPOTEST], ["^Test[E-P]"]), # 39 serial ("equipotest-r", [EQUIPOTEST], ["^TestR"]), # 42 serial ("equipotest-rest", [EQUIPOTEST], None), # 40 serial ("plan3test", ["./internal/plan3test"], None), # 41 ("rest", None, None), # every package no other lane names ] # The browser tests: what -tags browser adds to a package's tests, found # by comparing go list with and without the tag, so a new browser test # always runs. Lanes as above, after them in shard order: a lane that # names tests runs those of its one package; one that names none runs # the package's other browser tests; packages None is every package with # browser tests that no other browser lane names. Each test drives one # headless Chromium against its own instance, one test at a time (none # calls t.Parallel), so a lane is one browser; the lanes run side by side. # The browser tests wait on the page with short deadlines, so none of # these is LATE. BROWSER_LANES = [ ("browser-headless-chat", [HEADLESS], ["TestBrowserChat", "TestBrowserChatSendStaysOnPage", "TestBrowserComposer", "TestBrowserComposerReconcile", "TestBrowserComposerFocus", "TestBrowserComposerDock", "TestBrowserDraftStreamsFormatted", "TestBrowserDraftIsTheMessage"]), # 79 ("browser-headless-work", [HEADLESS], ["TestBrowserTaskCard", "TestBrowserReceiptFollowsReview", "TestBrowserRailFollowsWork", "TestBrowserTaskThread", "TestBrowserAskAfterMerge", "TestBrowserReceiptsDesktop", "TestBrowserReceiptsTouch"]), # 79 ("browser-headless-connections", [HEADLESS], ["^TestBrowserConnections", "TestBrowserPasteBox", "TestBrowserPasteCopiesItsBox"]), # 77 ("browser-headless-rest", [HEADLESS], None), # 79: thinking and cards, moving in, the notebook, any new one ("browser-rest", None, None), # 92: thintest's (91), plan3test's and any new package's ] # Shards after the lanes: work that is not a lane of packages but runs # beside them, each a list of make targets run in order. The static # checks are here too: hosted CI runs steps one after another and only # shards side by side, so a lint step of its own would only add its time. EXTRA_SHARDS = [ ["test-quarantine"], ["runner-host"], ["runner-dead-references", "lanes-check", "build", "vet", "fmt-check", "spacing", "budget", "migration-check"], ["staticcheck"], ["govulncheck"], ["gitleaks"], ] # Packages whose results must never come from the cache, with the reason. # They run with -count=1 inside their lane. UNCACHED = {} # Programs outside the module that tests run. Their resolved path, size # and modification time go into EQUIPO_TEST_TOOLS, which testci.Tools # reads, so upgrading one reruns the tests that use it. Keep this list # the same as fingerprinted in internal/testci. TEST_TOOLS = ["bwrap", "claude", "codex", "git", "gofmt", "python3", "sh", "srt", "tar"] # Directories of pinned programs tests run by path; every file counts. # The pinned Pi (EQUIPO_PI_ROOT) counts by its top level: node, pi and the # pinned- stamp the CI box writes beside them. TEST_TOOL_DIRS = {"try-bin": "~/.local/share/equipo/try/bin", "pi": os.environ.get("EQUIPO_PI_ROOT") or "/opt/equipo-pi", "opencode": os.environ.get("EQUIPO_OPENCODE_ROOT") or "/opt/equipo-opencode"} QUARANTINE = "scripts/ci-quarantine.txt" # The quarantine runs each quarantined test's entries in one go test, the # go tests side by side; more subtests of one test than this are split # into even runs of at most this many (nine TestHeadlessConnections # subtests took 91 to 105 s in one). QUARANTINE_RUN = 5 TEST_FUNC = re.compile(r"^func (Test[A-Za-z0-9_]*)\(\w+ \*testing\.T\)", re.M) # 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 = 10, 10.0 LATE = { "equipotest-a": 30, "equipotest-e": 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__))) def all_packages(): out = subprocess.check_output( ["go", "list", "-tags", TAGS, "-f", "{{.ImportPath}}", "./..."], text=True) return ["." + p[len(MODULE):] for p in out.split()] def lane_packages(name): for lane, packages, _ in LANES: if lane != name: continue if packages is not None: return packages named = {p for _, ps, _ in LANES if ps for p in ps} return [p for p in all_packages() if p not in named] sys.exit(f"ci-test: unknown lane {name!r}; lanes: {', '.join(l for l, _, _ in LANES)}") def test_pattern(tests): """The go test -run or -skip pattern naming exactly tests.""" parts = [] for t in tests: if t.startswith("^"): parts.append(t) else: parts.append("/".join("^" + re.escape(level) + "$" for level in t.split("/"))) return "|".join(parts) def lane_flags(name): """-run for a lane that names tests; -skip, for a lane that does not, of every test the other lanes of its package name.""" for lane, packages, tests in LANES: if lane != name: continue if tests: if packages is None or len(packages) != 1: sys.exit(f"ci-test: lane {name} names tests, so it must name one package") return ["-run", test_pattern(tests)] if packages is None: return [] taken = [t for other, ps, ts in LANES if other != name and ts and ps[0] in packages for t in ts] return ["-skip", test_pattern(taken)] if taken else [] return [] _files = {} def test_files(tags): """{package: (directory, test file names)} as go list sees them with tags.""" if tags not in _files: fmt = "{{.ImportPath}}|{{.Dir}}|{{join .TestGoFiles \" \"}} {{join .XTestGoFiles \" \"}}" out = subprocess.check_output(["go", "list", "-tags", tags, "-f", fmt, "./..."], text=True) found = {} for line in out.splitlines(): path, directory, names = line.split("|", 2) found["." + path[len(MODULE):]] = (directory, set(names.split())) _files[tags] = found return _files[tags] def read_tests(directory, names): """The top-level tests in the named files, and the files' text.""" tests, text = set(), [] for name in sorted(names): with open(os.path.join(directory, name)) as f: text.append(f.read()) tests.update(TEST_FUNC.findall(text[-1])) return tests, "\n".join(text) _browser = None def browser_tests(): """{package: [test, ...]}: the top-level tests that -tags browser adds, from the test files go list names only with BROWSER_TAGS.""" global _browser if _browser is not None: return _browser plain, browser = test_files(TAGS), test_files(BROWSER_TAGS) _browser = {} for package, (directory, names) in sorted(browser.items()): tests, _ = read_tests(directory, names - plain.get(package, ("", set()))[1]) if tests: _browser[package] = sorted(tests) return _browser def is_browser_lane(name): return any(lane == name for lane, _, _ in BROWSER_LANES) def browser_runs(name): """The (package, go test flags) a browser lane runs, one go test each.""" for lane, packages, tests in BROWSER_LANES: if lane != name: continue found = browser_tests() if packages is None: named = {p for _, ps, _ in BROWSER_LANES if ps for p in ps} packages = [p for p in found if p not in named] if tests: if len(packages) != 1: sys.exit(f"ci-test: browser lane {name} names tests, so it must name one package") return [(packages[0], ["-run", test_pattern(tests)])] runs = [] for package in packages: taken = [t for other, ps, ts in BROWSER_LANES if other != name and ts and ps and ps[0] == package for t in ts] flags = ["-run", test_pattern(["^(" + "|".join(found.get(package, [])) + ")$"])] if taken: flags += ["-skip", test_pattern(taken)] if found.get(package): runs.append((package, flags)) return runs sys.exit(f"ci-test: unknown browser lane {name!r}") def lane_problems(lanes, packages, tests, sources, kind="lane"): """What is wrong with one list of lanes, as messages; none when every test of every package runs in exactly one lane. packages is every package these lanes may run, tests {package: top-level tests} and sources {package: its test files' text}, for the subtest names.""" problems = [] rest = [name for name, ps, _ in lanes if ps is None] if len(rest) != 1: problems.append(f"want one {kind} that names no package, for every package the others do not name; have {rest}") named = {} for name, ps, ts in lanes: if ps is None: if ts: problems.append(f"{kind} {name} names tests but no package") continue if ts and len(ps) != 1: problems.append(f"{kind} {name} names tests, so it must name one package, not {ps}") for p in ps: if p not in packages: problems.append(f"{kind} {name}: no package {p} (renamed or deleted?)") named.setdefault(p, []).append((name, ts)) claims = {} # (package, test) -> [(lane, subtest or None)] for p, entries in sorted(named.items()): whole = [name for name, ts in entries if not ts] if len(whole) != 1: problems.append(f"{p}: want one {kind} that names no tests and runs what the others do not; have {whole}") for name, ts in entries: for t in ts or []: if t.startswith("^"): try: found = [x for x in tests.get(p, []) if re.search(t, x)] except re.error as e: problems.append(f"{kind} {name}: {t}: {e}") continue sub = None else: top, _, sub = t.partition("/") found = [top] if top in tests.get(p, []) else [] if found and sub and f'"{sub}"' not in sources.get(p, ""): problems.append(f"{kind} {name}: {p} has no subtest {sub!r} of {top}") if not found: problems.append(f"{kind} {name}: {t} names no test in {p}") for x in found: claims.setdefault((p, x), []).append((name, sub or None)) for (p, x), by in sorted(claims.items()): whole, lanes_of = {name for name, sub in by if sub is None}, {name for name, _ in by} if whole and len(lanes_of) > 1: parts = [", ".join(sorted(whole)) + " whole"] + ([", ".join(sorted(lanes_of - whole)) + " some of it"] if lanes_of - whole else []) problems.append(f"{p} {x} runs in more than one {kind}: {'; '.join(parts)}") for sub in sorted({sub for _, sub in by if sub}): lanes_of = sorted({name for name, s in by if s == sub}) if len(lanes_of) > 1: problems.append(f"{p} {x}/{sub} runs in more than one {kind}: {', '.join(lanes_of)}") return problems def check_lanes(): """make lanes-check: every test of every package runs in exactly one lane, and 20-check@N has a shard for each lane and extra shard.""" plain, tagged = test_files(TAGS), test_files(BROWSER_TAGS) tests, sources = {}, {} for p, (directory, names) in tagged.items(): _, text = read_tests(directory, names) sources[p] = text tests[p], _ = read_tests(directory, plain.get(p, ("", set()))[1]) browser = browser_tests() problems = lane_problems(LANES, set(plain), tests, sources) problems += lane_problems(BROWSER_LANES, set(browser), browser, sources, "browser lane") # A browser lane's -run would also take a plain test of the name; that # test already runs in its own lane. for name, ps, ts in BROWSER_LANES: for t in ts or []: top = t if t.startswith("^") else "^" + re.escape(t.partition("/")[0]) + "$" for x in tests.get(ps[0] if ps else "", []): if re.search(top, x): problems.append(f"browser lane {name}: {t} also takes {x}, which is not a browser test") names = all_lanes() problems += [f"two lanes are called {n}" for n in sorted({n for n in names if names.count(n) > 1})] steps = [n for n in os.listdir(os.path.join(root(), ".amadan", "ci.d")) if n.startswith("20-check@")] want = f"20-check@{len(names) + len(EXTRA_SHARDS)}" if steps != [want]: problems.append(f".amadan/ci.d has {steps}; {len(names)} lanes and {len(EXTRA_SHARDS)} extra shards need {want}") for p in problems: print("lanes: " + p) if problems: return 1 print(f"lanes: {len(LANES)} lanes and {len(BROWSER_LANES)} browser lanes run every test once; {want}") return 0 def all_lanes(): return [lane for lane, _, _ in LANES + BROWSER_LANES] def fingerprint(): lines = [] for tool in TEST_TOOLS: path = shutil_which(tool) if path is None: lines.append(f"{tool} missing") continue real = os.path.realpath(path) st = os.stat(real) lines.append(f"{tool} {real} {st.st_size} {st.st_mtime_ns}") for name, path in sorted(TEST_TOOL_DIRS.items()): path = os.path.expanduser(path) files = sorted(os.listdir(path)) if os.path.isdir(path) else [] for f in files: st = os.stat(os.path.join(path, f)) lines.append(f"{name} {f} {st.st_size} {st.st_mtime_ns}") if not files: lines.append(f"{name} missing") return "; ".join(lines) def shutil_which(tool): for d in os.environ.get("PATH", "").split(os.pathsep): p = os.path.join(d, tool) if os.path.isfile(p) and os.access(p, os.X_OK): return p return None def environment(quarantine): env = dict(os.environ) env["EQUIPO_TEST_TOOLS"] = fingerprint() if quarantine: env.pop("EQUIPO_QUARANTINE", None) else: env["EQUIPO_QUARANTINE"] = "skip" return env def budget_env(env): """Judge timing only on a dedicated runner; report it elsewhere.""" if env.get("EQUIPO_CI_DEDICATED") == "1": print("timing budgets: enforced (EQUIPO_CI_DEDICATED=1)", flush=True) return env print("timing budgets: reported, not enforced: a shared runner's load is not this " "change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)", flush=True) env = dict(env) env.pop("AMADAN_CI", None) env.pop("CI", None) return env def rastrillo(): return shlex.split(os.environ.get( "RASTRILLO", "go run amadan.net/rastrillo/rastrillo/cmd/rastrillo")) def budget_test(packages, env, lane, flags=(), tags=TAGS): """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] for group, extra in ((cached, []), (uncached, ["-count=1"])): if not group: continue for p in group if extra else []: print(f"uncached: {p}: {UNCACHED[p]}", flush=True) 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. 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, 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: "): sys.stderr.write(line) continue m = re.match(r"testcache: (\S+): (.*)", line.strip()) # "test output not found" is go finding the test it ran before with # different inputs. A test it has never run, or one it is about to # replay after all, says only "input list not found": not printed. 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) copier.join() return p.wait(), "".join(printed) def run_lane(name): if is_browser_lane(name): return run_browser_lane(name) packages = lane_packages(name) print(f"test lane {name}: {' '.join(packages)}", flush=True) return budget_test(packages, budget_env(environment(False)), name, lane_flags(name)) def browser_version(env): """Print which browser the tests will find; a launcher that does not start (a library missing from the pinned tree) fails here, by name, and not in every test. Returns whether it started.""" chrome = env.get("RASTRILLO_CHROME") if not chrome: print("browser: RASTRILLO_CHROME unset; harness.ChromePath looks for a chromium on PATH", flush=True) return True try: out = subprocess.run([chrome, "--version"], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, timeout=60, errors="replace") except (OSError, subprocess.TimeoutExpired) as e: print(f"browser: {chrome} did not start: {e}", flush=True) return False print(f"browser: {chrome}: {out.stdout.strip()}", flush=True) return out.returncode == 0 def run_browser_lane(name, env=None): env = env or budget_env(environment(False)) if not browser_version(env): return 1 status = 0 runs = browser_runs(name) if not runs: print(f"browser lane {name}: no browser tests", flush=True) for package, flags in runs: print(f"browser lane {name}: {package}", flush=True) status = budget_test([package], env, name, flags, BROWSER_TAGS) or status return status def run_all(): env = budget_env(environment(False)) if not UNCACHED: # One go test over ./... lets rastrillo also flag a stale time record. base = ["-tags", TAGS, "-timeout", TIMEOUT] status = run_retrying(rastrillo() + ["budget", "test"] + base + ["./..."], env, "all", base) else: status = budget_test(all_packages(), env, "all") for name, _, _ in BROWSER_LANES: status = run_browser_lane(name, env) or status return status 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 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", "", "./..."], # and the browser lanes' packages, with the browser tests in. ["go", "list", "-export", "-test", "-tags", BROWSER_TAGS, "-f", ""] + sorted(browser_tests())): 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(): """One line on how busy the machine was, for whoever balances the shards or meets a timeout: the load average, and the share of the last minute some task waited for a CPU or for memory.""" parts = [] try: with open("/proc/loadavg") as f: parts.append("load " + f.read().split()[0]) for name in ("cpu", "memory", "io"): with open("/proc/pressure/" + name) as f: parts.append(name + " waiting " + f.readline().split("avg60=")[1].split()[0] + "%") except (OSError, IndexError): pass print(f"machine: {os.cpu_count()} CPUs, " + ", ".join(parts), flush=True) def run_shard(): index = int(os.environ.get("AMADAN_SHARD", "-1")) count = int(os.environ.get("AMADAN_SHARD_COUNT", "0")) lanes = all_lanes() shards = len(lanes) + len(EXTRA_SHARDS) 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] 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(name) machine_load() return status targets = EXTRA_SHARDS[index - len(lanes)] print(f"shard {index}: make {' '.join(targets)}", flush=True) 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 def quarantined(): """(package, test) pairs from the quarantine file.""" entries = [] with open(os.path.join(root(), QUARANTINE)) as f: for number, line in enumerate(f, 1): line = line.strip() if not line or line.startswith("#"): continue fields = line.split(None, 2) if len(fields) < 3 or not fields[0].startswith("./") or not fields[1].startswith("Test"): sys.exit(f"{QUARANTINE}:{number}: want: ./package TestName[/Subtest] reason") entries.append((fields[0], fields[1])) return entries 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, the tests that passed and that failed, and whether the process itself exited 0. A process that exits non-zero has failed whatever its tests printed: a panic in a cleanup or a TestMain that fails comes after every PASS.""" 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+", 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}, code == 0 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: # The process failed and no test says why: none of them passed. passed, failed = set(), set(tests) return shlex.join(cmd), out, passed, failed, code == 0 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, result="FAIL"): """How long test's failed attempt took, from go test's own FAIL line (or, with result PASS, how long its pass took).""" m = re.search(r"^\s*--- " + result + r": " + 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 and each retry's process exited 0.""" 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, clean = go_test(package, tests, env, base) print(f"+ {cmd} (retry, once)", flush=True) twice = [] for t in tests or [WHOLE]: # Green needs both: the retry's process exited 0, and this test passed. if clean and 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, tags=TAGS): """Run one top-level test's quarantined entries; retry failures once.""" report = [] base = ["-tags", tags, "-timeout", TIMEOUT] started = time.time() cmd, out, passed, failed, _ = go_test(package, tests, env, base, fresh=False) report.append(f"+ {cmd} ({time.time() - started:.0f}s)") missing = set(tests) - passed - failed flaky, broken = [], sorted(missing) for t in sorted(missing): report.append(f"QUARANTINE NOT RUN {package} {t}: no PASS or FAIL line (renamed or skipped?)") if failed: report.append(f"first attempt failed: {' '.join(sorted(failed))}; output tail:") report.append(tail(out)) load = load_average() retry_cmd, retry_out, retry_passed, retry_failed, clean = go_test(package, sorted(failed), env, base) report.append(f"+ {retry_cmd} (retry, once)") for t in sorted(failed): if clean and t in retry_passed and t not in retry_failed: flaky.append(t) 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") if any(t in broken for t in failed): report.append(tail(retry_out)) for t in sorted(passed - failed): report.append(f"ok {package} {t} {failed_seconds(out, t, 'PASS')}") return report, flaky, broken def run_quarantine(): env = environment(True) 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) browser = browser_tests() def tags(package, top): return BROWSER_TAGS if top in browser.get(package, []) else TAGS runs = [] for (p, top), tests in sorted(groups.items()): tests = sorted(tests) size = -(-len(tests) // -(-len(tests) // QUARANTINE_RUN)) runs += [(p, top, tests[i:i + size]) for i in range(0, len(tests), size)] with ThreadPoolExecutor(max_workers=max(1, len(runs))) as pool: futures = [pool.submit(run_group, p, tests, env, tags(p, top)) for p, top, tests in runs] results = [f.result() for f in futures] flakes, broken = [], [] for report, flaky, bad in results: print("\n".join(report), flush=True) flakes += flaky broken += bad print(f"quarantine: {len(flakes)} flaked (passed on the retry), {len(broken)} failed", flush=True) for t in flakes: print(f"quarantine flake: {t}") return 1 if broken else 0 def main(argv): os.chdir(root()) if argv == ["all"]: return run_all() if len(argv) == 2 and argv[0] == "lane": return run_lane(argv[1]) if argv == ["shard"]: return run_shard() if argv == ["compile"]: 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))) for name, _, _ in BROWSER_LANES: for package, flags in browser_runs(name): print(name + ": -tags " + BROWSER_TAGS + " " + " ".join([package] + [shlex.quote(f) for f in flags])) return 0 if argv == ["check"]: return check_lanes() if argv == ["browser"]: for package, tests in browser_tests().items(): print(package + ": " + " ".join(tests)) return 0 print(__doc__, file=sys.stderr) return 2 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))