forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBfc0a0f7Tahinli5 days ago3995 commits

kill-matrix-analyze.py291 lines, 11.7 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Local analysis for the batched kill matrix (see lanes/testcut.phase2.md, "Batched variant").
3
4Subcommands (paths are absolute or relative to the lane root):
5
6 sample MUTANTS.tsv COVDIR N SEED OUT_IDX OUT_JSON
7 Stratified per-file seeded sample of mutants whose start line is covered by at
8 least one heavy test. OUT_JSON holds the sample (indices 0..N-1 in OUT_IDX).
9 survivors MUTANTS.json FASTDIR OUT_IDX
10 Indices whose fast-suite status is "pass" (survived the fast suite).
11 heavyjobs MUTANTS.json COVDIR SURV_IDX OUT_IDXFILE TESTSDIR
12 For each survivor, the heavy tests whose coverage includes its line. Writes
13 "<idx>\\t<testsfile>" lines for scripts/kill-matrix.sh mutrun heavy.
14 decide MUTANTS.json COVDIR FASTCOV.json FASTDIR HEAVYDIR TIMES.tsv KILLTSV REPORT_MD
15 failing LOG TESTS OUT
16 Test names from TESTS that nextest marks FAIL/TIMEOUT/signal in LOG (heavy mode).
17 compact LLVM_COV.json OUT.json
18 Reduce one llvm-cov JSON to executed ec-av1 regions (run on the server to keep
19 the copied-back data small).
20
21COVDIR holds index.tsv (ordinal, test name) and <ordinal>.json per heavy test.
22"""
23import json
24import os
25import random
26import re
27import sys
28from collections import defaultdict
29
30PROTECTED = re.compile(r"pinned|pins?_|_pins?\b|golden|sha256|vector|conformance|fuzz|realtime|faster|speedup|beats_the_incumbent")
31
32
33def compact(cov_json_path, out_path):
34 """Reduce an `llvm-cov report --json` file to the ec-av1 regions executed at least once.
35
36 Output: JSON list of [file, line_start, col_start, line_end, col_end].
37 """
38 cov = json.load(open(cov_json_path))
39 keys = set()
40 for fn in cov["data"][0]["functions"]:
41 names = fn.get("filenames", [])
42 for r in fn["regions"]:
43 if r[4] <= 0:
44 continue
45 f = names[r[5]]
46 if "crates/ec-av1/src/" in f:
47 keys.add((f, r[0], r[1], r[2], r[3]))
48 json.dump(sorted(list(k) for k in keys), open(out_path, "w"))
49 return keys
50
51
52def load_regions(path):
53 return {tuple(k) for k in json.load(open(path))}
54
55
56def norm(f):
57 """Workspace-relative path from "crates/" on (LLVM paths are absolute, mutant paths relative)."""
58 return f[f.index("crates/"):] if "crates/" in f else f
59
60
61def covered_lines(regions):
62 lines = defaultdict(set) # normalized file -> set of lines covered
63 for (f, l1, _, l2, _) in regions:
64 lines[norm(f)].update(range(l1, l2 + 1))
65 return lines
66
67
68def load_index(covdir):
69 rows = []
70 with open(os.path.join(covdir, "index.tsv")) as fh:
71 for line in fh:
72 i, name = line.rstrip("\n").split("\t")
73 rows.append((i, name))
74 return rows
75
76
77def covers_line(cov_lines, mutant):
78 line = mutant["span"]["start"]["line"]
79 return line in cov_lines.get(norm(mutant["file"]), set())
80
81
82def read_mutants_tsv(path):
83 """All mutants, in `cargo mutants --list --json` order: one TSV row per mutant (see README in the report)."""
84 rows = []
85 for line in open(path):
86 f, sl, sc, el, ec, rep, fn, genre, name = line.rstrip("\n").split("\t", 8)
87 rows.append({"file": f, "span": {"start": {"line": int(sl), "column": int(sc)},
88 "end": {"line": int(el), "column": int(ec)}},
89 "replacement": rep, "function": fn, "genre": genre, "name": name})
90 return rows
91
92
93def cmd_sample(tsv_path, covdir, n, seed, out_idx, out_json):
94 """Seeded, per-file stratified sample of mutants whose start line is covered by a heavy test.
95
96 out_json is the sample itself as a JSON array (same fields mutate.py reads). Its position is
97 the sample index used by the other subcommands; "global" keeps the index in the full list.
98 """
99 mutants = read_mutants_tsv(tsv_path)
100 union = defaultdict(set)
101 for i, _ in load_index(covdir):
102 for f, ls in covered_lines(load_regions(os.path.join(covdir, f"{i}.json"))).items():
103 union[f] |= ls
104 by_file = defaultdict(list)
105 for gidx, m in enumerate(mutants):
106 if covers_line(union, m):
107 by_file[m["file"]].append(gidx)
108 total = sum(len(v) for v in by_file.values())
109 rng = random.Random(seed)
110 picked = []
111 for f in sorted(by_file):
112 quota = max(1, round(n * len(by_file[f]) / total))
113 picked += rng.sample(by_file[f], min(quota, len(by_file[f])))
114 picked = sorted(rng.sample(picked, min(n, len(picked))))
115 sample = []
116 for g in picked:
117 m = dict(mutants[g])
118 m["global"] = g
119 sample.append(m)
120 json.dump(sample, open(out_json, "w"))
121 with open(out_idx, "w") as fh:
122 fh.write("".join(f"{i}\n" for i in range(len(sample))))
123 print(f"eligible={total} files={len(by_file)} sampled={len(sample)} seed={seed}")
124
125
126def read_statuses(d):
127 st = {}
128 for name in os.listdir(d):
129 if name.endswith(".status"):
130 st[int(name.split(".")[0])] = open(os.path.join(d, name)).read().strip()
131 return st
132
133
134def cmd_survivors(mutants_path, fastdir, out):
135 st = read_statuses(fastdir)
136 surv = sorted(i for i, s in st.items() if s == "pass")
137 open(out, "w").write("".join(f"{i}\n" for i in surv))
138 print(f"fast_run={len(st)} survivors={len(surv)} killed_by_fast={sum(1 for s in st.values() if s == 'fail')} unviable={sum(1 for s in st.values() if s == 'unviable')}")
139
140
141def cmd_heavyjobs(mutants_path, covdir, surv_path, out, testsdir):
142 mutants = json.load(open(mutants_path))
143 names = dict(load_index(covdir))
144 cov = {}
145 for i in names:
146 cov[i] = covered_lines(load_regions(os.path.join(covdir, f"{i}.json")))
147 os.makedirs(testsdir, exist_ok=True)
148 with open(out, "w") as fh:
149 for line in open(surv_path):
150 idx = int(line)
151 m = mutants[idx]
152 tests = [names[i] for i in names if covers_line(cov[i], m)]
153 tfile = os.path.join(testsdir, f"{idx}.txt")
154 with open(tfile, "w") as tf:
155 tf.write("".join(t + "\n" for t in tests))
156 fh.write(f"{idx}\t{tfile}\n")
157 print(f"survivor {idx}: {m['file']}:{m['span']['start']['line']} covering_heavy={len(tests)}")
158
159
160def cmd_decide(mutants_path, covdir, fastcov_path, fastdir, heavydir, times_path, killtsv, report_md):
161 mutants = json.load(open(mutants_path))
162 names = dict(load_index(covdir))
163 regs = {}
164 keep_names = set()
165 for fn in ("failed.txt", "nocov.txt"):
166 path = os.path.join(covdir, fn)
167 if os.path.exists(path):
168 keep_names |= {l.strip() for l in open(path) if l.strip()}
169 for i, name in names.items():
170 jpath = os.path.join(covdir, f"{i}.json")
171 if os.path.exists(jpath):
172 regs[name] = load_regions(jpath)
173 else:
174 keep_names.add(name)
175 regs[name] = set()
176 fast = load_regions(fastcov_path)
177 secs = {}
178 for line in open(times_path):
179 parts = line.rstrip("\n").split("\t")
180 if len(parts) == 2:
181 secs[parts[0]] = float(parts[1])
182 # Kill matrix: survivor -> failing heavy tests
183 kills = {}
184 for name in os.listdir(heavydir):
185 if name.endswith(".fail"):
186 idx = int(name.split(".")[0])
187 kills[idx] = set(l.strip() for l in open(os.path.join(heavydir, name)) if l.strip())
188 for idx in list(kills):
189 if not kills[idx]:
190 del kills[idx]
191 # Greedy runtime-weighted set cover over the kill matrix (Smith & Kapfhammer).
192 universe = set(kills)
193 kept, uncovered = [], set(universe)
194 tests_of = defaultdict(set)
195 for idx, ts in kills.items():
196 for t in ts:
197 tests_of[t].add(idx)
198 while uncovered:
199 best = max(tests_of, key=lambda t: (len(tests_of[t] & uncovered) / secs.get(t, 1.0), t), default=None)
200 if best is None or not (tests_of[best] & uncovered):
201 break
202 kept.append(best)
203 uncovered -= tests_of[best]
204 kept_set = set(kept)
205 kept_regions = set(fast)
206 for t in kept:
207 kept_regions |= set(regs[t])
208 rows = []
209 deleted_secs = 0.0
210 with open(killtsv, "w") as kt:
211 kt.write("mutant\tfile\tline\treplacement\tkilling_heavy_tests\n")
212 for idx in sorted(kills):
213 m = mutants[idx]
214 kt.write(f"{idx}\t{m['file']}\t{m['span']['start']['line']}\t{m['replacement']}\t{' ; '.join(sorted(kills[idx]))}\n")
215 for name in sorted(names.values(), key=lambda n: -secs.get(n, 0)):
216 u_fast = set(regs[name]) - set(fast)
217 u_kept = set(regs[name]) - kept_regions
218 kp = {idx for idx, ts in kills.items() if name in ts and not (ts & kept_set)}
219 if name in kept_set:
220 cls, action = "kept(cover)", "keep"
221 elif name in keep_names:
222 cls, action = "candidate", "keep (failed or no coverage)"
223 elif PROTECTED.search(name):
224 cls, action = "protected", "keep (protected)"
225 else:
226 cls = "candidate"
227 if u_kept:
228 action = "keep (unique coverage)"
229 elif kp:
230 action = "keep (unique kills)"
231 else:
232 action = "delete"
233 deleted_secs += secs.get(name, 0)
234 rows.append((name, cls, len(u_fast), len(u_kept), len(kp), action))
235 with open(report_md, "w") as rp:
236 rp.write("| crate | test | seconds | class | |U(T)| vs fast | |U(T)| vs fast+kept | |K'| | decision |\n")
237 rp.write("|---|---|---|---|---|---|---|---|\n")
238 for name, cls, uf, uk, kp_n, action in rows:
239 rp.write(f"| ec-av1 | {name} | {secs.get(name, 0):.1f} | {cls} | {uf} | {uk} | {kp_n} | {action} |\n")
240 deletions = [r[0] for r in rows if r[5] == "delete"]
241 print(f"survivors_with_kills={len(kills)} kept_by_cover={len(kept)} candidates={sum(1 for r in rows if r[1]=='candidate')} deletable={len(deletions)} seconds_saved={deleted_secs:.1f}")
242 with open(os.path.join(os.path.dirname(report_md), os.path.basename(report_md) + ".deletions"), "w") as fh:
243 fh.write("".join(d + "\n" for d in deletions))
244
245
246def cmd_failing(log_path, tests_path, out_path):
247 """Names from TESTS that nextest reports as FAIL/TIMEOUT/signal in LOG (one per line in OUT)."""
248 names = [l.strip() for l in open(tests_path) if l.strip()]
249 status = re.compile(r"^\s*(FAIL|TIMEOUT|SIGSEGV|SIGABRT|SIGKILL|SIGILL|SIGBUS|SIGFPE|SIGTERM|LEAK|ABORT)\b")
250 text = re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", open(log_path, errors="replace").read())
251 bad = set()
252 for line in text.splitlines():
253 if status.match(line):
254 tail = line.rstrip()
255 bad.update(n for n in names if tail.endswith(" " + n))
256 open(out_path, "w").write("".join(f"{n}\n" for n in sorted(bad)))
257 print(f"failing={len(bad)}")
258
259
260def cmd_regex(sample_json, idx):
261 """Anchored, escaped regex that selects exactly one mutant by its `--list` name."""
262 name = json.load(open(sample_json))[int(idx)]["name"]
263 special = set(".+*?()|[]{}^$\\#&-~")
264 print("^" + "".join("\\" + c if c in special else c for c in name) + "$")
265
266
267def cmd_name(sample_json, idx):
268 print(json.load(open(sample_json))[int(idx)]["name"])
269
270
271if __name__ == "__main__":
272 cmd = sys.argv[1]
273 args = sys.argv[2:]
274 if cmd == "regex":
275 cmd_regex(args[0], args[1])
276 elif cmd == "name":
277 cmd_name(args[0], args[1])
278 elif cmd == "compact":
279 compact(args[0], args[1])
280 elif cmd == "sample":
281 cmd_sample(args[0], args[1], int(args[2]), int(args[3]), args[4], args[5])
282 elif cmd == "survivors":
283 cmd_survivors(args[0], args[1], args[2])
284 elif cmd == "heavyjobs":
285 cmd_heavyjobs(args[0], args[1], args[2], args[3], args[4])
286 elif cmd == "decide":
287 cmd_decide(*args)
288 elif cmd == "failing":
289 cmd_failing(args[0], args[1], args[2])
290 else:
291 sys.exit(__doc__)