|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Coverage gate for the files where defects actually surfaced. |
| 3 | +
|
| 4 | +Fails when the line coverage of a hot file drops below the versioned baseline |
| 5 | +in scripts/coverage-baseline.json. The point is not the absolute number: it is |
| 6 | +that a change which removes exercised behaviour cannot land silently. |
| 7 | +
|
| 8 | +Regenerating the baseline is a deliberate act, reviewed like code: |
| 9 | +
|
| 10 | + cargo llvm-cov --lcov --output-path lcov.info |
| 11 | + python3 scripts/coverage_gate.py --write-baseline lcov.info scripts/coverage-baseline.json |
| 12 | +
|
| 13 | +Only ever move it upward in review. |
| 14 | +""" |
| 15 | + |
| 16 | +import fnmatch |
| 17 | +import json |
| 18 | +import sys |
| 19 | + |
| 20 | +HOT_GLOBS = [ |
| 21 | + "src/doctor.rs", |
| 22 | + "src/cli/**", |
| 23 | + "src/config/**", |
| 24 | + "src/scan_health.rs", |
| 25 | + "src/scanner/orchestrator.rs", |
| 26 | + "src/scanner/phases/llm_phases/**", |
| 27 | +] |
| 28 | + |
| 29 | + |
| 30 | +def canonical(path: str) -> str: |
| 31 | + path = path.replace("\\", "/") |
| 32 | + if "/src/" in path: |
| 33 | + return "src/" + path.split("/src/", 1)[1] |
| 34 | + if path.startswith("./"): |
| 35 | + return path[2:] |
| 36 | + return path |
| 37 | + |
| 38 | + |
| 39 | +def parse_lcov(lcov_path): |
| 40 | + """Return {canonical_path: {line: hit_count}}, merging duplicate records. |
| 41 | +
|
| 42 | + cargo-llvm-cov can emit one record per test binary; the same source line |
| 43 | + hit in either counts as hit, so records merge by summing counts per line. |
| 44 | + """ |
| 45 | + records = {} |
| 46 | + current = None |
| 47 | + with open(lcov_path, encoding="utf-8", errors="replace") as fh: |
| 48 | + for raw in fh: |
| 49 | + line = raw.strip() |
| 50 | + if line.startswith("SF:"): |
| 51 | + current = canonical(line[3:]) |
| 52 | + records.setdefault(current, {}) |
| 53 | + elif line.startswith("DA:") and current is not None: |
| 54 | + fields = line[3:].split(",") |
| 55 | + try: |
| 56 | + lineno = int(fields[0]) |
| 57 | + hits = int(fields[1]) |
| 58 | + except (IndexError, ValueError): |
| 59 | + continue |
| 60 | + records[current][lineno] = records[current].get(lineno, 0) + hits |
| 61 | + elif line == "end_of_record": |
| 62 | + current = None |
| 63 | + return {path: lines for path, lines in records.items() if lines} |
| 64 | + |
| 65 | + |
| 66 | +def tally(lines): |
| 67 | + found = len(lines) |
| 68 | + hit = sum(1 for count in lines.values() if count > 0) |
| 69 | + return hit, found |
| 70 | + |
| 71 | + |
| 72 | +def pct(hit, found): |
| 73 | + return f"{100.0 * hit / found:.2f}%" if found else "100.00%" |
| 74 | + |
| 75 | + |
| 76 | +def write_baseline(records, baseline_path): |
| 77 | + files = {} |
| 78 | + for path, lines in sorted(records.items()): |
| 79 | + if not any(fnmatch.fnmatch(path, glob) for glob in HOT_GLOBS): |
| 80 | + continue |
| 81 | + hit, found = tally(lines) |
| 82 | + files[path] = {"lines_hit": hit, "lines_found": found} |
| 83 | + payload = { |
| 84 | + "comment": ( |
| 85 | + "Line-coverage floor for the hot files, as (lines_hit, lines_found). " |
| 86 | + "The ci.yml coverage job fails a build when a file falls below its " |
| 87 | + "recorded pair. Regenerate with --write-baseline after adding tests; " |
| 88 | + "in review, only ever upward." |
| 89 | + ), |
| 90 | + "files": files, |
| 91 | + } |
| 92 | + with open(baseline_path, "w", encoding="utf-8") as fh: |
| 93 | + json.dump(payload, fh, indent=2, sort_keys=True) |
| 94 | + fh.write("\n") |
| 95 | + print(f"baseline written: {len(files)} hot files to {baseline_path}") |
| 96 | + |
| 97 | + |
| 98 | +def gate(records, baseline_path): |
| 99 | + with open(baseline_path, encoding="utf-8") as fh: |
| 100 | + baseline = json.load(fh) |
| 101 | + problems = [] |
| 102 | + checked = 0 |
| 103 | + for path, entry in sorted(baseline["files"].items()): |
| 104 | + hit_b = int(entry["lines_hit"]) |
| 105 | + found_b = int(entry["lines_found"]) |
| 106 | + if path not in records: |
| 107 | + problems.append( |
| 108 | + f"{path}: in the baseline but absent from the coverage report - " |
| 109 | + f"renamed or deleted; update scripts/coverage-baseline.json" |
| 110 | + ) |
| 111 | + continue |
| 112 | + hit_c, found_c = tally(records[path]) |
| 113 | + checked += 1 |
| 114 | + # Integer cross-multiplication: hit_c/found_c < hit_b/found_b exactly. |
| 115 | + if found_c == 0 and found_b > 0: |
| 116 | + problems.append( |
| 117 | + f"{path}: no instrumented lines in the coverage report " |
| 118 | + f"(baseline was {hit_b}/{found_b})" |
| 119 | + ) |
| 120 | + elif hit_c * found_b < hit_b * found_c: |
| 121 | + problems.append( |
| 122 | + f"{path}: line coverage fell: {hit_c}/{found_c} ({pct(hit_c, found_c)}) " |
| 123 | + f"< baseline {hit_b}/{found_b} ({pct(hit_b, found_b)}) - add tests, " |
| 124 | + f"or update scripts/coverage-baseline.json deliberately" |
| 125 | + ) |
| 126 | + if problems: |
| 127 | + print("coverage gate: FAILED", file=sys.stderr) |
| 128 | + for problem in problems: |
| 129 | + print(f" {problem}", file=sys.stderr) |
| 130 | + return 1 |
| 131 | + print(f"coverage gate: {checked} hot files at or above the baseline") |
| 132 | + return 0 |
| 133 | + |
| 134 | + |
| 135 | +def main(argv): |
| 136 | + if "--help" in argv: |
| 137 | + print(__doc__) |
| 138 | + return 0 |
| 139 | + if len(argv) == 4 and argv[1] == "--write-baseline": |
| 140 | + write_baseline(parse_lcov(argv[2]), argv[3]) |
| 141 | + return 0 |
| 142 | + if len(argv) == 3: |
| 143 | + return gate(parse_lcov(argv[1]), argv[2]) |
| 144 | + print( |
| 145 | + "usage: coverage_gate.py <lcov.info> <baseline.json> (gate)\n" |
| 146 | + " coverage_gate.py --write-baseline <lcov.info> <baseline.json>", |
| 147 | + file=sys.stderr, |
| 148 | + ) |
| 149 | + return 2 |
| 150 | + |
| 151 | + |
| 152 | +if __name__ == "__main__": |
| 153 | + sys.exit(main(sys.argv)) |
0 commit comments