Coverage for scripts/mutation_check.py: 100%
112 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""A small mutation check for the safety, admission and ledger modules (V6.6.4).
3A test suite that passes proves little if it would also pass with the code broken. This changes one thing at a time in a module (a comparison flipped, `and` swapped for `or`, a `not` removed,
4a constant moved by one, `+` swapped for `-`), runs that module's tests, and counts a change the tests did not notice as a survivor. A survivor in a safety or admission path needs a test that
5kills it, or a written reason it changes nothing (an equivalent mutant). It samples a fixed number of sites per file with a fixed seed, so a run is repeatable.
7It edits the real file in place and restores it in a `finally` (and checks the restore), so run it on a Codespace or a throwaway checkout, never on a tree with uncommitted work in those files.
9 python scripts/mutation_check.py --out ml/evaluation/v664/mutation.json [--max-per-file 40] [--only evaluation/generation_registry.py]
10"""
12from __future__ import annotations
14import argparse
15import ast
16import json
17import random
18import subprocess
19import sys
20import time
21from dataclasses import dataclass
22from pathlib import Path
24ROOT = Path(__file__).resolve().parents[1]
26TARGETS: dict[str, tuple[str, ...]] = {
27 "evaluation/generation_registry.py": ("tests/test_generation_registry.py", "tests/test_v664_mutation_ledgers.py", "tests/test_formal_differential_admission.py"),
28 "evaluation/forward_ledger.py": ("tests/test_forward_ledger.py", "tests/test_v664_mutation_ledgers.py", "tests/test_v664_late_session.py", "tests/test_formal_differential_session_resolve.py"),
29 "evaluation/research_cells.py": ("tests/test_research_cells.py", "tests/test_v664_mutation_ledgers.py", "tests/test_formal_differential_holdout_once.py"),
30 "portfolio/generation_blend.py": ("tests/test_generation_blend.py", "tests/test_v664_mutation_ledgers.py", "tests/test_formal_differential_generation_blend.py", "tests/test_formal_differential_generation_glide.py"),
31 "execution/order_gate.py": ("tests/test_order_gate.py", "tests/test_v664_mutation_safety.py", "tests/test_formal_differential_order_gate.py"),
32 "risk_controls.py": ("tests/test_risk_controls.py", "tests/test_v664_mutation_safety.py", "tests/test_v664_mutation_ledgers.py", "tests/test_formal_differential_risk_controls.py"),
33 "risk/kill_switch.py": ("tests/test_kill_switch.py", "tests/test_v664_mutation_safety.py", "tests/test_v664_mutation_ledgers.py", "tests/test_formal_differential_kill_switch.py"),
34 # V6.6.5: accounts that only tighten, who may lock, secrets that never show, the live gate, the field test's gate
35 "execution/accounts.py": ("tests/test_accounts.py", "tests/test_accounts_parity.py", "tests/test_formal_differential_account_overrides.py"),
36 "monitoring/auth.py": ("tests/test_auth.py", "tests/test_formal_differential_authorize.py"),
37 "execution/secrets.py": ("tests/test_secrets.py", "tests/test_secrets_property.py"),
38 "execution/live_readiness.py": ("tests/test_live_readiness.py",),
39 "execution/field_test.py": ("tests/test_field_test.py",),
40}
41COMPARE = {ast.Lt: ast.LtE, ast.LtE: ast.Lt, ast.Gt: ast.GtE, ast.GtE: ast.Gt, ast.Eq: ast.NotEq, ast.NotEq: ast.Eq}
42ARITHMETIC = {ast.Add: ast.Sub, ast.Sub: ast.Add}
43BOOLEAN = {ast.And: ast.Or, ast.Or: ast.And}
46@dataclass(frozen=True)
47class Site:
48 index: int # position among the tree's nodes in ast.walk order
49 line: int
50 kind: str
53def sites(source: str) -> list[Site]:
54 """Every place the operators can change something, in a stable order. Docstrings and annotations are left alone."""
55 tree = ast.parse(source)
56 found: list[Site] = []
57 for index, node in enumerate(ast.walk(tree)):
58 line = getattr(node, "lineno", 0)
59 if isinstance(node, ast.Compare) and any(type(op) in COMPARE for op in node.ops):
60 found.append(Site(index, line, "compare"))
61 elif isinstance(node, ast.BoolOp):
62 found.append(Site(index, line, "boolop"))
63 elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
64 found.append(Site(index, line, "not"))
65 elif isinstance(node, ast.Constant) and isinstance(node.value, bool):
66 found.append(Site(index, line, "bool"))
67 elif isinstance(node, ast.Constant) and isinstance(node.value, int) and not isinstance(node.value, bool) and node.value not in (0, 1):
68 found.append(Site(index, line, "int"))
69 elif isinstance(node, ast.BinOp) and type(node.op) in ARITHMETIC:
70 found.append(Site(index, line, "arithmetic"))
71 return found
74def mutate(source: str, site: Site) -> str:
75 """The source with one change at `site`."""
76 tree = ast.parse(source)
77 target = list(ast.walk(tree))[site.index]
78 if isinstance(target, ast.Compare):
79 target.ops = [COMPARE.get(type(op), type(op))() if position == 0 else op for position, op in enumerate(target.ops)]
80 elif isinstance(target, ast.BoolOp):
81 target.op = BOOLEAN[type(target.op)]()
82 elif isinstance(target, ast.UnaryOp):
83 replacement = target.operand
84 for parent in ast.walk(tree):
85 for name, value in ast.iter_fields(parent):
86 if value is target:
87 setattr(parent, name, replacement)
88 elif isinstance(value, list):
89 setattr(parent, name, [replacement if item is target else item for item in value])
90 elif isinstance(target, ast.Constant):
91 target.value = (not target.value) if isinstance(target.value, bool) else target.value + 1
92 elif isinstance(target, ast.BinOp):
93 target.op = ARITHMETIC[type(target.op)]()
94 ast.fix_missing_locations(tree)
95 return ast.unparse(tree) + "\n"
98def sample(found: list[Site], limit: int, seed: int) -> list[Site]:
99 """A fixed sample, in source order, so two runs test the same changes."""
100 if len(found) <= limit:
101 return list(found)
102 rng = random.Random(seed)
103 return sorted(rng.sample(found, limit), key=lambda site: site.index)
106def run_tests(tests: tuple[str, ...], timeout: float) -> bool:
107 """True when the tests pass (the change went unnoticed). A timeout or a crash counts as noticed."""
108 command = [sys.executable, "-m", "pytest", "-x", "-q", "-p", "no:cacheprovider", "--no-header", *[t for t in tests if (ROOT / t).exists()]]
109 try:
110 result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, timeout=timeout, check=False)
111 except subprocess.TimeoutExpired:
112 return False
113 return result.returncode == 0
116def check_file(relative: str, tests: tuple[str, ...], *, limit: int, seed: int, timeout: float, emit=print) -> dict:
117 path = ROOT / relative
118 original = path.read_text(encoding="utf-8")
119 if not run_tests(tests, timeout * 3):
120 return {"file": relative, "error": "the tests do not pass unmutated: nothing to measure"}
121 chosen = sample(sites(original), limit, seed)
122 survivors, killed = [], 0
123 try:
124 for site in chosen:
125 path.write_text(mutate(original, site), encoding="utf-8", newline="\n")
126 if run_tests(tests, timeout):
127 survivors.append({"line": site.line, "kind": site.kind})
128 emit(f"{relative}:{site.line} {site.kind} survived")
129 else:
130 killed += 1
131 finally:
132 path.write_text(original, encoding="utf-8", newline="\n")
133 if path.read_text(encoding="utf-8") != original:
134 raise SystemExit(f"{relative} was not restored")
135 total = len(chosen)
136 return {
137 "file": relative, "sites": len(sites(original)), "tried": total, "killed": killed, "survived": len(survivors), "kill_rate": (killed / total) if total else None, "survivors": survivors,
138 "tests": [t for t in tests if (ROOT / t).exists()],
139 }
142def main(argv: list[str] | None = None) -> int:
143 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
144 parser.add_argument("--out", required=True)
145 parser.add_argument("--max-per-file", type=int, default=40)
146 parser.add_argument("--seed", type=int, default=664)
147 parser.add_argument("--timeout", type=float, default=120.0)
148 parser.add_argument("--only", nargs="*", default=None)
149 args = parser.parse_args(argv)
150 started = time.time()
151 report = {"seed": args.seed, "max_per_file": args.max_per_file, "files": []}
152 for relative, tests in TARGETS.items():
153 if args.only and relative not in args.only:
154 continue
155 result = check_file(relative, tests, limit=args.max_per_file, seed=args.seed, timeout=args.timeout)
156 report["files"].append(result)
157 print(json.dumps({key: result.get(key) for key in ("file", "tried", "killed", "survived", "kill_rate", "error")}), flush=True)
158 report["seconds"] = round(time.time() - started)
159 Path(args.out).parent.mkdir(parents=True, exist_ok=True)
160 Path(args.out).write_text(json.dumps(report, indent=1), encoding="utf-8", newline="\n")
161 return 0
164if __name__ == "__main__":
165 raise SystemExit(main())