| 1 | #!/usr/bin/env python3 |
| 2 | """List the tests that keep flaking on CI. |
| 3 | |
| 4 | scripts/ci-flakes.py main and every branch git knows on origin |
| 5 | scripts/ci-flakes.py -branch B ... these branches only |
| 6 | scripts/ci-flakes.py -log FILE ... a saved job log, as one more run |
| 7 | |
| 8 | A test that fails and then passes on its one retry leaves a line in the |
| 9 | job's log (scripts/ci-test.py prints it): |
| 10 | |
| 11 | FLAKE <package>:<test> <lane> <commit> <seconds>s <load> |
| 12 | |
| 13 | This reads those lines back through `amadan ci status REPO -branch B |
| 14 | -json` and counts them per test over the last -days days (7). |
| 15 | |
| 16 | amadan keeps one run per branch, the latest, so each time it runs this |
| 17 | adds the runs it sees to a history file (-history, by default |
| 18 | ~/.cache/equipo/ci-flakes.jsonl) and counts over that file's last -runs |
| 19 | runs (200). Run it after a push, or daily, from the same account; a run |
| 20 | it never saw is not counted. |
| 21 | |
| 22 | A test with -times flakes (3) inside the window is a repeat offender. For |
| 23 | each one this prints the line to add to scripts/ci-quarantine.txt and the |
| 24 | two amadan commands that file it as a discussion of type Issue. It files |
| 25 | nothing itself: whoever runs it does, with the commands as printed. |
| 26 | """ |
| 27 | import argparse |
| 28 | import json |
| 29 | import os |
| 30 | import re |
| 31 | import shlex |
| 32 | import subprocess |
| 33 | import sys |
| 34 | import time |
| 35 | |
| 36 | # The line scripts/ci-test.py prints (FLAKE there): keep the two in step. |
| 37 | FLAKE = re.compile(r"^FLAKE (\./\S+):(Test\S*) (\S+) ([0-9a-f]{40}|unknown) (\d+(?:\.\d+)?s|unknown) (\d+(?:\.\d+)?|unknown)$", re.M) |
| 38 | |
| 39 | QUARANTINE = "scripts/ci-quarantine.txt" |
| 40 | |
| 41 | |
| 42 | def root(): |
| 43 | return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 44 | |
| 45 | |
| 46 | def flakes(log): |
| 47 | """The flakes in a log, each once however often the log repeats it.""" |
| 48 | found = dict.fromkeys(m.groups() for m in FLAKE.finditer(log)) |
| 49 | return [dict(zip(("package", "test", "lane", "commit", "seconds", "load"), groups)) for groups in found] |
| 50 | |
| 51 | |
| 52 | def origin_branches(): |
| 53 | """main, then every other branch git has seen on origin.""" |
| 54 | try: |
| 55 | out = subprocess.check_output( |
| 56 | ["git", "-C", root(), "for-each-ref", "--format=%(refname:lstrip=3)", "refs/remotes/origin"], text=True) |
| 57 | except (OSError, subprocess.CalledProcessError): |
| 58 | out = "" |
| 59 | names = [b for b in out.split() if b not in ("HEAD", "main")] |
| 60 | return ["main"] + sorted(names) |
| 61 | |
| 62 | |
| 63 | def fetch(repo, branch): |
| 64 | """The branch's latest run as amadan reports it, or None with the |
| 65 | reason: no such branch, no run yet, still running.""" |
| 66 | cmd = ["amadan", "ci", "status", repo, "-branch", branch, "-json"] |
| 67 | try: |
| 68 | p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=120) |
| 69 | except (OSError, subprocess.TimeoutExpired) as e: |
| 70 | return None, str(e) |
| 71 | try: |
| 72 | status = json.loads(p.stdout) |
| 73 | except ValueError: |
| 74 | return None, (p.stderr or p.stdout).strip() or "no JSON" |
| 75 | if status.get("state") not in ("success", "failure"): |
| 76 | return None, "state " + str(status.get("state")) |
| 77 | return { |
| 78 | "run": "%s %s %s" % (branch, status.get("sha", ""), status.get("updated_at", "")), |
| 79 | "branch": branch, "commit": status.get("sha", ""), "state": status["state"], |
| 80 | "at": int(status.get("updated_at") or time.time()), |
| 81 | "flakes": flakes("\n".join(logs(status))), |
| 82 | }, "" |
| 83 | |
| 84 | |
| 85 | def logs(status): |
| 86 | """Every log in a run: the whole one, each step's, each shard's. They |
| 87 | repeat one another; a long log may be cut in one and whole in another.""" |
| 88 | found = [status.get("log") or ""] |
| 89 | for step in status.get("steps") or []: |
| 90 | found.append(step.get("log") or "") |
| 91 | found += [shard.get("log") or "" for shard in step.get("shards") or []] |
| 92 | return found |
| 93 | |
| 94 | |
| 95 | def from_log(path): |
| 96 | with open(path, errors="replace") as f: |
| 97 | found = flakes(f.read()) |
| 98 | return {"run": "log " + os.path.abspath(path), "branch": "", "commit": found[0]["commit"] if found else "", |
| 99 | "state": "", "at": int(time.time()), "flakes": found} |
| 100 | |
| 101 | |
| 102 | def load_history(path): |
| 103 | runs = {} |
| 104 | try: |
| 105 | with open(path) as f: |
| 106 | for line in f: |
| 107 | if line.strip(): |
| 108 | run = json.loads(line) |
| 109 | runs[run["run"]] = run |
| 110 | except FileNotFoundError: |
| 111 | pass |
| 112 | return runs |
| 113 | |
| 114 | |
| 115 | def save_history(path, runs, keep): |
| 116 | kept = sorted(runs.values(), key=lambda r: r["at"])[-keep:] |
| 117 | os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True) |
| 118 | tmp = path + ".tmp" |
| 119 | with open(tmp, "w") as f: |
| 120 | for run in kept: |
| 121 | f.write(json.dumps(run, sort_keys=True) + "\n") |
| 122 | os.replace(tmp, path) |
| 123 | return kept |
| 124 | |
| 125 | |
| 126 | def quarantined(): |
| 127 | listed = set() |
| 128 | try: |
| 129 | with open(os.path.join(root(), QUARANTINE)) as f: |
| 130 | for line in f: |
| 131 | fields = line.split(None, 2) |
| 132 | if len(fields) >= 2 and fields[0].startswith("./"): |
| 133 | listed.add((fields[0], fields[1])) |
| 134 | except FileNotFoundError: |
| 135 | pass |
| 136 | return listed |
| 137 | |
| 138 | |
| 139 | def offender(repo, package, test, hits, days): |
| 140 | """What to do about a repeat offender, as text.""" |
| 141 | title = "Flaky test: %s %s" % (package, test) |
| 142 | lines = ["", "REPEAT OFFENDER %s %s: %d flakes in %d days" % (package, test, len(hits), days), |
| 143 | "1. Quarantine it. Make the test call testci.Quarantine(t) first, and add to " + QUARANTINE + ":", |
| 144 | "", |
| 145 | "%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), |
| 146 | "", |
| 147 | "2. File it, with these two commands as they are (the second with the id the first prints):", |
| 148 | "", |
| 149 | "amadan discuss new %s -title %s -body - <<'BODY'" % (repo, shlex.quote(title)), |
| 150 | "%s %s flaked %d times in %d days on hosted CI: it failed, then passed on its one retry." % (package, test, len(hits), days), |
| 151 | "It is quarantined in " + QUARANTINE + " until the cause is fixed.", |
| 152 | ""] |
| 153 | for at, branch, f in hits: |
| 154 | lines.append("- %s commit %s branch %s lane %s failed attempt %s load %s" % ( |
| 155 | time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime(at)), f["commit"][:12], branch or "?", f["lane"], f["seconds"], f["load"])) |
| 156 | lines += ["", "The failed attempt's output is in that run's job log, above its FLAKE line.", "BODY", |
| 157 | "amadan discuss type %s <id> -type Issue" % repo] |
| 158 | return "\n".join(lines) |
| 159 | |
| 160 | |
| 161 | def main(argv): |
| 162 | ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) |
| 163 | ap.add_argument("-repo", default="oficina/equipo") |
| 164 | ap.add_argument("-branch", action="append", help="a branch to read; repeat it. Default: main and every origin branch") |
| 165 | ap.add_argument("-log", action="append", default=[], help="a saved job log to read as one more run; repeat it") |
| 166 | ap.add_argument("-days", type=int, default=7) |
| 167 | ap.add_argument("-times", type=int, default=3, help="flakes inside the window that make a repeat offender") |
| 168 | ap.add_argument("-runs", type=int, default=200, help="runs the history keeps") |
| 169 | ap.add_argument("-history", default=os.path.join(os.path.expanduser("~"), ".cache", "equipo", "ci-flakes.jsonl")) |
| 170 | ap.add_argument("-no-fetch", action="store_true", help="read only the history and -log files") |
| 171 | args = ap.parse_args(argv) |
| 172 | |
| 173 | runs = load_history(args.history) |
| 174 | seen = len(runs) |
| 175 | if not args.no_fetch: |
| 176 | for branch in args.branch or origin_branches(): |
| 177 | run, why = fetch(args.repo, branch) |
| 178 | if run is None: |
| 179 | if args.branch: |
| 180 | print("%s: not read: %s" % (branch, why)) |
| 181 | continue |
| 182 | runs.setdefault(run["run"], run) |
| 183 | for path in args.log: |
| 184 | run = from_log(path) |
| 185 | runs.setdefault(run["run"], run) |
| 186 | kept = save_history(args.history, runs, args.runs) |
| 187 | |
| 188 | since = time.time() - args.days * 86400 |
| 189 | window = [r for r in kept if r["at"] >= since] |
| 190 | by_test = {} |
| 191 | for run in window: |
| 192 | for f in run["flakes"]: |
| 193 | by_test.setdefault((f["package"], f["test"]), []).append((run["at"], run["branch"], f)) |
| 194 | print("%d runs in the last %d days (%d new this time, %d kept in %s)" % ( |
| 195 | len(window), args.days, len(runs) - seen, len(kept), args.history)) |
| 196 | if not by_test: |
| 197 | print("no flakes") |
| 198 | return 0 |
| 199 | listed = quarantined() |
| 200 | print("flakes, package, test, lanes, last seen") |
| 201 | ranked = sorted(by_test.items(), key=lambda kv: (-len(kv[1]), kv[0])) |
| 202 | for (package, test), hits in ranked: |
| 203 | note = " (quarantined)" if (package, test) in listed else "" |
| 204 | print("%d %s %s %s %s%s" % ( |
| 205 | len(hits), package, test, ",".join(sorted({f["lane"] for _, _, f in hits})), |
| 206 | time.strftime("%Y-%m-%d", time.gmtime(max(at for at, _, _ in hits))), note)) |
| 207 | for (package, test), hits in ranked: |
| 208 | if len(hits) >= args.times and (package, test) not in listed: |
| 209 | print(offender(args.repo, package, test, sorted(hits, key=lambda h: h[0]), args.days)) |
| 210 | return 0 |
| 211 | |
| 212 | |
| 213 | if __name__ == "__main__": |
| 214 | sys.exit(main(sys.argv[1:])) |
| 215 | |