← Back to Home | Back to Testing

Mutation Testing

Orchard ML uses mutmut v3 for mutation testing. Mutmut injects small code changes (mutants) and verifies that the test suite catches each one. Survived mutants indicate gaps in test assertions.


Installing mutmut

[!IMPORTANT] mutmut is pinned to an exact commit of git main, not to a PyPI release.

"mutmut @ git+https://github.com/boxed/mutmut.git@cd2f73da310c3fc90cffcb3e6c768cdeac14e18c"

No published release works. What the pinned commit carries:

Change Available in
mutmut.mutation.* layout, imported by scripts/mutmut_entry.py 3.6.0 onwards
set_start_method guard (GH-466) after 3.5.0
env scrubbing, MUTANT_UNDER_TEST (#511) after 3.7.0, main only
fix: mutate methods of decorated classes (#539) after 3.7.0, main only

So 3.5.0 is unusable (wrong layout) and 3.7.0 is the newest release yet still ships the #511 bug: its trampoline does os.environ.get("MUTANT_UNDER_TEST", "") on every call, verified directly on the wheel.

The pin is an exact SHA, not @main, and that is not pedantry: mutant generation changes between commits, so the registry ratchet only compares like with like while the revision is frozen. Moving 3.5.0 → cd2f73d took search_spaces.py from 327 mutants to 358. Treat a mutmut bump like a mypy bump: deliberate, and followed by a re-baseline of the affected modules.

After rebuilding the venv, uv sync restores the pinned commit. To install it by hand:

uv pip install --no-deps \
  "mutmut @ git+https://github.com/boxed/mutmut.git@cd2f73da310c3fc90cffcb3e6c768cdeac14e18c"

--no-deps is deliberate: full resolution hits PyPI and has timed out on setproctitle. Every mutmut dependency is already in the venv.


Configuration

Mutation testing is configured in pyproject.toml:

[tool.mutmut]
paths_to_mutate = ["orchard/"]
tests_dir = ["tests/"]

Log and cosmetic mutations are suppressed automatically by the patched entry point scripts/mutmut_entry.py — no per-line # pragma: no mutate annotations are needed for logging calls. See Patched Entry Point below for details.


Running Mutation Tests

[!WARNING] Prerequisites

  1. Always use .venv/bin/python — never system python.
  2. All tests must pass before running mutmut. A single test failure causes ALL mutants to be marked not_checked, and batch mode sees "incomplete results" and skips/restores backup.
.venv/bin/python -m pytest tests/ -x -q

Full repository (slow — hours on first run):

# Generate mutants and run tests against each one
.venv/bin/python scripts/mutmut_entry.py run

# View results summary
.venv/bin/python scripts/mutmut_entry.py results

# Inspect a specific survived mutant
.venv/bin/python scripts/mutmut_entry.py show <mutant_name>

Single module (recommended for iterative work):

mutmut v3 uses dotted-module glob patterns as positional arguments:

# Mutate only the search_spaces module
.venv/bin/python scripts/mutmut_entry.py run "orchard.optimization.search_spaces*"

# Mutate only the loader module
.venv/bin/python scripts/mutmut_entry.py run "orchard.data_handler.loader*"

# Mutate only the evaluation pipeline
.venv/bin/python scripts/mutmut_entry.py run "orchard.evaluation.evaluation_pipeline*"

Multiple modules in one run:

.venv/bin/python scripts/mutmut_entry.py run "orchard.optimization*" "orchard.trainer*"

Single class or function:

.venv/bin/python scripts/mutmut_entry.py run "orchard.optimization.search_spaces.*SearchSpaceRegistry*"
.venv/bin/python scripts/mutmut_entry.py run "*get_optimization_space*"

[!NOTE] Always use scripts/mutmut_entry.py instead of bare mutmut — the patched entry point suppresses cosmetic mutations on logging calls automatically. scripts/mutmut_run.py invokes it internally.


Mutation Registry

The mutation registry (mutmut-registry.yaml) tracks per-file mutation scores and auto-updates when you test a module. Use scripts/mutmut_run.py:

# Run mutmut on a single file and update the registry
.venv/bin/python scripts/mutmut_run.py orchard/cli_app.py

# Run mutmut on an entire sub-package
.venv/bin/python scripts/mutmut_run.py orchard/core/config/

# Multiple targets at once
.venv/bin/python scripts/mutmut_run.py orchard/cli_app.py orchard/exceptions.py

# Show the registry report (no mutmut run, just read existing results)
.venv/bin/python scripts/mutmut_run.py --report

# Show report for specific modules
.venv/bin/python scripts/mutmut_run.py --report orchard/core/config/

# Batch: run each .py file one by one (cleans cache, updates registry after each)
.venv/bin/python scripts/mutmut_run.py --batch orchard/trainer/

# Batch the whole project (directory expansion skips __init__.py, see Gotchas)
.venv/bin/python scripts/mutmut_run.py --batch orchard/

Output example:

Module                                              Total  Kill  Surv   T/O   N/T   N/C   Score
-----------------------------------------------------------------------------------------------
orchard/architectures/factory.py                       78    60    18     0     0     0   76.9%
orchard/cli_app.py                                    523   493    30     0     0     0   94.3%
orchard/tracking/tracker.py                            78    30     0     0    48     0   38.5%
-----------------------------------------------------------------------------------------------
TOTAL                                                 679   583    48     0    48     0   85.9%

Outcome categories

Exit codes are classified per mutmut's own status_by_exit_code table. The distinction matters because each category needs a different fix:

Column Exit code Meaning Fix
Kill 1, 3 A test failed — the mutant was caught none
Surv 0 Tests ran and passed — nothing asserts the mutated behaviour add assertions
T/O -24, 24, 36, 152, 255 The mutant exceeded its wall-clock budget see the OpenMP note below
N/T 5, 33 No test covers this code at all — nothing ran write a test
N/C None Never checked — an incomplete run re-run the module

Only Kill counts toward the score. Folding timeouts into Kill (as any exit != 0 rule does) inflates it: a mutant that merely hung was never caught by an assertion.

The registry YAML is tracked in git so you can see score evolution across commits.

Registry guards (scripts/check_mutmut_registry.py):

# Fail if any module score dropped vs HEAD (pre-commit gate)
.venv/bin/python scripts/check_mutmut_registry.py --ratchet

# Fail if any modified module has a stale registry entry (release gate)
.venv/bin/python scripts/check_mutmut_registry.py --freshness

# Both
.venv/bin/python scripts/check_mutmut_registry.py --ratchet --freshness

The ratchet fires when a module's score drops and its undetected count grows, where undetected is survived + no_tests. Counting both matters: a module whose kills slide into no_tests has regressed just as surely as one that grew survivors, and comparing survived alone would wave it through.


Cleaning Cache

mutmut v3 caches trampoline files and metadata in the mutants/ directory. Always clean the entire mutants/ directory before reruns — deleting individual files is error-prone and can leave stale state:

# Clean all cached results (recommended)
rm -rf mutants/

[!WARNING] Uncommitted files and the registry

--batch mode uses _is_fresh which compares the registry last_run timestamp against git log -1 --format=%aI. Uncommitted changes don't update git log, so old registry entries look "newer" and the file gets skipped silently.

Before running mutmut on uncommitted files, remove their registry entries and the cache:

rm -rf mutants/
.venv/bin/python -c "
import yaml; from pathlib import Path
reg_path = Path('mutmut-registry.yaml')
reg = yaml.safe_load(reg_path.read_text()) or {}
for k in ['orchard/path/to/changed_file.py']:
    reg.pop(k, None)
reg = dict(sorted(reg.items()))
reg_path.write_text(yaml.dump(reg, default_flow_style=False, sort_keys=False))
"

Gotchas

[!CAUTION] Never name an __init__.py explicitly in --batch

_to_mutmut_glob strips .__init__ and appends *, so orchard/__init__.py becomes glob orchard* — which matches the entire codebase, in a single batch step with a 2400 s timeout.

Directory targets are safe: _source_files skips __init__.py when expanding a directory, so --batch orchard/ cannot trip this. The hazard is only in passing one by name. Use --report for __init__.py and other pure-declaration files (constants, re-exports) with no mutable logic:

.venv/bin/python scripts/mutmut_run.py --report orchard/__init__.py orchard/tasks/__init__.py

[!NOTE] Batch timeout

Batch mode has a 2400-second (40 min) timeout per file. If exceeded, previous results are restored from the .meta.bak backup.

The per-file cap and mutmut's own per-mutant cap are different things: this one bounds the whole module, timeout_constant in pyproject.toml bounds a single mutant.

[!CAUTION] Forking a live OpenMP pool fakes mass timeouts

mutmut runs each mutant in a child made by bare fork(), from a parent that has already imported the test suite. If torch's OpenMP pool is live at fork time, the child inherits a pool whose worker threads were never cloned, and the first parallel region blocks forever. The parent reaps it at the wall-clock limit and records a timeout.

scripts/mutmut_entry.py pins OMP_NUM_THREADS and MKL_NUM_THREADS to 1 before anything imports torch, which removes the pool and the deadlock with it.

The symptom is distinctive, and worth recognising if it ever comes back: timeouts land only on the torch-heavy modules, and every mutant's duration sits exactly on the limit. Raising the limit then moves the durations without reducing the count — proof the mutants are blocked, not slow.

Measured impact when this was found: 635 timeouts across the project, down to 31. orchard/evaluation/tta.py reported a fake 100.0 % (its 64 timeouts had been counted as kills); once measured it scored 71.7 %, exposing 41 genuine survivors. The full re-baseline also dropped from 1 h 20 m to 25 min.

[!CAUTION] Decorated functions produce zero mutants

mutmut does not wrap a decorated function or method in a trampoline, so its body is never mutated. Verified on the pinned commit:

training_config.py   1 trampoline  (the free function is_amp_safe_batch_size)
                     0             (both @model_validator methods)
cli_app.py           0             (run / init / validate / main, @app.command)

The consequence is that Pydantic validators and Typer commands are not mutation tested at all. Ten non-trivial files sit at total: 0, essentially the whole config layer. Read a 100 % score on a config module as "nothing was measured", not as "fully covered".

This is distinct from #539 and #558, which cover decorated classes. Not yet reported upstream.

[!NOTE] CI does not run mutmut

Mutation testing is a local quality gate only. CI runs linting, type checking, and pytest — but not mutmut.


Writing Mutation-Resilient Tests

Tests that only check key presence (assert "key" in space) will let many mutants survive. To kill mutants effectively:

  • Assert exact values passed to functions (bounds, lists, constants)
  • Assert exact return values, not just types
  • Test boundary conditions (e.g., resolution 223 vs 224)
  • Test both branches of conditionals (enabled/disabled, present/absent)
  • Verify side effects (function called vs not called)

Patched Entry Point

scripts/mutmut_entry.py monkey-patches mutmut's MutationVisitor to suppress cosmetic mutations without per-line annotations. It is invoked automatically by scripts/mutmut_run.py.

Two suppression levels:

Level Methods Effect
Full skip debug, info, add_format Entire Call node excluded — call, arguments, and strings
String-only skip warning, error, warn, getLogger Only string literals inside the call are excluded; the call itself and non-string args remain mutable

This eliminates the need for # pragma: no mutate on logging lines.


Pragma Conventions

Annotation Scope Usage
# pragma: no mutate Single line Plot formatting constants, cosmetic-only literals
# pragma: no cover Single line Unreachable defensive code

Logging calls (info, debug, warning, error, warn) are handled automatically by the patched entry point — do not annotate them manually.

Never apply # pragma: no mutate to:

  • Conditionals, computed values, or any real logic
  • Entire files (do_not_mutate is forbidden)

Resolved Issue: `set_start_method` Crash

mutmut 3.5.0 calls multiprocessing.set_start_method('fork') at module level in mutmut/__main__.py. When the module is re-executed (e.g. via python -m mutmut run), the call fails with:

RuntimeError: context has already been set

Status: fixed upstream in GH-466 (merged into main) and present in the installed build. See Installing mutmut — the sed patch that used to be documented here is obsolete, and would not have helped anyway: on PyPI 3.5.0 the blocker is the package layout, not that one line.


Resolved Issue: Name Mangling in Trampoline Generation

When a class name starts with an underscore (e.g. _CrossDomainValidator), mutmut generates trampoline function names like __CrossDomainValidator_validate_trampoline. Inside the class body, Python's name mangling rewrites __CrossDomainValidator_validate_trampoline to _CrossDomainValidator__CrossDomainValidator_validate_trampoline, causing a NameError at import time.

Status: fixed upstream in boxed/mutmut#499 (merged 2026-04-16, reported in #498). The pinned commit generates prefixes of the form x{CLASS_NAME_SEPARATOR}{class_name}{CLASS_NAME_SEPARATOR}, which never starts with a double underscore and so is immune to name mangling. No local patch is needed, and the sed recipe once documented here no longer matches anything.


Resolved Issue: env scrubbing wipes `MUTANT_UNDER_TEST`

When tests use patch.dict(os.environ, ..., clear=True), mutmut v3 trampolines break because MUTANT_UNDER_TEST is wiped from the environment. Mutants reachable only through such tests are falsely reported as survived, silently lowering the mutation score (measured impact on orchard/core/environment/hardware.py: 19 false survivors, 85.7 % vs. the true 97.0 %).

Status: fixed upstream. Reported as boxed/mutmut#511, closed as completed on 2026-08-17 via #552. The trampoline now keeps the mutant name in module state (mutation/trampoline.py) and only prefers the environment variable when present, so scrubbing os.environ no longer deactivates the mutant. The fix landed after the 3.7.0 tag, so it exists only on main: verified present in the pinned commit cd2f73d, and verified absent from PyPI 3.7.0.

Workaround removed (2026-09-03). The mutmut_safe_env() helper that re-injected MUTANT_UNDER_TEST into the patched env is gone, along with its 17 call sites in tests/test_environment/test_hardware.py and tests/test_paths/test_constants.py. Verified on the original repro: without the helper, orchard/core/environment/hardware.py scores 97.7 % (133 mutants, 3 survivors) instead of the 85.7 % the bug used to cause.

Scrubbing the environment in a test is safe again:

def test_something():
    with patch.dict(os.environ, {"MY_VAR": "1"}, clear=True):
        ...

Pending Issue: mutants leak into `Protocol` class namespaces

mutmut emits its mutant variants inside the class body. For a runtime_checkable Protocol, those names do not start with an underscore, so typing._get_protocol_attrs counts them as protocol members:

# in the mutated tree
_get_protocol_attrs(TaskEvalPipeline)
['run_evaluation',
 'xǁTaskEvalPipelineǁrun_evaluation__mutmut_1',
 'xǁTaskEvalPipelineǁrun_evaluation__mutmut_2',
 'xǁTaskEvalPipelineǁrun_evaluation__mutmut_orig']

Every isinstance(obj, SomeProtocol) check then fails, which aborts the stats run and marks all mutants not_checked — for every module, not just the one being measured.

Status: not yet reported upstream (observed on the pinned commit cd2f73d).

Workaround: scripts/mutmut_entry.py skips class definitions inheriting from Protocol (_is_protocol_class). Protocol methods are declaration-only stubs, so no meaningful mutant is lost.