| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | |
| 22 | |
| 23 | import json |
| 24 | import os |
| 25 | import random |
| 26 | import re |
| 27 | import sys |
| 28 | from collections import defaultdict |
| 29 | |
| 30 | PROTECTED = re.compile(r"pinned|pins?_|_pins?\b|golden|sha256|vector|conformance|fuzz|realtime|faster|speedup|beats_the_incumbent") |
| 31 | |
| 32 | |
| 33 | def compact(cov_json_path, out_path): |
| 34 | |
| 35 | |
| 36 | |
| 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 | |
| 52 | def load_regions(path): |
| 53 | return {tuple(k) for k in json.load(open(path))} |
| 54 | |
| 55 | |
| 56 | def norm(f): |
| 57 | |
| 58 | return f[f.index("crates/"):] if "crates/" in f else f |
| 59 | |
| 60 | |
| 61 | def covered_lines(regions): |
| 62 | lines = defaultdict(set) |
| 63 | for (f, l1, _, l2, _) in regions: |
| 64 | lines[norm(f)].update(range(l1, l2 + 1)) |
| 65 | return lines |
| 66 | |
| 67 | |
| 68 | def 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 | |
| 77 | def covers_line(cov_lines, mutant): |
| 78 | line = mutant["span"]["start"]["line"] |
| 79 | return line in cov_lines.get(norm(mutant["file"]), set()) |
| 80 | |
| 81 | |
| 82 | def read_mutants_tsv(path): |
| 83 | |
| 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 | |
| 93 | def cmd_sample(tsv_path, covdir, n, seed, out_idx, out_json): |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 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 | |
| 126 | def 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 | |
| 134 | def 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 | |
| 141 | def 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 | |
| 160 | def 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 | |
| 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 | |
| 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 | |
| 246 | def cmd_failing(log_path, tests_path, out_path): |
| 247 | |
| 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 | |
| 260 | def cmd_regex(sample_json, idx): |
| 261 | |
| 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 | |
| 267 | def cmd_name(sample_json, idx): |
| 268 | print(json.load(open(sample_json))[int(idx)]["name"]) |
| 269 | |
| 270 | |
| 271 | if __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__) |