| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | |
| 21 | import json |
| 22 | import os |
| 23 | import random |
| 24 | import re |
| 25 | import sys |
| 26 | from collections import defaultdict |
| 27 | |
| 28 | PROTECTED = re.compile(r"pinned|pins?_|_pins?\b|golden|sha256|vector|conformance|fuzz|realtime|faster|speedup|beats_the_incumbent") |
| 29 | |
| 30 | |
| 31 | def compact(cov_json_path, out_path): |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | cov = json.load(open(cov_json_path)) |
| 37 | keys = set() |
| 38 | for fn in cov["data"][0]["functions"]: |
| 39 | names = fn.get("filenames", []) |
| 40 | for r in fn["regions"]: |
| 41 | if r[4] <= 0: |
| 42 | continue |
| 43 | f = names[r[5]] |
| 44 | if "crates/ec-av1/src/" in f: |
| 45 | keys.add((f, r[0], r[1], r[2], r[3])) |
| 46 | json.dump(sorted(list(k) for k in keys), open(out_path, "w")) |
| 47 | return keys |
| 48 | |
| 49 | |
| 50 | def load_regions(path): |
| 51 | return {tuple(k) for k in json.load(open(path))} |
| 52 | |
| 53 | |
| 54 | def norm(f): |
| 55 | |
| 56 | return f[f.index("crates/"):] if "crates/" in f else f |
| 57 | |
| 58 | |
| 59 | def covered_lines(regions): |
| 60 | lines = defaultdict(set) |
| 61 | for (f, l1, _, l2, _) in regions: |
| 62 | lines[norm(f)].update(range(l1, l2 + 1)) |
| 63 | return lines |
| 64 | |
| 65 | |
| 66 | def load_index(covdir): |
| 67 | rows = [] |
| 68 | with open(os.path.join(covdir, "index.tsv")) as fh: |
| 69 | for line in fh: |
| 70 | i, name = line.rstrip("\n").split("\t") |
| 71 | rows.append((i, name)) |
| 72 | return rows |
| 73 | |
| 74 | |
| 75 | def covers_line(cov_lines, mutant): |
| 76 | line = mutant["span"]["start"]["line"] |
| 77 | return line in cov_lines.get(norm(mutant["file"]), set()) |
| 78 | |
| 79 | |
| 80 | def read_mutants_tsv(path): |
| 81 | |
| 82 | rows = [] |
| 83 | for line in open(path): |
| 84 | f, sl, sc, el, ec, rep, fn, genre, name = line.rstrip("\n").split("\t", 8) |
| 85 | rows.append({"file": f, "span": {"start": {"line": int(sl), "column": int(sc)}, |
| 86 | "end": {"line": int(el), "column": int(ec)}}, |
| 87 | "replacement": rep, "function": fn, "genre": genre, "name": name}) |
| 88 | return rows |
| 89 | |
| 90 | |
| 91 | def cmd_sample(tsv_path, covdir, n, seed, out_idx, out_json): |
| 92 | |
| 93 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | mutants = read_mutants_tsv(tsv_path) |
| 98 | union = defaultdict(set) |
| 99 | for i, _ in load_index(covdir): |
| 100 | for f, ls in covered_lines(load_regions(os.path.join(covdir, f"{i}.json"))).items(): |
| 101 | union[f] |= ls |
| 102 | by_file = defaultdict(list) |
| 103 | for gidx, m in enumerate(mutants): |
| 104 | if covers_line(union, m): |
| 105 | by_file[m["file"]].append(gidx) |
| 106 | total = sum(len(v) for v in by_file.values()) |
| 107 | rng = random.Random(seed) |
| 108 | picked = [] |
| 109 | for f in sorted(by_file): |
| 110 | quota = max(1, round(n * len(by_file[f]) / total)) |
| 111 | picked += rng.sample(by_file[f], min(quota, len(by_file[f]))) |
| 112 | picked = sorted(rng.sample(picked, min(n, len(picked)))) |
| 113 | sample = [] |
| 114 | for g in picked: |
| 115 | m = dict(mutants[g]) |
| 116 | m["global"] = g |
| 117 | sample.append(m) |
| 118 | json.dump(sample, open(out_json, "w")) |
| 119 | with open(out_idx, "w") as fh: |
| 120 | fh.write("".join(f"{i}\n" for i in range(len(sample)))) |
| 121 | print(f"eligible={total} files={len(by_file)} sampled={len(sample)} seed={seed}") |
| 122 | |
| 123 | |
| 124 | def read_statuses(d): |
| 125 | st = {} |
| 126 | for name in os.listdir(d): |
| 127 | if name.endswith(".status"): |
| 128 | st[int(name.split(".")[0])] = open(os.path.join(d, name)).read().strip() |
| 129 | return st |
| 130 | |
| 131 | |
| 132 | def cmd_survivors(mutants_path, fastdir, out): |
| 133 | st = read_statuses(fastdir) |
| 134 | surv = sorted(i for i, s in st.items() if s == "pass") |
| 135 | open(out, "w").write("".join(f"{i}\n" for i in surv)) |
| 136 | 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')}") |
| 137 | |
| 138 | |
| 139 | def cmd_heavyjobs(mutants_path, covdir, surv_path, out, testsdir): |
| 140 | mutants = json.load(open(mutants_path)) |
| 141 | names = dict(load_index(covdir)) |
| 142 | cov = {} |
| 143 | for i in names: |
| 144 | cov[i] = covered_lines(load_regions(os.path.join(covdir, f"{i}.json"))) |
| 145 | os.makedirs(testsdir, exist_ok=True) |
| 146 | with open(out, "w") as fh: |
| 147 | for line in open(surv_path): |
| 148 | idx = int(line) |
| 149 | m = mutants[idx] |
| 150 | tests = [names[i] for i in names if covers_line(cov[i], m)] |
| 151 | tfile = os.path.join(testsdir, f"{idx}.txt") |
| 152 | with open(tfile, "w") as tf: |
| 153 | tf.write("".join(t + "\n" for t in tests)) |
| 154 | fh.write(f"{idx}\t{tfile}\n") |
| 155 | print(f"survivor {idx}: {m['file']}:{m['span']['start']['line']} covering_heavy={len(tests)}") |
| 156 | |
| 157 | |
| 158 | def cmd_decide(mutants_path, covdir, fastcov_path, fastdir, heavydir, times_path, killtsv, report_md): |
| 159 | mutants = json.load(open(mutants_path)) |
| 160 | names = dict(load_index(covdir)) |
| 161 | regs = {} |
| 162 | keep_names = set() |
| 163 | for fn in ("failed.txt", "nocov.txt"): |
| 164 | path = os.path.join(covdir, fn) |
| 165 | if os.path.exists(path): |
| 166 | keep_names |= {l.strip() for l in open(path) if l.strip()} |
| 167 | for i, name in names.items(): |
| 168 | jpath = os.path.join(covdir, f"{i}.json") |
| 169 | if os.path.exists(jpath): |
| 170 | regs[name] = load_regions(jpath) |
| 171 | else: |
| 172 | keep_names.add(name) |
| 173 | regs[name] = set() |
| 174 | fast = load_regions(fastcov_path) |
| 175 | secs = {} |
| 176 | for line in open(times_path): |
| 177 | parts = line.rstrip("\n").split("\t") |
| 178 | if len(parts) == 2: |
| 179 | secs[parts[0]] = float(parts[1]) |
| 180 | |
| 181 | kills = {} |
| 182 | for name in os.listdir(heavydir): |
| 183 | if name.endswith(".fail"): |
| 184 | idx = int(name.split(".")[0]) |
| 185 | kills[idx] = set(l.strip() for l in open(os.path.join(heavydir, name)) if l.strip()) |
| 186 | for idx in list(kills): |
| 187 | if not kills[idx]: |
| 188 | del kills[idx] |
| 189 | |
| 190 | universe = set(kills) |
| 191 | kept, uncovered = [], set(universe) |
| 192 | tests_of = defaultdict(set) |
| 193 | for idx, ts in kills.items(): |
| 194 | for t in ts: |
| 195 | tests_of[t].add(idx) |
| 196 | while uncovered: |
| 197 | best = max(tests_of, key=lambda t: (len(tests_of[t] & uncovered) / secs.get(t, 1.0), t), default=None) |
| 198 | if best is None or not (tests_of[best] & uncovered): |
| 199 | break |
| 200 | kept.append(best) |
| 201 | uncovered -= tests_of[best] |
| 202 | kept_set = set(kept) |
| 203 | kept_regions = set(fast) |
| 204 | for t in kept: |
| 205 | kept_regions |= set(regs[t]) |
| 206 | rows = [] |
| 207 | deleted_secs = 0.0 |
| 208 | with open(killtsv, "w") as kt: |
| 209 | kt.write("mutant\tfile\tline\treplacement\tkilling_heavy_tests\n") |
| 210 | for idx in sorted(kills): |
| 211 | m = mutants[idx] |
| 212 | kt.write(f"{idx}\t{m['file']}\t{m['span']['start']['line']}\t{m['replacement']}\t{' ; '.join(sorted(kills[idx]))}\n") |
| 213 | for name in sorted(names.values(), key=lambda n: -secs.get(n, 0)): |
| 214 | u_fast = set(regs[name]) - set(fast) |
| 215 | u_kept = set(regs[name]) - kept_regions |
| 216 | kp = {idx for idx, ts in kills.items() if name in ts and not (ts & kept_set)} |
| 217 | if name in kept_set: |
| 218 | cls, action = "kept(cover)", "keep" |
| 219 | elif name in keep_names: |
| 220 | cls, action = "candidate", "keep (failed or no coverage)" |
| 221 | elif PROTECTED.search(name): |
| 222 | cls, action = "protected", "keep (protected)" |
| 223 | else: |
| 224 | cls = "candidate" |
| 225 | if u_kept: |
| 226 | action = "keep (unique coverage)" |
| 227 | elif kp: |
| 228 | action = "keep (unique kills)" |
| 229 | else: |
| 230 | action = "delete" |
| 231 | deleted_secs += secs.get(name, 0) |
| 232 | rows.append((name, cls, len(u_fast), len(u_kept), len(kp), action)) |
| 233 | with open(report_md, "w") as rp: |
| 234 | rp.write("| crate | test | seconds | class | |U(T)| vs fast | |U(T)| vs fast+kept | |K'| | decision |\n") |
| 235 | rp.write("|---|---|---|---|---|---|---|---|\n") |
| 236 | for name, cls, uf, uk, kp_n, action in rows: |
| 237 | rp.write(f"| ec-av1 | {name} | {secs.get(name, 0):.1f} | {cls} | {uf} | {uk} | {kp_n} | {action} |\n") |
| 238 | deletions = [r[0] for r in rows if r[5] == "delete"] |
| 239 | 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}") |
| 240 | with open(os.path.join(os.path.dirname(report_md), os.path.basename(report_md) + ".deletions"), "w") as fh: |
| 241 | fh.write("".join(d + "\n" for d in deletions)) |
| 242 | |
| 243 | |
| 244 | def cmd_regex(sample_json, idx): |
| 245 | |
| 246 | name = json.load(open(sample_json))[int(idx)]["name"] |
| 247 | special = set(".+*?()|[]{}^$\\#&-~") |
| 248 | print("^" + "".join("\\" + c if c in special else c for c in name) + "$") |
| 249 | |
| 250 | |
| 251 | def cmd_name(sample_json, idx): |
| 252 | print(json.load(open(sample_json))[int(idx)]["name"]) |
| 253 | |
| 254 | |
| 255 | NEXTEST_FAIL = re.compile(r"\b(?:FAIL|TIMEOUT|SIGSEGV|SIGABRT)\s+\[[^\]]*\]\s+\S+\s+(\S+)") |
| 256 | NEXTEST_RESULT = re.compile(r"\b(PASS|FAIL|TIMEOUT|SIGSEGV|SIGABRT|LEAK|SKIP)\s+\[") |
| 257 | |
| 258 | |
| 259 | def mutant_logs(d): |
| 260 | if os.path.isfile(d): |
| 261 | return [d] |
| 262 | out = [] |
| 263 | for root, _, files in os.walk(d): |
| 264 | out += [os.path.join(root, f) for f in files if f.endswith(".log")] |
| 265 | return out |
| 266 | |
| 267 | |
| 268 | def cmd_killers(d): |
| 269 | |
| 270 | names = set() |
| 271 | for path in mutant_logs(d): |
| 272 | for line in open(path, errors="replace"): |
| 273 | m = NEXTEST_FAIL.search(line) |
| 274 | if m: |
| 275 | names.add(m.group(1)) |
| 276 | print("\n".join(sorted(names))) |
| 277 | |
| 278 | |
| 279 | def cmd_evidence(d): |
| 280 | |
| 281 | results = rustc = runner = 0 |
| 282 | for path in mutant_logs(d): |
| 283 | for line in open(path, errors="replace"): |
| 284 | if NEXTEST_RESULT.search(line): |
| 285 | results += 1 |
| 286 | if re.search(r"error\[E\d+\]", line): |
| 287 | rustc += 1 |
| 288 | if re.search(r"rev-parse|exec(ution)? failed|No such file or directory|could not execute", line): |
| 289 | runner += 1 |
| 290 | print(f"nextest_results={results} rustc_errors={rustc} runner_errors={runner}") |
| 291 | |
| 292 | |
| 293 | if __name__ == "__main__": |
| 294 | cmd = sys.argv[1] |
| 295 | args = sys.argv[2:] |
| 296 | if cmd == "regex": |
| 297 | cmd_regex(args[0], args[1]) |
| 298 | elif cmd == "name": |
| 299 | cmd_name(args[0], args[1]) |
| 300 | elif cmd == "compact": |
| 301 | compact(args[0], args[1]) |
| 302 | elif cmd == "sample": |
| 303 | cmd_sample(args[0], args[1], int(args[2]), int(args[3]), args[4], args[5]) |
| 304 | elif cmd == "survivors": |
| 305 | cmd_survivors(args[0], args[1], args[2]) |
| 306 | elif cmd == "heavyjobs": |
| 307 | cmd_heavyjobs(args[0], args[1], args[2], args[3], args[4]) |
| 308 | elif cmd == "killers": |
| 309 | cmd_killers(args[0]) |
| 310 | elif cmd == "evidence": |
| 311 | cmd_evidence(args[0]) |
| 312 | elif cmd == "decide": |
| 313 | cmd_decide(*args) |
| 314 | else: |
| 315 | sys.exit(__doc__) |