evalmut 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
evalmut/outcome.py ADDED
@@ -0,0 +1,97 @@
1
+ """What a mutation did to an eval — the four outcomes, and the two ways an eval lies.
2
+
3
+ A mutation injects a *known* change into the system-under-test's output and reruns
4
+ the grader that was supposed to be watching. There are two kinds of change, and an
5
+ eval can be wrong about either:
6
+
7
+ DEFECT mutation — the output is now genuinely WRONG. A correct grader must reject
8
+ it. If the grader still passes, the eval is BLIND to that defect
9
+ class: a real regression of that shape would ship green.
10
+
11
+ EQUIVALENT mutation — the output changed but is still CORRECT (whitespace, a
12
+ trailing disclaimer after a complete answer, a reordering the
13
+ spec allows). A correct grader must still pass it. If the grader
14
+ now fails, the eval is BRITTLE: it cries wolf on cosmetic change,
15
+ and a brittle check is quietly recalibrated or ignored until it
16
+ stops catching the real thing too.
17
+
18
+ Most eval tooling only ever asks the first question. Both are real failure modes in
19
+ the corpus this tool is mined from — a suite that misses regressions and a suite that
20
+ flags correct answers are both suites you cannot trust — so both are first-class here.
21
+
22
+ The classic mutation-testing subtlety (the "equivalent mutant" problem) is handled
23
+ structurally rather than statistically: an operator only *applies* to a case when it
24
+ can establish which polarity it is in for THAT case — i.e. that the mutated output is
25
+ provably wrong (DEFECT) or provably still correct (EQUIVALENT) relative to the case's
26
+ own reference answer. Where it cannot establish that, it returns NA and is excluded
27
+ from the score. So a MISSED/FLAGGED is never a guess: by construction the mutant had a
28
+ known correct answer and the grader disagreed with it.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ from enum import Enum
33
+
34
+
35
+ class Polarity(str, Enum):
36
+ """Whether a mutation makes the output wrong, or leaves it correct."""
37
+
38
+ DEFECT = "defect" # mutated output is WRONG; a correct grader must REJECT it
39
+ EQUIVALENT = "equivalent" # mutated output is still CORRECT; a correct grader must ACCEPT it
40
+
41
+
42
+ class OperatorType(str, Enum):
43
+ """What a survival *means* — the difference between a broken grader and a missing one.
44
+
45
+ A DEFECT mutation that survives is always a hole, but not always the grader's fault,
46
+ and saying which is the difference between a fair report and an unfair one:
47
+
48
+ KILL — a sound grader of this kind MUST catch this. Survival is a BLIND SPOT:
49
+ the check is present and broken. Fix the check.
50
+ DIAGNOSTIC — this grader family is structurally blind to this shape BY DESIGN (e.g.
51
+ gradecore's valid_json checks key presence, never value type, and says
52
+ so). Survival is a COVERAGE GAP: no check in the suite guards this, which
53
+ is worth knowing but is not this grader misbehaving. Add a check.
54
+ SANITY — a floor probe (blank / garbage output). Survival means the grader asserts
55
+ nothing about the answer at all — a VACUOUS check that cannot fail.
56
+ """
57
+
58
+ KILL = "kill"
59
+ DIAGNOSTIC = "diagnostic"
60
+ SANITY = "sanity"
61
+
62
+
63
+ class Outcome(str, Enum):
64
+ """What the grader actually did, judged against what a correct grader should do."""
65
+
66
+ CAUGHT = "caught" # grader behaved correctly (rejected a defect / accepted an equivalent)
67
+ MISSED = "missed" # DEFECT survived: grader passed a genuinely-wrong output -> BLIND SPOT
68
+ FLAGGED = "flagged" # EQUIVALENT broke: grader failed a still-correct output -> BRITTLE SPOT
69
+ ERROR = "error" # grader raised on a well-formed mutant -> it cannot render a verdict at all
70
+ NA = "na" # operator could not apply here (no correctness boundary it could cross)
71
+
72
+ @property
73
+ def is_hole(self) -> bool:
74
+ """A hole is any way the eval got the answer wrong: a miss, a false flag, or a
75
+ crash. A grader that raises on a valid mutant is broken in its own way — it cannot
76
+ even produce a verdict — so it counts as a hole, reported apart from the others."""
77
+ return self in (Outcome.MISSED, Outcome.FLAGGED, Outcome.ERROR)
78
+
79
+ @property
80
+ def counts_toward_score(self) -> bool:
81
+ """NA and ERROR are excluded from the mutation score. NA is inapplicable; ERROR is
82
+ an undetermined verdict (the grader crashed, so it neither caught nor missed) —
83
+ counting a crash as a catch would let a fragile grader inflate its score, which is
84
+ exactly the conflation the SANITY probes exist to expose."""
85
+ return self not in (Outcome.NA, Outcome.ERROR)
86
+
87
+
88
+ def outcome_for(polarity: Polarity, grader_passed: bool) -> Outcome:
89
+ """Given the mutation's polarity and whether the grader passed the mutant, what
90
+ happened. This is the whole judgment, and it is deliberately tiny: the honesty
91
+ lives in the operator deciding its polarity per case, not in a fuzzy threshold here.
92
+ """
93
+ if polarity is Polarity.DEFECT:
94
+ # A wrong output. Correct grader rejects it (not passed) -> CAUGHT.
95
+ return Outcome.CAUGHT if not grader_passed else Outcome.MISSED
96
+ # EQUIVALENT: a still-correct output. Correct grader accepts it (passed) -> CAUGHT.
97
+ return Outcome.CAUGHT if grader_passed else Outcome.FLAGGED
evalmut/py.typed ADDED
File without changes
evalmut/report.py ADDED
@@ -0,0 +1,112 @@
1
+ """Render a Report as text a person can act on.
2
+
3
+ The score is one line and the least important. The body is the holes, grouped by how
4
+ alarming they are and each carrying the real defect it is the shape of — because
5
+ "your grounding check passed a fabricated clause (the SciFact 'vaccines cause autism'
6
+ shape)" is a thing to go fix, and "0.82" is not.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ from .outcome import Outcome
13
+ from .score import Report, Tally
14
+
15
+ _BAR = "─" * 72
16
+
17
+ # Grader detail and mutant echoes are attacker-influenced text — they can carry a model's
18
+ # output verbatim. Escape C0/C1 control chars (except \t and \n) at render time so a mutant
19
+ # can't smuggle ANSI/terminal control sequences into a terminal or CI log. The tool's own
20
+ # box-drawing glyphs live above U+009F and in non-untrusted literals, so they're untouched.
21
+ _CTRL = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
22
+
23
+
24
+ def _safe(s: str) -> str:
25
+ return _CTRL.sub(lambda m: repr(m.group())[1:-1], s)
26
+
27
+
28
+ def _pct(t: Tally) -> str:
29
+ return f"{t.score * 100:.0f}%" if t.applied else " —"
30
+
31
+
32
+ def render(report: Report, *, verbose: bool = False) -> str:
33
+ out: list[str] = []
34
+ w = out.append
35
+ t = report.total
36
+
37
+ w(_BAR)
38
+ w(" evalmut — does your eval actually check anything?")
39
+ w(_BAR)
40
+ w(f" mutation score {t.score * 100:5.1f}% "
41
+ f"({t.caught} caught / {t.applied} applied; {t.na} n/a)")
42
+ if report.crashing_defects: # the score excludes these — say so, loudly, next to it
43
+ w(f" ⚠ undetermined {len(report.crashing_defects)} defect mutation(s) CRASHED the "
44
+ f"grader (excluded from the score — a crash is not a catch)")
45
+ holes = len(report.holes)
46
+ if holes == 0:
47
+ w(" holes none — every applied mutation was handled correctly")
48
+ else:
49
+ parts = []
50
+ if report.vacuous: parts.append(f"{len(report.vacuous)} vacuous")
51
+ if report.blind_spots: parts.append(f"{len(report.blind_spots)} blind")
52
+ if report.errors: parts.append(f"{len(report.errors)} error")
53
+ if report.brittle_spots:parts.append(f"{len(report.brittle_spots)} brittle")
54
+ if report.coverage_gaps:parts.append(f"{len(report.coverage_gaps)} coverage-gap")
55
+ w(f" holes {holes} ({', '.join(parts)})")
56
+
57
+ if getattr(report, "baseline_failures", ()): # loud, never swallowed
58
+ w("")
59
+ w(" ⚠ BASELINE FAILURES — these cases were skipped (grader fails its own reference):")
60
+ for be in report.baseline_failures:
61
+ w(f" {_safe(str(be))}")
62
+
63
+ _section(w, "VACUOUS — the grader asserts nothing about the answer and cannot fail",
64
+ report.vacuous, verbose)
65
+ _section(w, "BLIND SPOTS — a real defect shipped green; the check is present and broken",
66
+ report.blind_spots, verbose)
67
+ _section(w, "ERRORS — grader crashed on a well-formed mutant (a crash on a DEFECT is an "
68
+ "undetermined blind spot, not a pass)",
69
+ report.errors, verbose)
70
+ _section(w, "BRITTLE SPOTS — the check fails a still-correct output (a false-positive)",
71
+ report.brittle_spots, verbose)
72
+ _section(w, "COVERAGE GAPS — no check guards this shape (a missing grader, not a broken one)",
73
+ report.coverage_gaps, verbose)
74
+
75
+ if verbose:
76
+ w("")
77
+ w(" per-grader:")
78
+ for gid, gt in sorted(report.by_grader.items()):
79
+ w(f" {_pct(gt):>4} {gid:<22} caught {gt.caught} missed {gt.missed} "
80
+ f"flagged {gt.flagged} n/a {gt.na}")
81
+
82
+ w(_BAR)
83
+ return "\n".join(out)
84
+
85
+
86
+ def _section(w, title: str, items, verbose: bool) -> None:
87
+ if not items:
88
+ return
89
+ w("")
90
+ w(f" {title}")
91
+ for h in items:
92
+ arrow = {Outcome.MISSED: "passed", Outcome.FLAGGED: "failed",
93
+ Outcome.ERROR: "crashed on"}.get(h.outcome, "handled")
94
+ w(f" • {h.grader_id} / {h.case_name}")
95
+ w(f" mutation : {h.operator_id} — {h.defect_shape}")
96
+ w(f" grader : {arrow} the mutant ({_safe(h.detail)})")
97
+ w(f" mined from: {h.real_origin}")
98
+ if verbose and h.mutant_preview:
99
+ w(f" mutant : {_safe(h.mutant_preview)}")
100
+ if h.grader_error:
101
+ w(f" note : grader crashed — {_safe(h.grader_error)}")
102
+
103
+
104
+ def render_short(report: Report) -> str:
105
+ """One line, for CI: score, hole counts, exit-worthy."""
106
+ t = report.total
107
+ return (f"evalmut {t.score*100:.0f}% "
108
+ f"vacuous={len(report.vacuous)} blind={len(report.blind_spots)} "
109
+ f"error={len(report.errors)} brittle={len(report.brittle_spots)} "
110
+ f"gap={len(report.coverage_gaps)}"
111
+ + (f" ⚠undetermined={len(report.crashing_defects)}"
112
+ if report.crashing_defects else ""))
evalmut/runner.py ADDED
@@ -0,0 +1,162 @@
1
+ """Run a set of operators against a suite and record what each mutation did.
2
+
3
+ The loop is deliberately small and deterministic — no sampling, no LLM, so a run
4
+ reproduces exactly, the same property gradecore is built on. For each case it first
5
+ confirms the baseline is green (mutation testing on a red baseline is meaningless),
6
+ then for each operator applies the mutation and reruns the grader.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Optional, Sequence
12
+
13
+ from gradecore import GradeInput, Verdict
14
+
15
+ from .case import EvalCase
16
+ from .operator import MutationOperator
17
+ from .operators import _clear_grader_id, _prime_grader_id
18
+ from .outcome import OperatorType, Outcome, Polarity, outcome_for
19
+
20
+
21
+ class BaselineError(Exception):
22
+ """A case whose grader does not pass its own reference output. Mutation testing
23
+ cannot proceed on it — the reference is mis-specified — so it is reported by name
24
+ rather than silently skipped."""
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class MutationResult:
29
+ case_name: str
30
+ grader_id: str
31
+ operator_id: str
32
+ family: str
33
+ polarity: Polarity
34
+ op_type: OperatorType
35
+ outcome: Outcome
36
+ real_origin: str
37
+ defect_shape: str
38
+ detail: str # what the grader said on the mutant
39
+ mutant_preview: str # a one-line echo of the mutated field
40
+ grader_error: Optional[str] = None # set if the grader raised on the mutant
41
+
42
+
43
+ def _preview(s: object, n: int = 100) -> str:
44
+ # Show newlines as a visible ⏎ rather than collapsing them: a mutation's newline can be the
45
+ # load-bearing difference (e.g. a same-line vs new-paragraph disclaimer), and silently flattening
46
+ # it misrepresents WHY a grader rejected the mutant (pass-4 aggravator).
47
+ t = " ".join(str(s).replace("\n", " ⏎ ").split())
48
+ return t if len(t) <= n else t[: n - 1] + "…"
49
+
50
+
51
+ def _mutated_field_preview(op: MutationOperator, mutant: GradeInput) -> str:
52
+ val = getattr(mutant, op.field, None)
53
+ if isinstance(val, (list, tuple)):
54
+ val = " | ".join(map(str, val))
55
+ return _preview(val if val is not None else mutant.text)
56
+
57
+
58
+ def run_case(case: EvalCase, operators: Sequence[MutationOperator]) -> list[MutationResult]:
59
+ """Apply every operator to one case. Raises BaselineError if the case's baseline
60
+ is not green — a caller that wants to tolerate that should use `run_suite`, which
61
+ collects baseline failures instead of raising."""
62
+ try:
63
+ baseline = case.baseline()
64
+ except Exception as exc:
65
+ # A grader that raises on its own clean reference is mis-specified in the worst
66
+ # way — it cannot render a verdict at all. Report it by name; do not let it abort
67
+ # the whole run (run_suite collects this, same as a red baseline).
68
+ raise BaselineError(
69
+ f"case {case.name!r}: grader raised on its own reference output "
70
+ f"({type(exc).__name__}: {exc}). Fix the grader before mutating."
71
+ )
72
+ if not baseline.passed:
73
+ raise BaselineError(
74
+ f"case {case.name!r}: grader {baseline.grader_id!r} fails its own reference "
75
+ f"output ({baseline.detail}). Fix the reference or the grader before mutating."
76
+ )
77
+ grader_id = baseline.grader_id
78
+ # Seed the per-case grader-id memo so the family-gating operators reuse the baseline's
79
+ # verdict instead of re-invoking the grader on case.good once per operator (wasteful for a
80
+ # slow grader; incorrect for a stateful/side-effecting one). Cleared in finally so id(case)
81
+ # is never left mapped past this case's operator loop.
82
+ prev_grader_id = _prime_grader_id(case, grader_id)
83
+
84
+ results: list[MutationResult] = []
85
+ try:
86
+ for op in operators:
87
+ # An operator that mutates a field the grader does not judge is irrelevant to this
88
+ # case, not a finding about it — skip it silently rather than record a false NA that
89
+ # would suggest it had something to say. (Text operators on a tool-only grader, etc.)
90
+ if op.field not in case.judges:
91
+ continue
92
+ try:
93
+ mutant = op.apply(case)
94
+ except Exception as exc:
95
+ # A user operator that crashes while BUILDING the mutant must not abort the whole
96
+ # run and discard every already-collected result. Record it as ERROR naming the
97
+ # OPERATOR (a distinct detail from the grader-crash branch below), surface it,
98
+ # and move on to the next operator.
99
+ results.append(_result(case, grader_id, op, Outcome.ERROR,
100
+ f"operator raised: {type(exc).__name__}: {exc}",
101
+ mutant_preview=""))
102
+ continue
103
+ if mutant is None:
104
+ results.append(_result(case, grader_id, op, Outcome.NA,
105
+ "n/a: operator not applicable here", mutant_preview=""))
106
+ continue
107
+
108
+ grader_error: Optional[str] = None
109
+ try:
110
+ v: Verdict = case.grader(mutant)
111
+ outcome = outcome_for(op.polarity, bool(v.passed))
112
+ detail = v.detail
113
+ except Exception as exc:
114
+ # A grader that crashes on a well-formed mutant did not "catch" anything — it
115
+ # failed to produce a verdict. Scoring a crash as a catch would hide a fragile
116
+ # grader (e.g. a rubber-stamp that indexes text[0] and dies on the blank-output
117
+ # probe, then reads as CAUGHT and vanishes from the vacuous report). ERROR is
118
+ # its own outcome, surfaced, excluded from the score.
119
+ outcome = Outcome.ERROR
120
+ detail = f"grader raised: {type(exc).__name__}: {exc}"
121
+ grader_error = f"{type(exc).__name__}: {exc}"
122
+
123
+ results.append(_result(case, grader_id, op, outcome, detail,
124
+ mutant_preview=_mutated_field_preview(op, mutant),
125
+ grader_error=grader_error))
126
+ finally:
127
+ _clear_grader_id(case, prev_grader_id)
128
+ return results
129
+
130
+
131
+ def run_suite(suite: Sequence[EvalCase], operators: Sequence[MutationOperator]
132
+ ) -> tuple[list[MutationResult], list[BaselineError]]:
133
+ """Run every case. Returns (results, baseline_failures). Baseline failures are
134
+ collected rather than raised so one mis-specified case doesn't abort the run — but
135
+ they are returned, not swallowed, so the caller reports them."""
136
+ results: list[MutationResult] = []
137
+ baseline_failures: list[BaselineError] = []
138
+ for case in suite:
139
+ try:
140
+ results.extend(run_case(case, operators))
141
+ except BaselineError as be:
142
+ baseline_failures.append(be)
143
+ return results, baseline_failures
144
+
145
+
146
+ def _result(case: EvalCase, grader_id: str, op: MutationOperator, outcome: Outcome,
147
+ detail: str, *, mutant_preview: str,
148
+ grader_error: Optional[str] = None) -> MutationResult:
149
+ return MutationResult(
150
+ case_name=case.name,
151
+ grader_id=grader_id,
152
+ operator_id=op.id,
153
+ family=op.family,
154
+ polarity=op.polarity,
155
+ op_type=op.op_type,
156
+ outcome=outcome,
157
+ real_origin=op.real_origin,
158
+ defect_shape=op.defect_shape,
159
+ detail=detail,
160
+ mutant_preview=mutant_preview,
161
+ grader_error=grader_error,
162
+ )
evalmut/score.py ADDED
@@ -0,0 +1,167 @@
1
+ """Turn a list of mutation results into a score and a list of holes.
2
+
3
+ The headline number is the eval mutation score: of the mutations that applied, what
4
+ fraction did the eval handle correctly (caught a defect, or held firm on an
5
+ equivalent). NA is excluded from the denominator — an operator that had nothing to
6
+ say about a case is not evidence either way, and folding it in would let a suite
7
+ inflate its score by being mostly inapplicable.
8
+
9
+ NA and ERROR are both out of the denominator, but for different reasons and with a
10
+ catch: NA is genuinely inapplicable, while ERROR is an *undetermined* verdict (the
11
+ grader crashed). Excluding ERROR is right — a crash is not a catch — but it means a
12
+ grader that crashes on the very defects it can't handle would read a clean 100% with an
13
+ empty blind-spots list. So `crashing_defects` re-surfaces exactly those (a DEFECT the
14
+ grader raised on), and the report prints them beside the blind spots; a defect-crash can
15
+ inflate the number but can never hide.
16
+
17
+ But the number is the least important output. The holes are the product: each MISSED
18
+ is a defect class the eval is blind to, each FLAGGED is a correct-output class it
19
+ breaks on, and every one names the real documented failure it is the shape of. That
20
+ provenance is the difference between "your score is 0.82" (unactionable) and "your
21
+ `contains` check passed a reply truncated before the answer — the exact 429/MNAR
22
+ shape from model-drift" (a specific thing to fix).
23
+ """
24
+ from __future__ import annotations
25
+
26
+ from collections import defaultdict
27
+ from dataclasses import dataclass, field
28
+ from typing import Sequence
29
+
30
+ from .outcome import OperatorType, Outcome, Polarity
31
+ from .runner import MutationResult
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Tally:
36
+ caught: int = 0
37
+ missed: int = 0
38
+ flagged: int = 0
39
+ error: int = 0
40
+ na: int = 0
41
+
42
+ @property
43
+ def applied(self) -> int:
44
+ # Excludes NA (inapplicable) and ERROR (undetermined — the grader crashed).
45
+ return self.caught + self.missed + self.flagged
46
+
47
+ @property
48
+ def holes(self) -> int:
49
+ return self.missed + self.flagged + self.error
50
+
51
+ @property
52
+ def score(self) -> float:
53
+ """Caught / applied. 1.0 when there is nothing to catch (vacuously robust);
54
+ callers that care distinguish that with `applied == 0`."""
55
+ return 1.0 if self.applied == 0 else self.caught / self.applied
56
+
57
+ def with_outcome(self, outcome: Outcome) -> "Tally":
58
+ return Tally(
59
+ caught=self.caught + (outcome is Outcome.CAUGHT),
60
+ missed=self.missed + (outcome is Outcome.MISSED),
61
+ flagged=self.flagged + (outcome is Outcome.FLAGGED),
62
+ error=self.error + (outcome is Outcome.ERROR),
63
+ na=self.na + (outcome is Outcome.NA),
64
+ )
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class Report:
69
+ total: Tally
70
+ by_grader: dict[str, Tally]
71
+ by_operator: dict[str, Tally]
72
+ by_family: dict[str, Tally]
73
+ holes: list[MutationResult] # every MISSED and FLAGGED, most-severe framing first
74
+ results: list[MutationResult] = field(default_factory=list)
75
+ baseline_failures: tuple = () # cases whose grader failed its own reference (mis-specified)
76
+
77
+ @property
78
+ def score(self) -> float:
79
+ return self.total.score
80
+
81
+ @property
82
+ def blind_spots(self) -> list[MutationResult]:
83
+ """A KILL mutation that shipped green: the check is present and BROKEN. The
84
+ most serious finding — a real regression of this shape would pass the suite."""
85
+ return [h for h in self.holes
86
+ if h.outcome is Outcome.MISSED and h.op_type is OperatorType.KILL]
87
+
88
+ @property
89
+ def coverage_gaps(self) -> list[MutationResult]:
90
+ """A DIAGNOSTIC mutation that survived: no check in the suite guards this shape.
91
+ Not a broken grader — a missing one. Worth knowing; often expected."""
92
+ return [h for h in self.holes
93
+ if h.outcome is Outcome.MISSED and h.op_type is OperatorType.DIAGNOSTIC]
94
+
95
+ @property
96
+ def vacuous(self) -> list[MutationResult]:
97
+ """A SANITY mutation (blank/garbage) that survived: the grader asserts nothing
98
+ about the answer and cannot fail. The floor is broken."""
99
+ return [h for h in self.holes
100
+ if h.outcome is Outcome.MISSED and h.op_type is OperatorType.SANITY]
101
+
102
+ @property
103
+ def brittle_spots(self) -> list[MutationResult]:
104
+ """An EQUIVALENT mutation that got flagged: the check fails a still-correct output
105
+ (a false-positive generator)."""
106
+ return [h for h in self.holes if h.outcome is Outcome.FLAGGED]
107
+
108
+ @property
109
+ def errors(self) -> list[MutationResult]:
110
+ """The grader raised on a well-formed mutant — it cannot render a verdict at all."""
111
+ return [h for h in self.holes if h.outcome is Outcome.ERROR]
112
+
113
+ @property
114
+ def crashing_defects(self) -> list[MutationResult]:
115
+ """DEFECT mutants the grader CRASHED on rather than rejecting. These are excluded from
116
+ the score as undetermined — but a grader that crashes on a defect did not catch it, so
117
+ they must be surfaced beside the blind spots, never allowed to silently empty that list
118
+ (a grader made to raise on the defects it can't handle would otherwise read as clean —
119
+ cold-critic pass-2 G)."""
120
+ return [h for h in self.errors if h.polarity is Polarity.DEFECT]
121
+
122
+ @property
123
+ def clean(self) -> bool:
124
+ return not self.holes
125
+
126
+
127
+ def score(results: Sequence[MutationResult]) -> Report:
128
+ total = Tally()
129
+ by_grader: dict[str, Tally] = defaultdict(Tally)
130
+ by_operator: dict[str, Tally] = defaultdict(Tally)
131
+ by_family: dict[str, Tally] = defaultdict(Tally)
132
+
133
+ for r in results:
134
+ total = total.with_outcome(r.outcome)
135
+ by_grader[r.grader_id] = by_grader[r.grader_id].with_outcome(r.outcome)
136
+ by_operator[r.operator_id] = by_operator[r.operator_id].with_outcome(r.outcome)
137
+ by_family[r.family] = by_family[r.family].with_outcome(r.outcome)
138
+
139
+ # Order by how alarming the hole is (must match the rank() body below):
140
+ # 0 vacuous — a SANITY probe survived; the grader asserts nothing, cannot fail
141
+ # 1 blind spot — a KILL defect shipped green; a present check is broken
142
+ # 2 error — the grader crashed on a well-formed mutant; no verdict at all
143
+ # 3 brittle — an EQUIVALENT was flagged; the check false-positives on correct output
144
+ # 4 coverage gap— a DIAGNOSTIC survived; no check guards this shape (often expected)
145
+ def rank(r: MutationResult) -> int:
146
+ if r.outcome is Outcome.MISSED and r.op_type is OperatorType.SANITY:
147
+ return 0
148
+ if r.outcome is Outcome.MISSED and r.op_type is OperatorType.KILL:
149
+ return 1
150
+ if r.outcome is Outcome.ERROR:
151
+ return 2
152
+ if r.outcome is Outcome.FLAGGED:
153
+ return 3
154
+ return 4 # MISSED + DIAGNOSTIC
155
+ holes = sorted(
156
+ (r for r in results if r.outcome.is_hole),
157
+ key=lambda r: (rank(r), r.grader_id, r.operator_id),
158
+ )
159
+
160
+ return Report(
161
+ total=total,
162
+ by_grader=dict(by_grader),
163
+ by_operator=dict(by_operator),
164
+ by_family=dict(by_family),
165
+ holes=holes,
166
+ results=list(results),
167
+ )