forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

driver.py313 lines, 12.4 KiBHistoryRawDownload
1#!/usr/bin/env python3
2"""Phase 2 evidence driver for ec-h264 (runs on a server inside the lane tree).
3
4Stages (argv[1]):
5 cov coverage of fast suite and each candidate; prints U(T) sizes
6 run full pipeline: coverage, sampling, S/K/K' kill runs, decisions
7
8Output that matters goes to stdout as lines starting with 'RESULT\t'.
9Scratch (cargo-mutants trees) goes under $TMPDIR, which is not synced.
10"""
11import json, os, re, shutil, subprocess, sys, glob
12
13CRATE = "ec-h264"
14ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))
15TMP = os.environ.get("TMPDIR", "/tmp")
16WORK = os.path.join(TMP, "p2h264")
17N_SAMPLE = int(os.environ.get("N_SAMPLE", "30"))
18ENV = dict(os.environ, EC_REQUIRE_FIXTURES="1")
19TARGET = os.environ.get("CARGO_TARGET_DIR", os.path.join(ROOT, "target"))
20
21# (test, runtime s, class). Order = decreasing runtime, as the protocol requires.
22CANDS = [
23 ("every_quantiser_with_motion_matches_ffmpeg", 70.90, "candidate"),
24 ("every_quantiser_matches_ffmpeg", 70.34, "candidate"),
25 ("high_profile_8x8_matches_ffmpeg", 56.82, "candidate"),
26 ("x264_hi444_10bit", 24.18, "candidate"),
27 ("corrupt_streams_never_panic", 24.24, "pseudo"),
28 ("x264_hi444_8bit", 23.01, "candidate"),
29 ("truncated_and_corrupted_conformance_streams_never_panic", 20.88, "pseudo"),
30]
31PROTECTED = {"jvt_hi444_vectors_bit_exact": 464.6}
32EXCLUDE_ALWAYS = "encode::real_library_frames_encode_and_decode_exactly"
33
34
35def sel(name):
36 return "test(/(^|::)%s$/)" % name
37
38
39def sh(args, log):
40 os.makedirs(WORK, exist_ok=True)
41 with open(os.path.join(WORK, log), "w") as f:
42 r = subprocess.run(args, cwd=ROOT, env=ENV, stdout=f, stderr=subprocess.STDOUT)
43 print("STEP %s rc=%d" % (log, r.returncode), flush=True)
44 return r.returncode
45
46
47def clear_profraw():
48 for p in glob.glob(os.path.join(TARGET, "llvm-cov-target", "*.profraw")):
49 os.remove(p)
50
51
52VALID = {}
53FAST_CACHE = {}
54LAST_BAD = 0
55LAST_RC = 0
56
57
58def prune_bad_profraw(files):
59 sysroot = subprocess.run(["rustc", "--print", "sysroot"], capture_output=True, text=True).stdout.strip()
60 prof = os.path.join(sysroot, "lib/rustlib/x86_64-unknown-linux-gnu/bin/llvm-profdata")
61 n = 0
62 for f in files:
63 r = subprocess.run([prof, "show", f], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
64 if r.returncode != 0:
65 os.remove(f)
66 n += 1
67 print("PRUNED bad profraw: %d" % n, flush=True)
68 return n
69
70
71def tail_log(log, n=40):
72 p = os.path.join(WORK, log)
73 if os.path.exists(p):
74 with open(p, errors="replace") as f:
75 lines = f.readlines()[-n:]
76 print("LOG-TAIL %s\n%s" % (log, "".join(lines)), flush=True)
77
78
79def cov_report(out_json, extra_args):
80 """Run instrumented tests (profraw kept fresh), then dump JSON.
81
82 --no-fail-fast: wall-clock tripwires can fail under instrumentation; the
83 profraw is still written, so a nonzero run exit is only reported.
84 """
85 subprocess.run(["cargo", "llvm-cov", "clean", "--profraw-only"], cwd=ROOT, env=ENV,
86 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
87 clear_profraw()
88 base = os.path.basename(out_json)
89 rc_run = sh(["cargo", "llvm-cov", "nextest", "--release", "-p", CRATE, "--no-report",
90 "--no-fail-fast"] + extra_args, base + ".run.log")
91 files = sorted(glob.glob(os.path.join(TARGET, "llvm-cov-target", "*.profraw")))
92 global LAST_BAD
93 LAST_BAD = prune_bad_profraw(files)
94 files = sorted(glob.glob(os.path.join(TARGET, "llvm-cov-target", "*.profraw")))
95 print("PROFRAW %s n=%d sizes=%s" % (base, len(files),
96 [os.path.getsize(f) for f in files][:20]), flush=True)
97 rc_rep = sh(["cargo", "llvm-cov", "report", "--release", "--json", "--output-path", out_json],
98 base + ".rep.log")
99 if rc_rep != 0 or not os.path.exists(out_json):
100 print("FAIL coverage report for %s (run rc=%d, report rc=%d)" % (base, rc_run, rc_rep),
101 flush=True)
102 tail_log(base + ".run.log")
103 tail_log(base + ".rep.log")
104 sys.exit(3)
105 global LAST_RC
106 LAST_RC = rc_run
107 if rc_run != 0:
108 print("NOTE coverage run for %s exited %d (test failures, profraw kept)" % (base, rc_run),
109 flush=True)
110 with open(out_json) as f:
111 return json.load(f)
112
113
114def regions(report):
115 """key (file, l1, c1, l2, c2) -> (max count, function name), code regions only."""
116 out = {}
117 for fn in report["data"][0]["functions"]:
118 for r in fn["regions"]:
119 l1, c1, l2, c2, cnt, fid, _exp, kind = r[:8]
120 if kind != 0:
121 continue
122 fname = fn["filenames"][fid]
123 if "/crates/%s/src/" % CRATE not in fname:
124 continue
125 rel = fname[fname.index("crates/"):]
126 key = (rel, l1, c1, l2, c2)
127 prev = out.get(key)
128 if prev is None or cnt > prev[0]:
129 out[key] = (cnt, fn["name"])
130 return out
131
132
133def innermost(regs, rel, line):
134 best = None
135 for key, (cnt, _f) in regs.items():
136 if key[0] != rel or not (key[1] <= line <= key[3]):
137 continue
138 span = (key[3] - key[1], key[4] - key[2] if key[1] == key[3] else 0)
139 if best is None or span < best[0]:
140 best = (span, key, cnt)
141 return best
142
143
144def mutants_list():
145 txt = subprocess.run(["cargo", "mutants", "-p", CRATE, "--list"], cwd=ROOT, env=ENV,
146 capture_output=True, text=True).stdout
147 out = []
148 for line in txt.splitlines():
149 m = re.match(r"^(crates/%s/src/[^:]+):(\d+):(\d+): " % CRATE, line)
150 if m:
151 out.append((line.strip(), m.group(1), int(m.group(2))))
152 return out
153
154
155def mutate(outdir, names, extra_test_args, timeout_is_kill):
156 """Return (caught, not_killed) name sets for the given mutants.
157
158 The unmutated baseline runs in the scratch copy (default baseline). If it
159 fails, cargo-mutants exits 4 and we stop without deciding anything.
160 `--gitignore false` copies the ignored `fixtures` symlink into the scratch tree.
161 Timeouts count as kills only when timeout_is_kill (the candidate's own run).
162 """
163 if not names:
164 return set(), set()
165 if os.path.isdir(outdir):
166 assert outdir.startswith(WORK + os.sep), outdir
167 shutil.rmtree(outdir)
168 os.makedirs(outdir, exist_ok=True)
169 tag = os.path.basename(outdir)
170 args = ["cargo", "mutants", "-p", CRATE, "--test-tool", "nextest",
171 "--timeout-multiplier", "3", "-j", "1", "--copy-vcs", "true",
172 "--gitignore", "false", "-o", outdir]
173 for n in names:
174 args += ["--re", re.escape(n)]
175 # Needs the user's personal media, which no server has: excluded from every mutation run.
176 excl = "not test(=%s)" % EXCLUDE_ALWAYS
177 extra = list(extra_test_args)
178 if "-E" in extra:
179 i = extra.index("-E") + 1
180 extra[i] = "(%s) and %s" % (extra[i], excl)
181 else:
182 extra += ["-E", excl]
183 for a in extra:
184 args += ["--cargo-test-arg=" + a]
185 rc = sh(args, tag + ".log")
186 if rc == 4:
187 print("RESULT\tbaseline_failed\t%s" % tag, flush=True)
188 sys.exit(4)
189 base = glob.glob(os.path.join(outdir, "**", "mutants.out"), recursive=True)
190 if not base:
191 print("RESULT\tmutate_no_output\t%s\trc=%d" % (tag, rc), flush=True)
192 sys.exit(5)
193 d = base[0]
194
195 def read(name):
196 p = os.path.join(d, name)
197 return set(l.strip() for l in open(p)) if os.path.exists(p) else set()
198
199 caught = read("caught.txt")
200 timeouts = read("timeout.txt")
201 missed = read("missed.txt")
202 if timeout_is_kill:
203 caught |= timeouts
204 else:
205 missed |= timeouts
206 print("MUTSTAT %s caught=%d missed=%d timeout=%d unviable=%d asked=%d rc=%d" % (
207 tag, len(caught), len(missed), len(timeouts), len(read("unviable.txt")), len(names), rc), flush=True)
208 # Sanity: fixture/runner errors must not be what kills a mutant.
209 logs = glob.glob(os.path.join(d, "log", "*.log"))
210 bad = [p for p in logs if "lists no" in open(p, errors="replace").read()]
211 print("SANITY %s logs=%d fixture_errors=%d" % (tag, len(logs), len(bad)), flush=True)
212 for p in logs:
213 hits = [l.rstrip() for l in open(p, errors="replace") if "panicked at" in l]
214 if hits:
215 print("SANITY %s sample_log=%s" % (tag, p), flush=True)
216 for h in hits[:3]:
217 print("SANITY " + h[:200], flush=True)
218 break
219 return caught, missed
220
221
222def run_cov(cands_to_check):
223 fast = cov_report(os.path.join(WORK, "fast.json"),
224 ["--profile", "fast"])
225 fast_r = regions(fast)
226 per = {}
227 for name, _s, _c in cands_to_check:
228 rep = cov_report(os.path.join(WORK, name + ".json"), ["-E", sel(name)])
229 tr = regions(rep)
230 VALID[name] = (LAST_BAD == 0 and LAST_RC == 0)
231 print("RESULT\tvalid\t%s\t%s\tbad_profraw=%d\trc=%d" % (name, VALID[name], LAST_BAD, LAST_RC), flush=True)
232 U = [k for k, (c, _f) in tr.items() if c > 0 and fast_r.get(k, (0,))[0] == 0]
233 per[name] = (tr, U)
234 funcs = sorted({tr[k][1] for k in U})
235 print("RESULT\tcov\t%s\tU=%d\tfuncs=%s" % (name, len(U), ";".join(funcs)[:400]), flush=True)
236 return fast_r, per
237
238
239def main():
240 stage = sys.argv[1] if len(sys.argv) > 1 else "run"
241 os.makedirs(WORK, exist_ok=True)
242 if stage == "cov":
243 run_cov(CANDS)
244 return
245 # full pipeline; start from a clean instrumented tree (as the ec-aac lane does)
246 subprocess.run(["cargo", "llvm-cov", "clean", "--workspace"], cwd=ROOT, env=ENV,
247 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
248 fast_r, per = run_cov(CANDS)
249 muts = mutants_list()
250 print("RESULT\tmutants_listed\t%d" % len(muts), flush=True)
251 deleted = set()
252 heavy_all = [n for n, _s, _c in CANDS] + list(PROTECTED)
253 for name, secs, cls in CANDS:
254 remaining = [h for h in heavy_all if h not in deleted and h != name]
255 tr, U = per[name]
256 if not VALID.get(name):
257 print("RESULT\tdecision\t%s\t%s\tsecs=%.1f\tU=%d\ttried=0\tS=0\tK=0\tKp=0\tkeep (no valid evidence)\tex=" % (
258 CRATE, name, secs, len(U)), flush=True)
259 continue
260 # mutants inside code T executes
261 eligible = []
262 for line_txt, rel, line in muts:
263 hit = innermost(tr, rel, line)
264 if hit is None or hit[2] == 0:
265 continue
266 fh = innermost(fast_r, rel, line)
267 fast_hit = fh[2] if fh else 0
268 in_u = hit[1] in U
269 eligible.append((0 if in_u else 1, fast_hit, line_txt))
270 eligible.sort()
271 sample = [e[2] for e in eligible[:N_SAMPLE]]
272 tag = name[:24]
273 # S: survivors of the fast suite
274 new = [m for m in sample if m not in FAST_CACHE]
275 fc, fm = mutate(os.path.join(WORK, "fast-" + tag), new, ["--profile", "fast"], False)
276 print("SANITY\t%s\tmissed=%d\tcaught=%d" % (name, len(fm), len(fc)), flush=True)
277 for m in fc:
278 FAST_CACHE[m] = True
279 for m in fm:
280 FAST_CACHE[m] = False
281 viable = [m for m in sample if m in FAST_CACHE]
282 if not viable:
283 print("RESULT\tdecision\t%s\t%s\tsecs=%.1f\tU=%d\ttried=%d\tS=0\tK=0\tKp=0\tkeep (no valid evidence: 0 viable mutants)\tex=" % (
284 CRATE, name, secs, len(U), len(sample)), flush=True)
285 continue
286 S = sorted(m for m in viable if not FAST_CACHE[m])
287 # K: survivors of fast that T kills
288 tc, tm = mutate(os.path.join(WORK, "t-" + tag), S,
289 ["-E", sel(name)], True)
290 K = sorted(set(S) - tm)
291 # K': K mutants that no other remaining heavy test kills
292 if K and remaining:
293 expr = " | ".join(sel(h) for h in remaining)
294 kc, km = mutate(os.path.join(WORK, "k-" + tag), K, ["-E", expr], False)
295 Kp = sorted(set(K) - kc)
296 else:
297 Kp = list(K)
298 if cls == "pseudo":
299 decision = "delete" if not K else "keep (weak oracle, kills %d)" % len(K)
300 else:
301 decision = "delete" if not Kp else "keep"
302 if decision == "delete" and not PROTECTED.get(name):
303 deleted.add(name)
304 tried = len(viable)
305 ex = Kp[0] if Kp else (K[0] if K and cls == "pseudo" else "")
306 print("RESULT\tdecision\t%s\t%s\tsecs=%.1f\tU=%d\ttried=%d\tS=%d\tK=%d\tKp=%d\t%s\tex=%s" % (
307 CRATE, name, secs, len(U), tried, len(S), len(K), len(Kp), decision,
308 ex), flush=True)
309 print("RESULT\tdeleted\t%s" % ",".join(sorted(deleted)), flush=True)
310
311
312if __name__ == "__main__":
313 main()