oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Run the test suite, one lane of it, or the quarantined flaky tests.
3
4 scripts/ci-test.py all every lane in one go test (make test)
5 scripts/ci-test.py lane NAME one lane (make test-lane LANE=NAME)
6 scripts/ci-test.py shard the shard AMADAN_SHARD names (make ci-shard)
7 scripts/ci-test.py quarantine the quarantined tests (make test-quarantine)
8 scripts/ci-test.py compile compile every package once (make ci-compile)
9 scripts/ci-test.py retried LANE ARGS... go test ARGS, with the one retry
10 scripts/ci-test.py lanes print each lane and its packages
11 scripts/ci-test.py browser print each package's browser tests
12 scripts/ci-test.py check every test in exactly one lane (make lanes-check)
13
14The slow packages each have a lane of their own and "rest" holds every
15other package. The browser tests (files built only with -tags browser)
16have lanes of their own, BROWSER_LANES, which build with BROWSER_TAGS
17and run only those tests; the browser is RASTRILLO_CHROME, the Chromium
18scripts/ci-box.py pins. CI runs the lanes side by side as the shards of one step,
19.amadan/ci.d/20-check@N: amadan runs separate steps one after another, and
20a step's @N shards are how it runs work in parallel. A lane's packages
21pass or fail in that shard's own log. The quarantine, the runner host
22checks (make runner-host) and the static checks are shards of the same
23step, after the lanes.
24
25A failed test is retried once, where it failed, and a pass on the retry
26is a flake: the step stays green and prints one line,
27
28 FLAKE <package>:<test> <lane> <commit> <seconds>s <load>
29
30with the time the failed attempt took and the machine's load average when
31it failed. Red means the test failed twice. scripts/ci-flakes.py reads
32those lines back from CI and names the tests that keep flaking.
33
34Results are cached: go test replays a pass for a package whose test
35binary, declared files and environment are unchanged (internal/testci
36covers the inputs go test cannot see). UNCACHED lists what must run
37every time, and why.
38
39Timing budgets (.rastrillo/budgets.txt) are judged only where
40EQUIPO_CI_DEDICATED=1, a runner with nothing else on it. On a shared
41runner the times are reported and do not fail the step; size budgets are
42enforced everywhere by make budget.
43"""
44import os
45import re
46import shlex
47import subprocess
48import sys
49import tempfile
50import threading
51import time
52from concurrent.futures import ThreadPoolExecutor
53
54MODULE = "amadan.net/oficina/equipo"
55TAGS = "testbuild"
56BROWSER_TAGS = "browser,testbuild"
57TIMEOUT = "15m"
58
59# Lane order is the shard index: shard 0 runs the first lane. After the
60# lanes come EXTRA_SHARDS. Keep the count in .amadan/ci.d/20-check@N equal
61# to the number of lanes plus the extra shards.
62#
63# A lane is (name, packages, tests). With tests, the lane runs only those
64# of its one package: "TestX" is a test, "TestX/name" one of its subtests,
65# and anything starting with ^ is a regular expression over test names.
66# A lane of the same package without tests runs everything the others do
67# not name, so a new test always lands somewhere. Split a package when its
68# lane is the slowest shard, by the times its shard prints. The seconds
69# beside each lane are its tests' time on a cold run on a 32 CPU hosted
70# machine (2026-11-12, every shard started on an empty cache); a shard
71# takes about 3 s more, and a LATE one its wait too. `scripts/ci-test.py
72# check` (make lanes-check, in the static checks) fails when a lane names
73# a test or package that does not exist, two lanes take the same test, or
74# a package lacks the lane that runs what the others do not name.
75HEADLESS, RUNNER, EQUIPOTEST, THINTEST = "./internal/headless", "./internal/runner", "./internal/equipotest", "./internal/thintest"
76LANES = [
77 ("headless-work", [HEADLESS], ["TestHeadless/4c_rebase", "TestHeadless/4b_ask", "TestHeadless/4c_checks_card", "TestHeadless/4_step_crash"]), # 75
78 ("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
79 ("headless-connections", [HEADLESS], ["TestHeadlessConnections", "TestHeadlessTokenPasteEndToEnd", "TestHeadlessTokenConnection"]), # 76 without the quarantined
80 ("headless-mac", [HEADLESS], ["TestMacWorker", "TestHeadlessAttachments", "TestHeadlessPrewarm", "TestHeadless/1_first_token", "TestHeadless/6_quick_messages", "TestHeadless/8_instance_restart", "TestHeadless/3_runner_offline"]), # 77
81 ("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
82 # TestHeadlessAssistant (18 s on a shared 16 CPU box, 2026-11-13; its
83 # quick_website runs only where the site hosts are set) stays here:
84 # the lane was 115 s on that box with it, about 70 s hosted.
85 ("headless-rest", [HEADLESS], None), # 67: the rest of TestHeadless, the Assistant, Research, batching and the small ones
86 # thintest's pages, Research and triage tests (every test but
87 # TestContract*) take the Assistant's contract tests too, so the
88 # other contract tests have the package's rest lane: 102 s and 93 s
89 # on a shared 16 CPU box (2026-11-13), about a minute each hosted.
90 ("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
91 ("thintest-contract", [THINTEST], None), # 57: every other contract test, and any new one
92 ("runner-thin", ["./internal/runner/thin"], None), # 54
93 ("runner-bug", [RUNNER], ["TestDirectBugWorkflow", "TestEnrolKeepsTheRole"]), # 47
94 ("runner-plans", [RUNNER], ["TestPlanWorkflowCandidateOrder", "TestPlanWorkflowFeature", "TestCoordinatorRecoveryCallRefusalKeepsServing", "TestCoordinatorRefusalMatrix"]), # 51
95 ("runner-rest", [RUNNER], None), # 34
96 # equipotest's long tests call t.Parallel and wait together at the
97 # end, about 15 s; a lane is its serial tests plus that wait.
98 ("equipotest-a", [EQUIPOTEST], ["^Test[A-D]", "^TestQ"]), # 36 serial
99 ("equipotest-e", [EQUIPOTEST], ["^Test[E-P]"]), # 39 serial
100 ("equipotest-r", [EQUIPOTEST], ["^TestR"]), # 42 serial
101 ("equipotest-rest", [EQUIPOTEST], None), # 40 serial
102 ("plan3test", ["./internal/plan3test"], None), # 41
103 ("rest", None, None), # every package no other lane names
104]
105
106# The browser tests: what -tags browser adds to a package's tests, found
107# by comparing go list with and without the tag, so a new browser test
108# always runs. Lanes as above, after them in shard order: a lane that
109# names tests runs those of its one package; one that names none runs
110# the package's other browser tests; packages None is every package with
111# browser tests that no other browser lane names. Each test drives one
112# headless Chromium against its own instance, one test at a time (none
113# calls t.Parallel), so a lane is one browser; the lanes run side by side.
114# The browser tests wait on the page with short deadlines, so none of
115# these is LATE.
116BROWSER_LANES = [
117 ("browser-headless-chat", [HEADLESS], ["TestBrowserChat", "TestBrowserChatSendStaysOnPage", "TestBrowserComposer", "TestBrowserComposerReconcile", "TestBrowserComposerFocus", "TestBrowserComposerDock", "TestBrowserDraftStreamsFormatted", "TestBrowserDraftIsTheMessage"]), # 79
118 ("browser-headless-work", [HEADLESS], ["TestBrowserTaskCard", "TestBrowserReceiptFollowsReview", "TestBrowserRailFollowsWork", "TestBrowserTaskThread", "TestBrowserAskAfterMerge", "TestBrowserReceiptsDesktop", "TestBrowserReceiptsTouch"]), # 79
119 ("browser-headless-connections", [HEADLESS], ["^TestBrowserConnections", "TestBrowserPasteBox", "TestBrowserPasteCopiesItsBox"]), # 77
120 ("browser-headless-rest", [HEADLESS], None), # 79: thinking and cards, moving in, the notebook, any new one
121 ("browser-rest", None, None), # 92: thintest's (91), plan3test's and any new package's
122]
123
124# Shards after the lanes: work that is not a lane of packages but runs
125# beside them, each a list of make targets run in order. The static
126# checks are here too: hosted CI runs steps one after another and only
127# shards side by side, so a lint step of its own would only add its time.
128EXTRA_SHARDS = [
129 ["test-quarantine"],
130 ["runner-host"],
131 ["runner-dead-references", "lanes-check", "build", "vet", "fmt-check", "spacing", "budget", "migration-check"],
132 ["staticcheck"],
133 ["govulncheck"],
134 ["gitleaks"],
135]
136
137# Packages whose results must never come from the cache, with the reason.
138# They run with -count=1 inside their lane.
139UNCACHED = {}
140
141# Programs outside the module that tests run. Their resolved path, size
142# and modification time go into EQUIPO_TEST_TOOLS, which testci.Tools
143# reads, so upgrading one reruns the tests that use it. Keep this list
144# the same as fingerprinted in internal/testci.
145TEST_TOOLS = ["bwrap", "claude", "codex", "git", "gofmt", "python3", "sh", "srt", "tar"]
146# Directories of pinned programs tests run by path; every file counts.
147# The pinned Pi (EQUIPO_PI_ROOT) counts by its top level: node, pi and the
148# pinned-<tree digest> stamp the CI box writes beside them.
149TEST_TOOL_DIRS = {"try-bin": "~/.local/share/equipo/try/bin", "pi": os.environ.get("EQUIPO_PI_ROOT") or "/opt/equipo-pi",
150 "opencode": os.environ.get("EQUIPO_OPENCODE_ROOT") or "/opt/equipo-opencode"}
151
152QUARANTINE = "scripts/ci-quarantine.txt"
153# The quarantine runs each quarantined test's entries in one go test, the
154# go tests side by side; more subtests of one test than this are split
155# into even runs of at most this many (nine TestHeadlessConnections
156# subtests took 91 to 105 s in one).
157QUARANTINE_RUN = 5
158
159TEST_FUNC = re.compile(r"^func (Test[A-Za-z0-9_]*)\(\w+ \*testing\.T\)", re.M)
160
161# More failures than this in one lane is a broken change, not a flake:
162# nothing is retried and the lane is red.
163RETRY_LIMIT = 10
164
165# The shards of a step all start at once on one machine. On an empty
166# cache that was 24 go builds on 32 CPUs, a load near 100 for the whole
167# step, and tests with a 45 second wait in them timed out (the first
168# token, the transfer, containment proofs). Three things keep it down.
169#
170# The compile step builds what shards would otherwise each build: the test
171# packages and the tools (run_compile, make ci-compile).
172#
173# Each shard's go commands run at most BUILD_JOBS actions at once (go's
174# -p, 32 by default here); the static checks, which only compute, also
175# keep to CHECK_CPUS threads.
176#
177# The shards named in LATE start after the load-sensitive lanes are under
178# way: they wait SETTLE seconds, then until tasks have waited for a CPU
179# less than BUSY percent of the last ten seconds, LATE seconds at most. A
180# warm run is never busy, so there it costs SETTLE seconds of shards that
181# finish early anyway. A late shard is named by its lane, or by its first
182# make target.
183BUILD_JOBS = 8
184BUILD_JOBS_MANY = 16 # for the lane of many small packages, where -p is also how many test at once
185CHECK_CPUS = 8
186SETTLE, BUSY = 10, 10.0
187LATE = {
188 "equipotest-a": 30, "equipotest-e": 30, "equipotest-r": 30, "equipotest-rest": 30,
189 "plan3test": 30, "rest": 30,
190 "runner-dead-references": 30, "staticcheck": 30, "govulncheck": 30, "gitleaks": 30,
191}
192
193
194def root():
195 return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
196
197
198def all_packages():
199 out = subprocess.check_output(
200 ["go", "list", "-tags", TAGS, "-f", "{{.ImportPath}}", "./..."], text=True)
201 return ["." + p[len(MODULE):] for p in out.split()]
202
203
204def lane_packages(name):
205 for lane, packages, _ in LANES:
206 if lane != name:
207 continue
208 if packages is not None:
209 return packages
210 named = {p for _, ps, _ in LANES if ps for p in ps}
211 return [p for p in all_packages() if p not in named]
212 sys.exit(f"ci-test: unknown lane {name!r}; lanes: {', '.join(l for l, _, _ in LANES)}")
213
214
215def test_pattern(tests):
216 """The go test -run or -skip pattern naming exactly tests."""
217 parts = []
218 for t in tests:
219 if t.startswith("^"):
220 parts.append(t)
221 else:
222 parts.append("/".join("^" + re.escape(level) + "$" for level in t.split("/")))
223 return "|".join(parts)
224
225
226def lane_flags(name):
227 """-run for a lane that names tests; -skip, for a lane that does not,
228 of every test the other lanes of its package name."""
229 for lane, packages, tests in LANES:
230 if lane != name:
231 continue
232 if tests:
233 if packages is None or len(packages) != 1:
234 sys.exit(f"ci-test: lane {name} names tests, so it must name one package")
235 return ["-run", test_pattern(tests)]
236 if packages is None:
237 return []
238 taken = [t for other, ps, ts in LANES if other != name and ts and ps[0] in packages for t in ts]
239 return ["-skip", test_pattern(taken)] if taken else []
240 return []
241
242
243_files = {}
244
245
246def test_files(tags):
247 """{package: (directory, test file names)} as go list sees them with tags."""
248 if tags not in _files:
249 fmt = "{{.ImportPath}}|{{.Dir}}|{{join .TestGoFiles \" \"}} {{join .XTestGoFiles \" \"}}"
250 out = subprocess.check_output(["go", "list", "-tags", tags, "-f", fmt, "./..."], text=True)
251 found = {}
252 for line in out.splitlines():
253 path, directory, names = line.split("|", 2)
254 found["." + path[len(MODULE):]] = (directory, set(names.split()))
255 _files[tags] = found
256 return _files[tags]
257
258
259def read_tests(directory, names):
260 """The top-level tests in the named files, and the files' text."""
261 tests, text = set(), []
262 for name in sorted(names):
263 with open(os.path.join(directory, name)) as f:
264 text.append(f.read())
265 tests.update(TEST_FUNC.findall(text[-1]))
266 return tests, "\n".join(text)
267
268
269_browser = None
270
271
272def browser_tests():
273 """{package: [test, ...]}: the top-level tests that -tags browser adds,
274 from the test files go list names only with BROWSER_TAGS."""
275 global _browser
276 if _browser is not None:
277 return _browser
278 plain, browser = test_files(TAGS), test_files(BROWSER_TAGS)
279 _browser = {}
280 for package, (directory, names) in sorted(browser.items()):
281 tests, _ = read_tests(directory, names - plain.get(package, ("", set()))[1])
282 if tests:
283 _browser[package] = sorted(tests)
284 return _browser
285
286
287def is_browser_lane(name):
288 return any(lane == name for lane, _, _ in BROWSER_LANES)
289
290
291def browser_runs(name):
292 """The (package, go test flags) a browser lane runs, one go test each."""
293 for lane, packages, tests in BROWSER_LANES:
294 if lane != name:
295 continue
296 found = browser_tests()
297 if packages is None:
298 named = {p for _, ps, _ in BROWSER_LANES if ps for p in ps}
299 packages = [p for p in found if p not in named]
300 if tests:
301 if len(packages) != 1:
302 sys.exit(f"ci-test: browser lane {name} names tests, so it must name one package")
303 return [(packages[0], ["-run", test_pattern(tests)])]
304 runs = []
305 for package in packages:
306 taken = [t for other, ps, ts in BROWSER_LANES if other != name and ts and ps and ps[0] == package for t in ts]
307 flags = ["-run", test_pattern(["^(" + "|".join(found.get(package, [])) + ")$"])]
308 if taken:
309 flags += ["-skip", test_pattern(taken)]
310 if found.get(package):
311 runs.append((package, flags))
312 return runs
313 sys.exit(f"ci-test: unknown browser lane {name!r}")
314
315
316def lane_problems(lanes, packages, tests, sources, kind="lane"):
317 """What is wrong with one list of lanes, as messages; none when every
318 test of every package runs in exactly one lane. packages is every
319 package these lanes may run, tests {package: top-level tests} and
320 sources {package: its test files' text}, for the subtest names."""
321 problems = []
322 rest = [name for name, ps, _ in lanes if ps is None]
323 if len(rest) != 1:
324 problems.append(f"want one {kind} that names no package, for every package the others do not name; have {rest}")
325 named = {}
326 for name, ps, ts in lanes:
327 if ps is None:
328 if ts:
329 problems.append(f"{kind} {name} names tests but no package")
330 continue
331 if ts and len(ps) != 1:
332 problems.append(f"{kind} {name} names tests, so it must name one package, not {ps}")
333 for p in ps:
334 if p not in packages:
335 problems.append(f"{kind} {name}: no package {p} (renamed or deleted?)")
336 named.setdefault(p, []).append((name, ts))
337 claims = {} # (package, test) -> [(lane, subtest or None)]
338 for p, entries in sorted(named.items()):
339 whole = [name for name, ts in entries if not ts]
340 if len(whole) != 1:
341 problems.append(f"{p}: want one {kind} that names no tests and runs what the others do not; have {whole}")
342 for name, ts in entries:
343 for t in ts or []:
344 if t.startswith("^"):
345 try:
346 found = [x for x in tests.get(p, []) if re.search(t, x)]
347 except re.error as e:
348 problems.append(f"{kind} {name}: {t}: {e}")
349 continue
350 sub = None
351 else:
352 top, _, sub = t.partition("/")
353 found = [top] if top in tests.get(p, []) else []
354 if found and sub and f'"{sub}"' not in sources.get(p, ""):
355 problems.append(f"{kind} {name}: {p} has no subtest {sub!r} of {top}")
356 if not found:
357 problems.append(f"{kind} {name}: {t} names no test in {p}")
358 for x in found:
359 claims.setdefault((p, x), []).append((name, sub or None))
360 for (p, x), by in sorted(claims.items()):
361 whole, lanes_of = {name for name, sub in by if sub is None}, {name for name, _ in by}
362 if whole and len(lanes_of) > 1:
363 parts = [", ".join(sorted(whole)) + " whole"] + ([", ".join(sorted(lanes_of - whole)) + " some of it"] if lanes_of - whole else [])
364 problems.append(f"{p} {x} runs in more than one {kind}: {'; '.join(parts)}")
365 for sub in sorted({sub for _, sub in by if sub}):
366 lanes_of = sorted({name for name, s in by if s == sub})
367 if len(lanes_of) > 1:
368 problems.append(f"{p} {x}/{sub} runs in more than one {kind}: {', '.join(lanes_of)}")
369 return problems
370
371
372def check_lanes():
373 """make lanes-check: every test of every package runs in exactly one
374 lane, and 20-check@N has a shard for each lane and extra shard."""
375 plain, tagged = test_files(TAGS), test_files(BROWSER_TAGS)
376 tests, sources = {}, {}
377 for p, (directory, names) in tagged.items():
378 _, text = read_tests(directory, names)
379 sources[p] = text
380 tests[p], _ = read_tests(directory, plain.get(p, ("", set()))[1])
381 browser = browser_tests()
382 problems = lane_problems(LANES, set(plain), tests, sources)
383 problems += lane_problems(BROWSER_LANES, set(browser), browser, sources, "browser lane")
384 # A browser lane's -run would also take a plain test of the name; that
385 # test already runs in its own lane.
386 for name, ps, ts in BROWSER_LANES:
387 for t in ts or []:
388 top = t if t.startswith("^") else "^" + re.escape(t.partition("/")[0]) + "$"
389 for x in tests.get(ps[0] if ps else "", []):
390 if re.search(top, x):
391 problems.append(f"browser lane {name}: {t} also takes {x}, which is not a browser test")
392 names = all_lanes()
393 problems += [f"two lanes are called {n}" for n in sorted({n for n in names if names.count(n) > 1})]
394 steps = [n for n in os.listdir(os.path.join(root(), ".amadan", "ci.d")) if n.startswith("20-check@")]
395 want = f"20-check@{len(names) + len(EXTRA_SHARDS)}"
396 if steps != [want]:
397 problems.append(f".amadan/ci.d has {steps}; {len(names)} lanes and {len(EXTRA_SHARDS)} extra shards need {want}")
398 for p in problems:
399 print("lanes: " + p)
400 if problems:
401 return 1
402 print(f"lanes: {len(LANES)} lanes and {len(BROWSER_LANES)} browser lanes run every test once; {want}")
403 return 0
404
405
406def all_lanes():
407 return [lane for lane, _, _ in LANES + BROWSER_LANES]
408
409
410def fingerprint():
411 lines = []
412 for tool in TEST_TOOLS:
413 path = shutil_which(tool)
414 if path is None:
415 lines.append(f"{tool} missing")
416 continue
417 real = os.path.realpath(path)
418 st = os.stat(real)
419 lines.append(f"{tool} {real} {st.st_size} {st.st_mtime_ns}")
420 for name, path in sorted(TEST_TOOL_DIRS.items()):
421 path = os.path.expanduser(path)
422 files = sorted(os.listdir(path)) if os.path.isdir(path) else []
423 for f in files:
424 st = os.stat(os.path.join(path, f))
425 lines.append(f"{name} {f} {st.st_size} {st.st_mtime_ns}")
426 if not files:
427 lines.append(f"{name} missing")
428 return "; ".join(lines)
429
430
431def shutil_which(tool):
432 for d in os.environ.get("PATH", "").split(os.pathsep):
433 p = os.path.join(d, tool)
434 if os.path.isfile(p) and os.access(p, os.X_OK):
435 return p
436 return None
437
438
439def environment(quarantine):
440 env = dict(os.environ)
441 env["EQUIPO_TEST_TOOLS"] = fingerprint()
442 if quarantine:
443 env.pop("EQUIPO_QUARANTINE", None)
444 else:
445 env["EQUIPO_QUARANTINE"] = "skip"
446 return env
447
448
449def budget_env(env):
450 """Judge timing only on a dedicated runner; report it elsewhere."""
451 if env.get("EQUIPO_CI_DEDICATED") == "1":
452 print("timing budgets: enforced (EQUIPO_CI_DEDICATED=1)", flush=True)
453 return env
454 print("timing budgets: reported, not enforced: a shared runner's load is not this "
455 "change's time (set EQUIPO_CI_DEDICATED=1 on a dedicated runner)", flush=True)
456 env = dict(env)
457 env.pop("AMADAN_CI", None)
458 env.pop("CI", None)
459 return env
460
461
462def rastrillo():
463 return shlex.split(os.environ.get(
464 "RASTRILLO", "go run amadan.net/rastrillo/rastrillo/cmd/rastrillo"))
465
466
467def budget_test(packages, env, lane, flags=(), tags=TAGS):
468 """One rastrillo budget test over packages, a failed test retried once;
469 returns its exit status."""
470 status = 0
471 cached = [p for p in packages if p not in UNCACHED]
472 uncached = [p for p in packages if p in UNCACHED]
473 for group, extra in ((cached, []), (uncached, ["-count=1"])):
474 if not group:
475 continue
476 for p in group if extra else []:
477 print(f"uncached: {p}: {UNCACHED[p]}", flush=True)
478 base = ["-tags", tags, "-timeout", TIMEOUT] + extra + list(flags)
479 status = run_retrying(rastrillo() + ["budget", "test"] + base + group, env, lane, base) or status
480 return status
481
482
483def run_retrying(cmd, env, lane, base):
484 """Run a rastrillo budget test; retry what failed once, with go test
485 and the flags in base. Returns the exit status after the retry."""
486 print("+ " + " ".join(shlex.quote(c) for c in cmd), flush=True)
487 status, out = run_reporting_misses(cmd, env)
488 if status == 0:
489 return 0
490 return retry_failures(out, env, lane, base)
491
492
493def run_reporting_misses(cmd, env):
494 """Run cmd with go's test cache debugging on, and print one line per
495 package that missed the cache because its inputs changed, instead of
496 go's ID-by-ID trace. Returns the exit status and what cmd printed."""
497 env = dict(env)
498 env["GODEBUG"] = ",".join(filter(None, [env.get("GODEBUG", ""), "gocachetest=1"]))
499 p = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
500 text=True, bufsize=1, errors="replace")
501 printed = []
502
503 def copy():
504 for line in p.stdout:
505 printed.append(line)
506 sys.stdout.write(line)
507 sys.stdout.flush()
508 copier = threading.Thread(target=copy)
509 copier.start()
510 missed = set()
511 for line in p.stderr:
512 if not line.startswith("testcache: "):
513 sys.stderr.write(line)
514 continue
515 m = re.match(r"testcache: (\S+): (.*)", line.strip())
516 # "test output not found" is go finding the test it ran before with
517 # different inputs. A test it has never run, or one it is about to
518 # replay after all, says only "input list not found": not printed.
519 if m and m.group(1) not in missed and m.group(2).startswith("test output not found"):
520 missed.add(m.group(1))
521 print(f"cache miss: {m.group(1)}: its inputs changed", flush=True)
522 copier.join()
523 return p.wait(), "".join(printed)
524
525
526def run_lane(name):
527 if is_browser_lane(name):
528 return run_browser_lane(name)
529 packages = lane_packages(name)
530 print(f"test lane {name}: {' '.join(packages)}", flush=True)
531 return budget_test(packages, budget_env(environment(False)), name, lane_flags(name))
532
533
534def browser_version(env):
535 """Print which browser the tests will find; a launcher that does not
536 start (a library missing from the pinned tree) fails here, by name,
537 and not in every test. Returns whether it started."""
538 chrome = env.get("RASTRILLO_CHROME")
539 if not chrome:
540 print("browser: RASTRILLO_CHROME unset; harness.ChromePath looks for a chromium on PATH", flush=True)
541 return True
542 try:
543 out = subprocess.run([chrome, "--version"], env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
544 text=True, timeout=60, errors="replace")
545 except (OSError, subprocess.TimeoutExpired) as e:
546 print(f"browser: {chrome} did not start: {e}", flush=True)
547 return False
548 print(f"browser: {chrome}: {out.stdout.strip()}", flush=True)
549 return out.returncode == 0
550
551
552def run_browser_lane(name, env=None):
553 env = env or budget_env(environment(False))
554 if not browser_version(env):
555 return 1
556 status = 0
557 runs = browser_runs(name)
558 if not runs:
559 print(f"browser lane {name}: no browser tests", flush=True)
560 for package, flags in runs:
561 print(f"browser lane {name}: {package}", flush=True)
562 status = budget_test([package], env, name, flags, BROWSER_TAGS) or status
563 return status
564
565
566def run_all():
567 env = budget_env(environment(False))
568 if not UNCACHED:
569 # One go test over ./... lets rastrillo also flag a stale time record.
570 base = ["-tags", TAGS, "-timeout", TIMEOUT]
571 status = run_retrying(rastrillo() + ["budget", "test"] + base + ["./..."], env, "all", base)
572 else:
573 status = budget_test(all_packages(), env, "all")
574 for name, _, _ in BROWSER_LANES:
575 status = run_browser_lane(name, env) or status
576 return status
577
578
579def run_retried(lane, args):
580 """go test args through rastrillo, untimed, with the one retry: for the
581 make targets that run go test themselves (runner-host)."""
582 base = [a for a in args if not a.startswith("./")]
583 return run_retrying(rastrillo() + ["budget", "test", "-no-time"] + args, dict(os.environ), lane, base)
584
585
586def run_compile():
587 """Compile every package and its tests, as the lanes build them, and
588 link no test: what stays is the build cache the shards then share.
589 Each shard still links its own test binary."""
590 for cmd in (["go", "build", "-tags", TAGS, "./..."],
591 # -export compiles each package and, with -test, its tests:
592 # the lanes of one package would each compile them again.
593 ["go", "list", "-export", "-test", "-tags", TAGS, "-f", "", "./..."],
594 # and the browser lanes' packages, with the browser tests in.
595 ["go", "list", "-export", "-test", "-tags", BROWSER_TAGS, "-f", ""] + sorted(browser_tests())):
596 print("+ " + " ".join(cmd), flush=True)
597 started = time.time()
598 status = subprocess.call(cmd, stdout=subprocess.DEVNULL)
599 print(f" {time.time() - started:.1f}s", flush=True)
600 if status:
601 return status
602 # The lanes run rastrillo with go run, which keeps the program it
603 # built. What budget size says is the budget target's to judge.
604 subprocess.call(rastrillo() + ["budget", "size"], stdout=subprocess.DEVNULL)
605 return 0
606
607
608def load_average():
609 try:
610 with open("/proc/loadavg") as f:
611 return f.read().split()[0]
612 except (OSError, IndexError):
613 return "unknown"
614
615
616def cpu_waiting():
617 """The share of the last ten seconds some task waited for a CPU."""
618 try:
619 with open("/proc/pressure/cpu") as f:
620 return float(f.readline().split("avg10=")[1].split()[0])
621 except (OSError, IndexError, ValueError):
622 return 0.0
623
624
625def stagger(name):
626 """Start a shard named in LATE once the machine has calmed down."""
627 limit = LATE.get(name)
628 if not limit:
629 return
630 started = time.time()
631 time.sleep(min(SETTLE, limit))
632 while time.time() - started < limit and cpu_waiting() >= BUSY:
633 time.sleep(1)
634 print(f"stagger: {name} started {time.time() - started:.0f}s late; cpu waiting {cpu_waiting():.1f}%, "
635 f"load {load_average()}", flush=True)
636
637
638def machine_load():
639 """One line on how busy the machine was, for whoever balances the
640 shards or meets a timeout: the load average, and the share of the last
641 minute some task waited for a CPU or for memory."""
642 parts = []
643 try:
644 with open("/proc/loadavg") as f:
645 parts.append("load " + f.read().split()[0])
646 for name in ("cpu", "memory", "io"):
647 with open("/proc/pressure/" + name) as f:
648 parts.append(name + " waiting " + f.readline().split("avg60=")[1].split()[0] + "%")
649 except (OSError, IndexError):
650 pass
651 print(f"machine: {os.cpu_count()} CPUs, " + ", ".join(parts), flush=True)
652
653
654def run_shard():
655 index = int(os.environ.get("AMADAN_SHARD", "-1"))
656 count = int(os.environ.get("AMADAN_SHARD_COUNT", "0"))
657 lanes = all_lanes()
658 shards = len(lanes) + len(EXTRA_SHARDS)
659 if count != shards or not 0 <= index < count:
660 sys.exit(f"ci-test: shard {index} of {count}, but there are {len(lanes)} lanes and "
661 f"{len(EXTRA_SHARDS)} extra shards; name the step 20-check@{shards}")
662 name = lanes[index] if index < len(lanes) else EXTRA_SHARDS[index - len(lanes)][0]
663 jobs = BUILD_JOBS_MANY if name == "rest" else BUILD_JOBS
664 os.environ["GOFLAGS"] = " ".join(filter(None, [os.environ.get("GOFLAGS", ""), f"-p={jobs}"]))
665 stagger(name)
666 if index < len(lanes):
667 status = run_lane(name)
668 machine_load()
669 return status
670 targets = EXTRA_SHARDS[index - len(lanes)]
671 print(f"shard {index}: make {' '.join(targets)}", flush=True)
672 env = dict(os.environ)
673 if targets == ["runner-host"]:
674 # runner-host reruns tests the lanes ran; the quarantine shard beside
675 # it is where a quarantined one of them runs.
676 env["EQUIPO_QUARANTINE"] = "skip"
677 elif targets != ["test-quarantine"]:
678 env["GOMAXPROCS"] = str(CHECK_CPUS) # a static check: it only computes
679 status = subprocess.call(["make", "--no-print-directory"] + targets, env=env)
680 machine_load()
681 return status
682
683
684def quarantined():
685 """(package, test) pairs from the quarantine file."""
686 entries = []
687 with open(os.path.join(root(), QUARANTINE)) as f:
688 for number, line in enumerate(f, 1):
689 line = line.strip()
690 if not line or line.startswith("#"):
691 continue
692 fields = line.split(None, 2)
693 if len(fields) < 3 or not fields[0].startswith("./") or not fields[1].startswith("Test"):
694 sys.exit(f"{QUARANTINE}:{number}: want: ./package TestName[/Subtest] reason")
695 entries.append((fields[0], fields[1]))
696 return entries
697
698
699def go_test(package, tests, env, base, fresh=True):
700 """go test -v of tests in package (all of it when tests is empty), with
701 the flags in base. Returns the command, its output, the tests that
702 passed and that failed, and whether the process itself exited 0. A
703 process that exits non-zero has failed whatever its tests printed: a
704 panic in a cleanup or a TestMain that fails comes after every PASS."""
705 cmd = ["go", "test"] + list(base) + ["-v"]
706 if tests:
707 cmd += ["-run", test_pattern(tests)]
708 if fresh:
709 cmd.append("-count=1")
710 cmd.append(package)
711 with tempfile.TemporaryFile("w+", errors="replace") as log:
712 code = subprocess.call(cmd, env=env, stdout=log, stderr=subprocess.STDOUT)
713 log.seek(0)
714 out = log.read()
715 if not tests:
716 return shlex.join(cmd), out, {WHOLE} if code == 0 else set(), set() if code == 0 else {WHOLE}, code == 0
717 passed = {t for t in tests if re.search(r"^\s*--- PASS: " + re.escape(t) + r" \(", out, re.M)}
718 failed = {t for t in tests if re.search(r"^\s*--- FAIL: " + re.escape(t) + r" \(", out, re.M)}
719 if code != 0 and not failed:
720 # The process failed and no test says why: none of them passed.
721 passed, failed = set(), set(tests)
722 return shlex.join(cmd), out, passed, failed, code == 0
723
724
725def tail(text, n=60):
726 return "\n".join(text.splitlines()[-n:])
727
728
729# The one retry, and the FLAKE line.
730
731# What a flake is called when the package failed outside every test.
732WHOLE = "TestMain"
733
734FLAKE = re.compile(r"^FLAKE (\./\S+):(Test\S*) (\S+) ([0-9a-f]{40}|unknown) (\d+(?:\.\d+)?s|unknown) (\d+(?:\.\d+)?|unknown)$", re.M)
735
736
737def commit():
738 """The commit under test: amadan names it, git knows it anywhere else."""
739 named = os.environ.get("AMADAN_COMMIT", "")
740 if re.fullmatch(r"[0-9a-f]{40}", named):
741 return named
742 try:
743 head = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL).strip()
744 except (OSError, subprocess.CalledProcessError):
745 return "unknown"
746 return head if re.fullmatch(r"[0-9a-f]{40}", head) else "unknown"
747
748
749def failed_seconds(out, test, result="FAIL"):
750 """How long test's failed attempt took, from go test's own FAIL line
751 (or, with result PASS, how long its pass took)."""
752 m = re.search(r"^\s*--- " + result + r": " + re.escape(test) + r" \((\d+(?:\.\d+)?)s\)", out, re.M)
753 return m.group(1) + "s" if m else "unknown"
754
755
756def flake_line(package, test, lane, seconds, load):
757 """The one line per flake, with a rule above and below so it is not
758 missed in a log. scripts/ci-flakes.py reads it back (FLAKE above): keep
759 the two in step."""
760 line = f"FLAKE {package}:{test} {lane} {commit()} {seconds} {load}"
761 assert FLAKE.fullmatch(line), line
762 rule = "#" * 78
763 return f"{rule}\n{line}\n{rule}\nfailed, then passed on its one retry: the step stays green and the flake is on record"
764
765
766def failures(out):
767 """What a rastrillo budget test reported as failed: {package: tests},
768 a package that failed outside every test mapped to no tests. Tests
769 that never finished (a timeout, a panic beside them) count as failed."""
770 found = {}
771 for m in re.finditer(r"^--- FAIL (\S+) \(package output\)$", out, re.M):
772 if m.group(1).startswith(MODULE):
773 found.setdefault("." + m.group(1)[len(MODULE):], [])
774 for m in re.finditer(r"^--- FAIL (\S+) (Test\S*)(?: \(never finished\))?$", out, re.M):
775 if m.group(1).startswith(MODULE):
776 found.setdefault("." + m.group(1)[len(MODULE):], []).append(m.group(2))
777 return found
778
779
780def leaves(tests):
781 """The failed tests with no failed subtest of their own: a parent only
782 fails because one of those did."""
783 return sorted(t for t in set(tests) if not any(other.startswith(t + "/") for other in tests))
784
785
786def retry_failures(out, env, lane, base):
787 """Retry once, with go test, each test the failed run in out reported.
788 A pass on the retry is a flake and prints its line; returns 0 only when
789 everything that failed passed on its retry and each retry's process
790 exited 0."""
791 found = {package: leaves(tests) for package, tests in failures(out).items()}
792 count = sum(max(1, len(tests)) for tests in found.values())
793 if re.search(r"^--- BUILD FAILED ", out, re.M):
794 print("not retried: a package did not build", flush=True)
795 return 1
796 if not found:
797 print("not retried: go test failed without naming a failed test (a build, a budget)", flush=True)
798 return 1
799 if count > RETRY_LIMIT:
800 print(f"not retried: {count} tests failed, more than {RETRY_LIMIT}: a break, not a flake", flush=True)
801 return 1
802 load = load_average()
803 status = 0
804 for package, tests in sorted(found.items()):
805 cmd, retry_out, passed, failed, clean = go_test(package, tests, env, base)
806 print(f"+ {cmd} (retry, once)", flush=True)
807 twice = []
808 for t in tests or [WHOLE]:
809 # Green needs both: the retry's process exited 0, and this test passed.
810 if clean and t in passed and t not in failed:
811 print(flake_line(package, t, lane, failed_seconds(out, t), load), flush=True)
812 else:
813 twice.append(t)
814 print(f"FAILED TWICE {package}:{t} {lane}", flush=True)
815 if twice:
816 status = 1
817 print(tail(retry_out, 200), flush=True)
818 return status
819
820
821# The quarantine.
822
823def run_group(package, tests, env, tags=TAGS):
824 """Run one top-level test's quarantined entries; retry failures once."""
825 report = []
826 base = ["-tags", tags, "-timeout", TIMEOUT]
827 started = time.time()
828 cmd, out, passed, failed, _ = go_test(package, tests, env, base, fresh=False)
829 report.append(f"+ {cmd} ({time.time() - started:.0f}s)")
830 missing = set(tests) - passed - failed
831 flaky, broken = [], sorted(missing)
832 for t in sorted(missing):
833 report.append(f"QUARANTINE NOT RUN {package} {t}: no PASS or FAIL line (renamed or skipped?)")
834 if failed:
835 report.append(f"first attempt failed: {' '.join(sorted(failed))}; output tail:")
836 report.append(tail(out))
837 load = load_average()
838 retry_cmd, retry_out, retry_passed, retry_failed, clean = go_test(package, sorted(failed), env, base)
839 report.append(f"+ {retry_cmd} (retry, once)")
840 for t in sorted(failed):
841 if clean and t in retry_passed and t not in retry_failed:
842 flaky.append(t)
843 report.append(flake_line(package, t, "quarantine", failed_seconds(out, t), load))
844 else:
845 broken.append(t)
846 report.append(f"QUARANTINE FAIL {package} {t}: failed twice")
847 if any(t in broken for t in failed):
848 report.append(tail(retry_out))
849 for t in sorted(passed - failed):
850 report.append(f"ok {package} {t} {failed_seconds(out, t, 'PASS')}")
851 return report, flaky, broken
852
853
854def run_quarantine():
855 env = environment(True)
856 groups = {}
857 for package, test in quarantined():
858 groups.setdefault((package, test.split("/", 1)[0]), []).append(test)
859 for (_, top), tests in groups.items():
860 if top in tests and len(tests) > 1:
861 sys.exit(f"{QUARANTINE}: list a test or some of its subtests, not both: {tests}")
862 print(f"quarantine: {sum(len(v) for v in groups.values())} tests from {QUARANTINE}; "
863 "a failure is retried once, and a pass on the retry is reported as a flake", flush=True)
864 browser = browser_tests()
865
866 def tags(package, top):
867 return BROWSER_TAGS if top in browser.get(package, []) else TAGS
868 runs = []
869 for (p, top), tests in sorted(groups.items()):
870 tests = sorted(tests)
871 size = -(-len(tests) // -(-len(tests) // QUARANTINE_RUN))
872 runs += [(p, top, tests[i:i + size]) for i in range(0, len(tests), size)]
873 with ThreadPoolExecutor(max_workers=max(1, len(runs))) as pool:
874 futures = [pool.submit(run_group, p, tests, env, tags(p, top)) for p, top, tests in runs]
875 results = [f.result() for f in futures]
876 flakes, broken = [], []
877 for report, flaky, bad in results:
878 print("\n".join(report), flush=True)
879 flakes += flaky
880 broken += bad
881 print(f"quarantine: {len(flakes)} flaked (passed on the retry), {len(broken)} failed", flush=True)
882 for t in flakes:
883 print(f"quarantine flake: {t}")
884 return 1 if broken else 0
885
886
887def main(argv):
888 os.chdir(root())
889 if argv == ["all"]:
890 return run_all()
891 if len(argv) == 2 and argv[0] == "lane":
892 return run_lane(argv[1])
893 if argv == ["shard"]:
894 return run_shard()
895 if argv == ["compile"]:
896 return run_compile()
897 if argv == ["quarantine"]:
898 return run_quarantine()
899 if len(argv) > 2 and argv[0] == "retried":
900 return run_retried(argv[1], argv[2:])
901 if argv == ["lanes"]:
902 for name, _, _ in LANES:
903 print(name + ": " + " ".join(lane_packages(name) + lane_flags(name)))
904 for name, _, _ in BROWSER_LANES:
905 for package, flags in browser_runs(name):
906 print(name + ": -tags " + BROWSER_TAGS + " " + " ".join([package] + [shlex.quote(f) for f in flags]))
907 return 0
908 if argv == ["check"]:
909 return check_lanes()
910 if argv == ["browser"]:
911 for package, tests in browser_tests().items():
912 print(package + ": " + " ".join(tests))
913 return 0
914 print(__doc__, file=sys.stderr)
915 return 2
916
917
918if __name__ == "__main__":
919 sys.exit(main(sys.argv[1:]))
920