#!/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 : s 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): """The flakes in a log, each once however often the log repeats it.""" found = dict.fromkeys(m.groups() for m in FLAKE.finditer(log)) return [dict(zip(("package", "test", "lane", "commit", "seconds", "load"), groups)) for groups in found] 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("\n".join(logs(status))), }, "" def logs(status): """Every log in a run: the whole one, each step's, each shard's. They repeat one another; a long log may be cut in one and whole in another.""" found = [status.get("log") or ""] for step in status.get("steps") or []: found.append(step.get("log") or "") found += [shard.get("log") or "" for shard in step.get("shards") or []] return found 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 -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:]))