stocks / scripts /mutation_gate.py
user
python version
ee446e8
Raw History Blame Contribute Delete
11.5 kB
#!/usr/bin/env python3
"""Mutation-score gate: run mutmut per scoped file and enforce a threshold.
Why a gate rather than a report: line coverage says a line executed, not that
a wrong answer on it would fail anything. A surviving mutant is a behaviour
the test suite does not actually pin -- exactly the class of bug that reaches
a trader as a wrong signal. This turns that number into something CI can
fail on, and it fails *per file* so a big new module cannot hide behind an
already-good one.
Usage:
python scripts/mutation_gate.py # check every scoped file
python scripts/mutation_gate.py core/dsl/security.py
python scripts/mutation_gate.py --record # re-measure and rewrite baselines
python scripts/mutation_gate.py --list # show the config, run nothing
Each scope pins the pytest selection used for its mutants. Running the whole
suite per mutant is what made `make mutation` an overnight job; a scoped file
only needs the tests that can actually observe it.
Exit codes: 0 all scopes at or above threshold, 1 at least one below,
2 a scope could not be measured.
"""
import argparse
import json
import shutil
import subprocess
import sys
from collections import Counter
from dataclasses import dataclass
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
PYPROJECT = PROJECT_ROOT / "pyproject.toml"
CONFIG_PATH = PROJECT_ROOT / "mutation-gate.json"
# Only these statuses count as "the test suite caught it". "no tests" and
# "skipped" are not kills: a scope whose mutants nothing exercises would
# otherwise score 100% for the wrong reason.
KILLED_STATUSES = {"killed", "caught by type check"}
# Why a scope is skipped, kept here so --record does not have to invent a
# reason when it rewrites the config.
SKIP_REASONS: dict[str, str] = {}
# Thresholds are recorded to one decimal place; compare with half that much
# slack so a baseline score does not fail against its own rounding.
ROUNDING_TOLERANCE = 0.05
@dataclass(frozen=True)
class Scope:
"""One mutated file plus the tests that can observe it."""
path: str
tests: tuple[str, ...]
threshold: float | None # None = measure only, never gate
enabled: bool = True # False = skipped, with the reason in the config
def load_config() -> list[Scope]:
data = json.loads(CONFIG_PATH.read_text())
for entry in data["scopes"]:
if not entry.get("enabled", True):
SKIP_REASONS[entry["path"]] = entry.get("skip_reason", "disabled in config")
return [
Scope(
path=entry["path"],
tests=tuple(entry["tests"]),
threshold=entry.get("threshold"),
enabled=entry.get("enabled", True),
)
for entry in data["scopes"]
]
def save_config(scopes: list[Scope]) -> None:
data = {
"_comment": (
"Generated by scripts/mutation_gate.py --record. `threshold` is a "
"percentage of mutants killed (plus caught by the type checker). "
"null means measure-only: the score is reported, never enforced."
),
"scopes": [
{
"path": s.path,
"tests": list(s.tests),
"threshold": s.threshold,
**({} if s.enabled else {"enabled": False, "skip_reason": SKIP_REASONS.get(s.path, "")}),
}
for s in scopes
],
}
CONFIG_PATH.write_text(json.dumps(data, indent=2) + "\n")
def _patch_pyproject(paths: list[str], tests: list[str]) -> str:
"""Temporarily rewrite [tool.mutmut] for a scoped run.
Returns the original text so the caller can restore it. A SIGTERM mid-run
would skip a plain finally in a subprocess wrapper, so the caller also
installs a signal handler; see main().
"""
original = PYPROJECT.read_text()
lines = original.split("\n")
out: list[str] = []
in_mutmut = False
inserted_mutate = inserted_tests = False
for line in lines:
stripped = line.strip()
if stripped == "[tool.mutmut]":
in_mutmut = True
elif stripped.startswith("[") and in_mutmut:
in_mutmut = False
# If the key was already emitted (injected just above), drop the
# original line rather than emitting the key twice.
if in_mutmut and stripped.startswith("only_mutate"):
if not inserted_mutate:
out.append(f"only_mutate = {paths!r}")
inserted_mutate = True
continue
if in_mutmut and stripped.startswith("pytest_add_cli_args_test_selection"):
if not inserted_tests:
out.append(f"pytest_add_cli_args_test_selection = {tests!r}")
inserted_tests = True
continue
out.append(line)
# Exact-key matches only: a prefix match on "pytest_add_cli_args" would
# also fire for the shorter key above and emit the key twice, which
# tomllib rejects outright.
if in_mutmut and not inserted_mutate and stripped.startswith("source_paths"):
out.append(f"only_mutate = {paths!r}")
inserted_mutate = True
if (
in_mutmut
and not inserted_tests
and stripped.startswith("pytest_add_cli_args_test_selection")
or in_mutmut
and not inserted_tests
and stripped.startswith("pytest_add_cli_args ")
):
out.append(f"pytest_add_cli_args_test_selection = {tests!r}")
inserted_tests = True
if not (inserted_mutate and inserted_tests):
raise RuntimeError("could not inject only_mutate/test selection into [tool.mutmut]")
PYPROJECT.write_text("\n".join(out))
return original
def read_scores(path: str) -> Counter:
"""Per-status mutant counts for one already-run file.
Reads mutmut's own result store rather than scraping its progress bar, so
the numbers cannot drift with a terminal-width or emoji change.
"""
from mutmut.mutation.data import SourceFileMutationData
from mutmut.stats import status_by_exit_code
data = SourceFileMutationData(path=path)
data.load()
return Counter(status_by_exit_code[code] for code in data.exit_code_by_key.values())
def run_scope(scope: Scope) -> Counter:
"""Clear prior results, mutate one file, return its status counts."""
mutants_dir = PROJECT_ROOT / "mutants"
if mutants_dir.exists():
shutil.rmtree(mutants_dir)
original = _patch_pyproject([scope.path], list(scope.tests))
try:
result = subprocess.run(
[sys.executable, "-m", "mutmut", "run", "--max-children", "8"],
cwd=PROJECT_ROOT,
capture_output=True,
text=True,
timeout=3600,
)
if result.returncode != 0:
sys.stderr.write(result.stdout[-4000:] + "\n" + result.stderr[-2000:] + "\n")
raise RuntimeError(f"mutmut run failed for {scope.path}")
finally:
PYPROJECT.write_text(original)
return read_scores(scope.path)
def score(counts: Counter) -> tuple[int, int, float | None]:
killed = sum(n for status, n in counts.items() if status in KILLED_STATUSES)
total = sum(counts.values())
if total == 0:
return killed, total, None
return killed, total, 100.0 * killed / total
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("paths", nargs="*", help="scope paths to check (default: all)")
parser.add_argument("--record", action="store_true", help="rewrite thresholds from this run")
parser.add_argument("--list", action="store_true", help="print the config and exit")
args = parser.parse_args()
scopes = load_config()
if args.paths:
scopes = [s for s in scopes if s.path in args.paths]
missing = set(args.paths) - {s.path for s in scopes}
if missing:
sys.stderr.write(f"Not in {CONFIG_PATH.name}: {', '.join(sorted(missing))}\n")
return 2
if args.list:
for s in scopes:
if not s.enabled:
print(f"{s.path:<40} {'skipped':>12} {SKIP_REASONS.get(s.path, '')}")
continue
enforced = f"{s.threshold:.1f}%" if s.threshold is not None else "measure-only"
print(f"{s.path:<40} {enforced:>12} tests={','.join(s.tests)}")
return 0
# mutmut rewrites pyproject.toml for a scoped run. A raw SIGTERM would
# skip the finally below and leave only_mutate stuck in a shared file, so
# restore synchronously from the handler too.
import signal
def _restore(signum: int, _frame: object) -> None:
backup = PYPROJECT.with_suffix(".toml.mutation_gate_backup")
if backup.exists():
shutil.copy2(backup, PYPROJECT)
backup.unlink()
sys.exit(128 + signum)
backup = PYPROJECT.with_suffix(".toml.mutation_gate_backup")
if backup.exists():
shutil.copy2(backup, PYPROJECT)
backup.unlink()
shutil.copy2(PYPROJECT, backup)
signal.signal(signal.SIGTERM, _restore)
signal.signal(signal.SIGINT, _restore)
try:
results: list[tuple[Scope, Counter]] = []
for scope in scopes:
if not scope.enabled:
print(f"skipping {scope.path}: {SKIP_REASONS.get(scope.path, 'disabled in config')}")
continue
print(f"mutating {scope.path} (tests: {', '.join(scope.tests)}) ...", flush=True)
counts = run_scope(scope)
results.append((scope, counts))
killed, total, pct = score(counts)
print(f" {killed}/{total} killed" + (f" = {pct:.1f}%" if pct is not None else " (no mutants)"))
finally:
if backup.exists():
shutil.copy2(backup, PYPROJECT)
backup.unlink()
shutil.rmtree(PROJECT_ROOT / "mutants", ignore_errors=True)
print()
failures = 0
unmeasurable = 0
updated: list[Scope] = []
for scope, counts in results:
killed, total, pct = score(counts)
if pct is None:
print(f"UNMEASURABLE {scope.path}: no mutants were generated")
unmeasurable += 1
updated.append(scope)
continue
if args.record:
updated.append(Scope(scope.path, scope.tests, round(pct, 1)))
print(f"recorded {scope.path}: {pct:.1f}%")
continue
if scope.threshold is None:
print(f"{scope.path:<40} {pct:5.1f}% (measure-only)")
continue
# Thresholds are stored rounded to one decimal, so a scope that sits
# exactly on its baseline (14/18 = 77.777...% recorded as 77.8) would
# otherwise fail on rounding alone. Half a unit of stored precision.
if pct + ROUNDING_TOLERANCE < scope.threshold:
print(f"BELOW THRESHOLD {scope.path}: {pct:.1f}% < {scope.threshold:.1f}%")
failures += 1
else:
print(f"{scope.path:<40} {pct:5.1f}% >= {scope.threshold:.1f}%")
if args.record and updated:
# Merge into the full config: a scoped --record must not drop the
# scopes it did not run.
recorded = {s.path: s for s in updated}
save_config([recorded.get(s.path, s) for s in load_config()])
print(f"\nrewrote {CONFIG_PATH.name}")
if unmeasurable:
return 2
return 1 if failures else 0
if __name__ == "__main__":
sys.exit(main())