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/__init__.py ADDED
@@ -0,0 +1,56 @@
1
+ """evalmut — mutation testing for evals.
2
+
3
+ Your eval suite passes. Does it actually check anything? evalmut injects known
4
+ defects into the system-under-test's output — mutations mined from real, documented
5
+ eval failures — and reruns the graders that were supposed to be watching. A mutation
6
+ the grader catches is a check doing its job. A mutation that survives is a hole: a
7
+ class of defect that would ship green (a blind spot) or a class of correct output the
8
+ check breaks on (a brittle spot). Every operator names the real failure it reproduces.
9
+
10
+ from evalmut import EvalCase, run, catalog
11
+ from gradecore import GradeInput, contains
12
+
13
+ suite = [EvalCase("adds", contains("42"), GradeInput(text="the answer is 42"),
14
+ intent="reply must contain the sum")]
15
+ report = run(suite)
16
+ print(report.score, "-", len(report.holes), "holes")
17
+ for h in report.blind_spots:
18
+ print(h.grader_id, "is blind to", h.real_origin)
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from typing import Optional, Sequence
23
+
24
+ from .case import EvalCase, case
25
+ from .operator import MutationOperator, applies_to_tag, operator, with_text
26
+ from .operators import CORE_OPERATORS, catalog
27
+ from .outcome import OperatorType, Outcome, Polarity, outcome_for
28
+ from .report import render, render_short
29
+ from .runner import BaselineError, MutationResult, run_case, run_suite
30
+ from .score import Report, Tally, score
31
+
32
+ __version__ = "0.1.0"
33
+
34
+
35
+ def run(suite: Sequence[EvalCase],
36
+ operators: Optional[Sequence[MutationOperator]] = None) -> Report:
37
+ """The one-call entry point: run the (default or given) operators over the suite
38
+ and return a scored report. Baseline failures are attached to the report so a
39
+ mis-specified case is loud, not silent."""
40
+ import dataclasses
41
+ ops = tuple(operators) if operators is not None else catalog()
42
+ results, baseline_failures = run_suite(suite, ops)
43
+ report = score(results)
44
+ if baseline_failures:
45
+ report = dataclasses.replace(report, baseline_failures=tuple(baseline_failures))
46
+ return report
47
+
48
+
49
+ __all__ = [
50
+ "EvalCase", "case", "run", "run_case", "run_suite",
51
+ "MutationOperator", "operator", "applies_to_tag", "with_text",
52
+ "CORE_OPERATORS", "catalog",
53
+ "Outcome", "Polarity", "OperatorType", "outcome_for",
54
+ "Report", "Tally", "score", "MutationResult", "BaselineError",
55
+ "render", "render_short",
56
+ ]
evalmut/case.py ADDED
@@ -0,0 +1,105 @@
1
+ """An eval case: a grader and a reference-correct output it passes.
2
+
3
+ This is the unit a mutation is applied to. The crucial field is `good`: a
4
+ GradeInput the grader is known to PASS. Mutation testing needs a green baseline
5
+ for the same reason code mutation testing does — you cannot ask "would this check
6
+ catch a defect I introduce?" if the check is already failing on the clean input.
7
+ The runner refuses to score a case whose baseline is red and tells you which, so a
8
+ mis-specified reference is a loud error rather than a silently skipped one.
9
+
10
+ `good` is also the ground truth every operator reasons against. Because the grader
11
+ passes it, `good` is by definition a correct output for this task; an operator that
12
+ transforms `good` into something wrong has, relative to this reference, injected a
13
+ real defect — no separate oracle required.
14
+
15
+ Some operators need to know a bar that lives inside the grader's closure and is
16
+ invisible from the outside — a numeric tolerance, a grounding threshold, which
17
+ cosmetic changes this task's contract treats as still-correct, the expected tool
18
+ plan. The honest answer is never to guess it (guessing a module default, or trusting
19
+ a grader-emitted id label, is exactly what manufactured evalmut's own false findings
20
+ in cold-critic pass 2). Instead the suite author DECLARES it here, and the operator
21
+ either uses the declared bar or declines. Every such field defaults to the value that
22
+ makes the dependent operator DECLINE, so an undecorated case can only ever be
23
+ under-tested, never falsely accused.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ from dataclasses import dataclass, field
28
+
29
+ from gradecore import GradeInput, Grader
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class EvalCase:
34
+ name: str
35
+ grader: Grader
36
+ good: GradeInput
37
+ # Which GradeInput fields the grader actually judges. A mutation is only a defect
38
+ # relative to what the task grades: blanking `text` is a real defect for "answer the
39
+ # question" but not for "did the agent avoid a denylisted tool", where the text is
40
+ # incidental and the grader rightly ignores it. Defaulting to ("text",) covers the
41
+ # overwhelming majority (scalar/text/safety graders); a tool or retrieval case names
42
+ # its own fields so text operators don't fire on it and manufacture false findings.
43
+ judges: tuple[str, ...] = ("text",)
44
+
45
+ # ── declared contract bars (each defaults to "operator declines") ────────────
46
+ # The numeric acceptance band the grader uses, if this is a numeric-answer task. A
47
+ # near-miss is a defect only if it falls OUTSIDE the tolerance — and that band lives in
48
+ # the grader's closure, invisible to an operator. Declaring it lets the numeric operator
49
+ # perturb to just past the band; it also cross-checks the declaration against the grader
50
+ # before trusting it. Left None, the numeric operator declines.
51
+ num_tol: float | None = None
52
+ # This task's grader is supposed to require CONTENT in the answer (an exact/contains/
53
+ # number/JSON-style check), so a blank or unrelated output is a provable defect and the
54
+ # SANITY probes may fire. For gradecore's content graders this is inferred from grader_id;
55
+ # a custom grader must opt in, because a blank output is legitimately fine for an ABSENCE
56
+ # grader (injection_resistance, tool_misuse) and calling that vacuous is false (pass-2 C).
57
+ content_required: bool = False
58
+ # The cosmetic changes THIS task's contract treats as still-correct — any of
59
+ # "whitespace", "fence", "disclaimer". An EQUIVALENT operator claims "still correct" only
60
+ # when the change is declared here, because equivalence is a property of the task's
61
+ # contract, not something readable from a grader-emitted id: a composite grader can
62
+ # honestly carry a primitive's id yet also enforce length or format, so a fence or added
63
+ # whitespace legitimately fails it (cold-critic pass-2 B). Declared here, the equivalence
64
+ # claim rests on the author, not on a label the grader controls. Undeclared -> decline.
65
+ tolerates: tuple[str, ...] = ()
66
+ # The expected ordered tool plan, for a trajectory case. trajectory_drop_step proves a
67
+ # defect only by dropping a step whose removal pushes LCS coverage below the threshold —
68
+ # which requires knowing the plan (it lives in the grader closure). Left empty, the
69
+ # operator declines rather than blindly dropping the last call (cold-critic pass-2 E).
70
+ expected_trajectory: tuple[str, ...] = ()
71
+ # The trajectory coverage threshold the grader enforces (gradecore's default is 1.0, but a
72
+ # lenient grader may accept partial coverage). Defaults to None = DECLINE: 1.0 is the STRICTEST
73
+ # bar, not a safe default — trusting it flags a lenient grader that correctly accepts a partial
74
+ # trajectory as a blind spot (cold-critic pass-3 F3). Declare it (with expected_trajectory) to
75
+ # let trajectory_drop_step fire.
76
+ trajectory_threshold: float | None = None
77
+
78
+ # The gradecore CONTRACT FAMILY this grader behaves like, when the grader is external and does
79
+ # not carry a gradecore grader_id (e.g. a promptfoo `is-json` port). Operators gate some
80
+ # behavior on the grader's contract family; for an in-house gradecore grader that family is read
81
+ # from its own grader_id, but an external grader must DECLARE it here (e.g. "valid_json",
82
+ # "number", "grounding", "contains", "injection_resistance"). Declared, it lets evalmut run
83
+ # against a framework's graders unmodified while the grader keeps reporting its own honest id.
84
+ grader_family: str | None = None
85
+ # Optional human-readable notes surfaced in reports; never load-bearing.
86
+ intent: str = ""
87
+ tags: tuple[str, ...] = field(default_factory=tuple)
88
+
89
+ def baseline(self):
90
+ """The grader's verdict on the clean reference. Must pass, or the case is
91
+ mis-specified and the runner will refuse to mutate it."""
92
+ return self.grader(self.good)
93
+
94
+
95
+ def case(name: str, grader: Grader, good: GradeInput, *, judges: tuple[str, ...] = ("text",),
96
+ num_tol: float | None = None, content_required: bool = False,
97
+ tolerates: tuple[str, ...] = (), expected_trajectory: tuple[str, ...] = (),
98
+ trajectory_threshold: float | None = None, grader_family: str | None = None,
99
+ intent: str = "", tags: tuple[str, ...] = ()) -> EvalCase:
100
+ """Terse constructor for suites written as data."""
101
+ return EvalCase(name=name, grader=grader, good=good, judges=judges,
102
+ num_tol=num_tol, content_required=content_required, tolerates=tolerates,
103
+ expected_trajectory=expected_trajectory,
104
+ trajectory_threshold=trajectory_threshold, grader_family=grader_family,
105
+ intent=intent, tags=tags)
evalmut/cli.py ADDED
@@ -0,0 +1,144 @@
1
+ """`evalmut` — point it at an eval suite and see what its checks don't check.
2
+
3
+ evalmut run path/to/suite.py # run mutations, print the report
4
+ evalmut run suite.py --json # machine-readable results
5
+ evalmut run suite.py --short # one line, for CI
6
+ evalmut operators # list the mined catalog, each with its provenance
7
+
8
+ A suite module exposes `suite` (a list of EvalCase) and optionally `operators`
9
+ (a list of MutationOperator; defaults to the full mined catalog).
10
+
11
+ Exit code: 0 if clean or only coverage-gaps; 1 if any vacuous / blind / brittle hole —
12
+ so a suite that stopped checking things fails CI the way a red test would.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import dataclasses
18
+ import importlib.util
19
+ import json
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ from . import catalog, run
24
+ from .report import render, render_short
25
+ from .runner import MutationResult
26
+
27
+
28
+ def _load_suite(path: str):
29
+ p = Path(path).resolve()
30
+ if not p.exists():
31
+ sys.exit(f"evalmut: no such suite file: {path}")
32
+ spec = importlib.util.spec_from_file_location("_evalmut_suite", p)
33
+ if spec is None or spec.loader is None:
34
+ sys.exit(f"evalmut: cannot load suite from {path}")
35
+ mod = importlib.util.module_from_spec(spec)
36
+ # Let a suite import sibling modules (a suite.py next to a my_graders.py) and let it self-import:
37
+ # register the module before exec so dataclasses / pickling resolve to this same object.
38
+ sys.path.insert(0, str(p.parent))
39
+ sys.modules[spec.name] = mod
40
+ try:
41
+ spec.loader.exec_module(mod)
42
+ if not hasattr(mod, "suite"):
43
+ sys.exit(f"evalmut: {path} must define `suite` (a list of EvalCase)")
44
+ return list(mod.suite), (list(mod.operators) if hasattr(mod, "operators") else None)
45
+ except Exception as e: # a raising import or a non-iterable `suite` shouldn't dump a raw traceback
46
+ sys.exit(f"evalmut: error loading {path}: {type(e).__name__}: {e}")
47
+
48
+
49
+ def _result_dict(r: MutationResult) -> dict:
50
+ d = dataclasses.asdict(r)
51
+ d["polarity"] = r.polarity.value
52
+ d["op_type"] = r.op_type.value
53
+ d["outcome"] = r.outcome.value
54
+ return d
55
+
56
+
57
+ def _cmd_run(args) -> int:
58
+ suite, operators = _load_suite(args.suite)
59
+ report = run(suite, operators)
60
+
61
+ if args.json:
62
+ payload = {
63
+ "score": report.score,
64
+ "tally": dataclasses.asdict(report.total),
65
+ "holes": {
66
+ "vacuous": [_result_dict(h) for h in report.vacuous],
67
+ "blind": [_result_dict(h) for h in report.blind_spots],
68
+ "error": [_result_dict(h) for h in report.errors],
69
+ "brittle": [_result_dict(h) for h in report.brittle_spots],
70
+ "coverage_gap": [_result_dict(h) for h in report.coverage_gaps],
71
+ },
72
+ "baseline_failures": [str(b) for b in getattr(report, "baseline_failures", ())],
73
+ "results": [_result_dict(r) for r in report.results] if args.all else None,
74
+ }
75
+ print(json.dumps(payload, indent=2))
76
+ elif args.short:
77
+ print(render_short(report))
78
+ else:
79
+ print(render(report, verbose=args.verbose))
80
+
81
+ # An empty suite (or one where no operator could apply) produced a 100%/no-holes report
82
+ # above — but nothing was actually mutated or checked, which is the exact lie this tool
83
+ # exists to catch. Fail the gate rather than green-light it.
84
+ if report.total.applied == 0:
85
+ if not args.json:
86
+ print("evalmut: no mutations applied — the suite is empty or no case has a "
87
+ "mutable, gradeable field. Nothing was checked; this is not a pass.",
88
+ file=sys.stderr)
89
+ return 1
90
+
91
+ # CI gate: coverage-gaps alone do not fail (they name missing graders, not broken
92
+ # ones); vacuous / blind / error / brittle do.
93
+ serious = (report.vacuous or report.blind_spots or report.errors
94
+ or report.brittle_spots)
95
+ return 1 if (serious or getattr(report, "baseline_failures", ())) else 0
96
+
97
+
98
+ def _cmd_operators(args) -> int:
99
+ ops = catalog()
100
+ if args.json:
101
+ print(json.dumps([
102
+ {"id": o.id, "family": o.family, "polarity": o.polarity.value,
103
+ "op_type": o.op_type.value, "field": o.field,
104
+ "defect_shape": o.defect_shape, "real_origin": o.real_origin}
105
+ for o in ops], indent=2))
106
+ return 0
107
+ print(f"evalmut — {len(ops)} mined operators (every one names the real defect it reproduces)\n")
108
+ for o in sorted(ops, key=lambda x: (x.family, x.id)):
109
+ print(f" {o.id} [{o.family} · {o.polarity.value} · {o.op_type.value} · {o.field}]")
110
+ print(f" shape : {o.defect_shape}")
111
+ print(f" mined : {o.real_origin}\n")
112
+ return 0
113
+
114
+
115
+ def main(argv=None) -> int:
116
+ ap = argparse.ArgumentParser(prog="evalmut", description=__doc__,
117
+ formatter_class=argparse.RawDescriptionHelpFormatter)
118
+ sub = ap.add_subparsers(dest="cmd", required=True)
119
+
120
+ r = sub.add_parser("run", help="run mutations against a suite file")
121
+ r.add_argument("suite", help="path to a Python file defining `suite`")
122
+ r.add_argument("--json", action="store_true", help="machine-readable output")
123
+ r.add_argument("--short", action="store_true", help="one line, for CI")
124
+ r.add_argument("--all", action="store_true", help="(with --json) include every result, not just holes")
125
+ r.add_argument("-v", "--verbose", action="store_true", help="per-grader table + mutant previews")
126
+ r.set_defaults(fn=_cmd_run)
127
+
128
+ o = sub.add_parser("operators", help="list the mined operator catalog")
129
+ o.add_argument("--json", action="store_true")
130
+ o.set_defaults(fn=_cmd_operators)
131
+
132
+ # The report uses box-drawing / warning glyphs; on a non-UTF-8 stdout (Windows cp1252,
133
+ # a redirected CI pipe) printing them would crash with UnicodeEncodeError and lose the
134
+ # whole report. Degrade unrepresentable glyphs to a placeholder instead of dying.
135
+ enc = (getattr(sys.stdout, "encoding", None) or "").lower()
136
+ if enc not in ("utf-8", "utf8") and hasattr(sys.stdout, "reconfigure"):
137
+ sys.stdout.reconfigure(errors="backslashreplace")
138
+
139
+ args = ap.parse_args(argv)
140
+ return args.fn(args)
141
+
142
+
143
+ if __name__ == "__main__":
144
+ sys.exit(main())
evalmut/operator.py ADDED
@@ -0,0 +1,138 @@
1
+ """A mutation operator: a mined defect shape, and the rule for injecting it.
2
+
3
+ Every operator carries the concrete, documented failure it is the shape of
4
+ (`real_origin`). This is not decoration — it is the project's whole claim to
5
+ honesty. An *authored* mutation operator only tests what its author already
6
+ imagined a check might miss, which is exactly the blind spot you are trying to
7
+ find. A *mined* operator reproduces a defect that actually happened and actually
8
+ got past a check. Every operator in this package must name one; an operator that
9
+ cannot is cut.
10
+
11
+ `apply(good) -> GradeInput | None` is the contract. It returns a mutated input, or
12
+ None when the operator cannot establish its polarity for this case. That None is
13
+ the equivalent-mutant defense: rather than mutate blindly and then guess whether a
14
+ survival is a real hole, an operator applies ONLY where it can guarantee the
15
+ mutant's correctness relative to the reference — provably wrong for a DEFECT
16
+ operator, provably still-correct for an EQUIVALENT operator. Everywhere else it
17
+ declines. So a MISSED or FLAGGED outcome downstream is a fact about the grader, not
18
+ an artifact of an ambiguous mutant.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass, replace
23
+ from typing import TYPE_CHECKING, Callable, Optional
24
+
25
+ from gradecore import GradeInput
26
+
27
+ from .outcome import OperatorType, Polarity
28
+
29
+ if TYPE_CHECKING:
30
+ from .case import EvalCase
31
+
32
+ # A pure function from a case to a mutated input, or None (N/A). It receives the whole
33
+ # case, not just the input, so a semantic operator can read the ground truth it needs:
34
+ # `case.good.expected` (the canonical answer, for number/exact/truncation operators) and
35
+ # `case.tags` (the task class, for safety/abstention operators whose correctness depends
36
+ # on what the task is FOR, which the output text alone cannot reveal).
37
+ ApplyFn = Callable[["EvalCase"], Optional[GradeInput]]
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class MutationOperator:
42
+ id: str
43
+ family: str
44
+ polarity: Polarity
45
+ defect_shape: str # one line: the class of real defect this injects
46
+ real_origin: str # the concrete documented failure it is mined from
47
+ field: str # which GradeInput field it perturbs (for reports/filtering)
48
+ _apply: ApplyFn
49
+ op_type: OperatorType = OperatorType.KILL # what a survival means (see OperatorType)
50
+
51
+ def apply(self, case: "EvalCase") -> Optional[GradeInput]:
52
+ """Mutate the case's reference input, or return None if not applicable here.
53
+
54
+ Invariant every operator must uphold: a non-None result is, relative to
55
+ `case.good`, a genuinely wrong output when polarity is DEFECT, and a
56
+ genuinely still-correct output when polarity is EQUIVALENT. Operators
57
+ enforce this by declining (returning None) wherever they cannot guarantee
58
+ it — e.g. a number-corrupting operator returns None on an input with no
59
+ number to corrupt; a truncation operator returns None when it cannot locate
60
+ the answer span it would need to cut away.
61
+ """
62
+ mutant = self._apply(case)
63
+ if mutant is None:
64
+ return None
65
+ # A structural no-op is not a mutation. Guard it here so no operator can
66
+ # accidentally report a verdict about an unchanged input.
67
+ if _same_input(mutant, case.good):
68
+ return None
69
+ return mutant
70
+
71
+
72
+ def operator(id: str, *, family: str, polarity: Polarity, defect_shape: str,
73
+ real_origin: str, field: str,
74
+ op_type: OperatorType = OperatorType.KILL
75
+ ) -> Callable[[ApplyFn], MutationOperator]:
76
+ """Decorator form, so an operator reads as its apply-rule with provenance attached.
77
+
78
+ @operator("truncate_before_answer", family="truncation",
79
+ polarity=Polarity.DEFECT, field="text",
80
+ defect_shape="reply cut off before it reaches the answer",
81
+ real_origin="model-drift 429/MNAR: a cut-off reply and a wrong "
82
+ "reply fail differently and must not share a metric")
83
+ def _(good): ...
84
+ """
85
+ def wrap(fn: ApplyFn) -> MutationOperator:
86
+ return MutationOperator(
87
+ id=id, family=family, polarity=polarity, defect_shape=defect_shape,
88
+ real_origin=real_origin, field=field, _apply=fn, op_type=op_type,
89
+ )
90
+ return wrap
91
+
92
+
93
+ def applies_to_tag(*tags: str):
94
+ """Guard helper: a semantic operator that is only meaningful for a task class.
95
+ Wrap an apply-fn so it returns None unless the case carries one of `tags`. Keeps
96
+ the correctness contract honest — a refusal-swap is only a defect on a task that
97
+ was supposed to refuse, and we know that from the case tag, not the output text."""
98
+ wanted = set(tags)
99
+
100
+ def deco(fn: ApplyFn) -> ApplyFn:
101
+ def guarded(case: "EvalCase") -> Optional[GradeInput]:
102
+ if wanted.isdisjoint(case.tags):
103
+ return None
104
+ return fn(case)
105
+ return guarded
106
+ return deco
107
+
108
+
109
+ def with_text(good: GradeInput, text: str) -> GradeInput:
110
+ """Return a copy of `good` with its `text` replaced — the common mutation move."""
111
+ return replace(good, text=text)
112
+
113
+
114
+ def _same_input(a: GradeInput, b: GradeInput) -> bool:
115
+ """Structural equality across every field a grader might read. Frozen dataclass
116
+ equality would work too, but sequences may arrive as list vs tuple from different
117
+ call sites, so compare field-wise and normalize sequences to tuples."""
118
+ def seq(x):
119
+ return tuple(x) if x is not None else ()
120
+ return (
121
+ a.text == b.text
122
+ and a.prompt == b.prompt
123
+ and seq(a.retrieved) == seq(b.retrieved)
124
+ and seq(a.contexts) == seq(b.contexts)
125
+ and seq(a.citations) == seq(b.citations)
126
+ and tuple(map(_freeze, a.tool_calls)) == tuple(map(_freeze, b.tool_calls))
127
+ and seq(a.gold_ids) == seq(b.gold_ids)
128
+ and a.expected == b.expected
129
+ )
130
+
131
+
132
+ def _freeze(d):
133
+ """A hashable, comparable view of a tool-call dict for equality checks."""
134
+ if isinstance(d, dict):
135
+ return tuple(sorted((k, _freeze(v)) for k, v in d.items()))
136
+ if isinstance(d, (list, tuple)):
137
+ return tuple(_freeze(x) for x in d)
138
+ return d