targeted-mutation-python
Targeted mutation testing for Python and pytest (tmtpy): observes the runtime values your tests pass through comparisons, synthesizes the nearest boundary and margin bugs your suite cannot distinguish, and tells you whether each surviving edit needs a missing input or a stronger assertion.
Why targeted mutation testing?
Conventional Python mutation tools (mutmut, pytest-gremlins, cosmic-ray) apply fixed syntactic templates (>= → >, + → -, True → False), re-run pytest across candidates, and report a flat list of SURVIVED mutants to diagnose by hand. That workflow leaves three structural gaps:
- Syntactic operator swaps miss value-level boundary and margin bugs. Suppose
qualifies(price)checksprice >= 5000, and tests assertnot qualifies(4800)andqualifies(5000). Those two inputs kill both conventional operator swaps (price > 5000andprice < 5000), yetprice >= 4999—and every threshold in4801..5000—still passes every test. By recording exact scalar extrema when comparison probes are active,targeted-mutation-pythoncomputes the closed interval of undistinguished thresholds (4801through5000), IEEE-754 adjacentfloatboundaries (math.nextafter), and variable-RHS integer margins (balance >= (price - 1)) in a constant number of arithmetic operations regardless of interval width, without an SMT solver or LLM. SURVIVEDconflates missing inputs with weak assertions. Along the Reachability–Infection–Propagation–Reveal (RIPR) model, a surviving comparison mutant means either no test passed an input that changes the comparison (INPUT GAP) or the comparison flipped during a test and the suite still passed (ASSERTION GAP).targeted-mutation-pythonseparates the two, records the pytest node ID where the comparison outcome diverged (when observed inside a test), and—with--verify-witnesses(--suggest-assertions)—runs a generated pytest check against both the original code and a physical source edit before marking it[verified].- Explicit determinism with sound process isolation. By default, every trial runs in a fresh Python interpreter and an independent workspace snapshot using physical source edits. Opting into
--deterministicskips comparison replays whose recorded exact operands prove identical outcomes (using a 3-bit order-class mask checked in Lean 4) and enables an in-memory import overlay—falling back to physical source replays whensys.addaudithookdetects subprocess creation or uninstrumented execution of an observed project file.
| Dimension | Conventional Python mutation tools | targeted-mutation-python (tmtpy) |
|---|---|---|
| Boundary & margin discovery | Fixed token/literal templates | Synthesizes nearest undistinguished arbitrary-precision int thresholds, math.nextafter float boundaries, and variable-RHS int margins (a >= (b - 1)) from runtime extrema |
| Survivor diagnosis | Generic SURVIVED |
Separates INPUT GAP (missing boundary input + interval) from ASSERTION GAP (comparison flipped in a recorded pytest test) |
| Verified assertions | Manual inspection | --verify-witnesses / --suggest-assertions verifies ready-to-paste assert ... checks against original and mutated code |
| Deterministic replay pruning | Re-runs every candidate | --deterministic skips provably equivalent comparison replays ([observed]) and uses compiled import overlays |
| Pull request review | Changed-line filter | --since REV --undo-changes scopes to Git diffs, reverts modified change blocks (UNTESTED CHANGE), and flags WEAKENED TEST regressions |
| Workspace & process safety | In-place edits or shared workers | Isolated snapshots (CoW where available), process-group cleanup, and an optional guarded Linux forkserver |
| Dependencies | Tool-specific runners / plugins | pytest>=8,<10 only; no AI, no SMT solver, no native extension build |
Quick start
Requirements & install
- CPython 3.11–3.14 on Linux or macOS (POSIX process groups are required).
pytest(>=8,<10) installed in the same Python environment as the target project and its test dependencies.- Install the
targeted-mutationpackage (providingtmtpy,targeted-mutation-python, andtargeted-mutationentry points) into your project's virtual environment:
python -m pip install targeted-mutation
Security note: Like
pytest,tmtpyimports and executes target project and test code with your user permissions. Run it only on code you trust. Mutation trials execute inside temporary snapshots rather than modifying your working tree in place (only explicit--output,--write-baseline, and--checkpointpaths are written on the host).
1. Find a missing boundary input (INPUT GAP)
Create a small project with src/shipping.py and test_shipping.py:
# src/shipping.py
def qualifies(price):
return price >= 5000
def discount(cents, pct):
return (cents * pct) // 100
# test_shipping.py
from shipping import discount, qualifies
def test_qualifies():
assert not qualifies(4800)
assert qualifies(5000)
def test_discount():
assert discount(200, 15) == 30
Run tmtpy analyze --deterministic --verify-witnesses:
$ tmtpy analyze --deterministic --verify-witnesses
INPUT GAP src/shipping.py:2:12
price >= 5000 → (price >= 4999) [observed]
distinguishing left operand: 4999
undistinguished interval: 4801 through 5000
[verified] assert qualifies(4999) is False
1 sites, 2 tests, 2 killed, 1 survived, 1 replays avoided, 0 incomplete
$ echo $?
2
(price > 5000) and (price < 5000) were killed (2 killed), while (price >= 4999) needed zero test replays (1 replays avoided) because the recorded operands (4800 and 5000) prove identical outcomes across 4801 through 5000. With --verify-witnesses, assert qualifies(4999) is False passed on the original source and failed at that assertion on the physical source edit. Adding assert not qualifies(4999) to test_qualifies closes every integer threshold gap on that comparison and exits 0.
2. Pinpoint a weak test (ASSERTION GAP)
Now suppose test_qualifies checks assert not qualifies(4800) and assert not qualifies(4999), and calls qualifies(5000) without asserting its return value. tmtpy separates that weak assertion from a missing input, reports the pytest node where the comparison outcome flipped, and verifies the missing check:
$ tmtpy analyze --deterministic --suggest-assertions
ASSERTION GAP src/shipping.py:2:12
price >= 5000 → (price > 5000) [replayed]
observed in test_shipping.py::test_qualifies
[verified] assert qualifies(5000) is True
1 sites, 2 tests, 1 killed, 1 survived, 0 replays avoided, 0 incomplete
3. Catch non-comparison bugs (--full)
Restoring assert qualifies(5000) and passing --full pairs comparison probes with the Python source mutation catalogue—exposing bugs such as integer truncation when dividing before multiplying ((200 // 100) * 15 == 30), float division (30.0 == 30 in Python), and unguarded literal shifts (3000 // 99 == 30):
$ tmtpy analyze --full --lines src/shipping.py:5
SOURCE SURVIVOR src/shipping.py:5:12
(cents * pct) // 100 → (cents * pct / 100) [source-replay]
SOURCE SURVIVOR src/shipping.py:5:12
(cents * pct) // 100 → (cents // 100 * pct) [source-replay]
SOURCE SURVIVOR src/shipping.py:5:29
100 → (99) [source-replay]
3 sites, 2 tests, 9 killed, 3 survived, 0 replays avoided, 0 incomplete
Understanding findings, exit codes & reports
Finding statuses
| Text label | JSON status |
Meaning | What to do |
|---|---|---|---|
INPUT GAP |
input-gap |
Recorded exact operands agree on both the original and mutated comparison (either inferred via [observed] under --deterministic or confirmed by replay). Reports distinguishing_input and threshold_interval when derivable. |
Add a test with the distinguishing operand or margin (pass --verify-survivors to force a replay under --deterministic). |
ASSERTION GAP |
assertion-gap |
A recorded operand pair flipped the comparison outcome (reporting test when observed inside a pytest item), yet the mutated test suite passed. |
Strengthen assertions in the reported pytest node (use --suggest-assertions / --verify-witnesses). |
SOURCE SURVIVOR |
source-survivor |
An edit executed and passed the test suite without exact comparison proof (for non-probe AST rules, --source-only edits, or comparisons whose observations were marked unknown). |
Add a test that exercises and asserts the mutated expression's behavior. |
UNTESTED CHANGE |
untested-change |
With --since REV --undo-changes, reverting a modified block in an existing tracked Python file back to REV was reached and still passed the suite. |
Add a regression test that fails against the pre-change code, or suppress intentional refactorings with # tmt:ignore. |
WEAKENED TEST |
weakened-test |
With --since REV, conventional test files changed since REV let an unsuppressed mutation survive (or go unreached) that the restored REV tests killed on current production code. |
Restore the lost assertion coverage from REV (or pass --no-weakened-tests when old tests no longer apply). |
KILLED |
killed |
A test that activated the mutation subsequently failed (included in JSON/JSONL; omitted from text and SARIF). | None—your suite caught the mutation. |
UNREACHED |
unreached |
No selected test executed the tracked edit (hidden in text unless --show-unreached is passed). |
Add test coverage reaching that code path. |
ERROR / TIMEOUT / UNSTABLE / AUDIT DISAGREEMENT / WITNESS ERROR |
error, timeout, unstable, audit-disagreement, witness-error (plus reserved not-evaluated) |
Execution could not establish a sound verdict (e.g., unrelated test failure without activation, per-trial timeout, nondeterministic test inventory/failure on an unchanged comparison, --audit mismatch, or witness runner failure). Increments incomplete and exits 3 even when inline-suppressed, and is always shown in text and SARIF. |
Fix test nondeterminism, raise --timeout, or inspect detail. |
Each result carries an evidence tag ([...] in text):
observed— skipped under--deterministicbecause exact recorded operands prove identical comparison outcomes.replayed— executed through the in-memory import overlay in--deterministicmode.source-replay— executed against a physical source rewrite in an isolated snapshot.previous-tests— compared against conventional test files restored from--since REV.static— listed statically via--listwithout running pytest.
Exit codes & accounting identities
| Exit code | Meaning |
|---|---|
0 |
Complete run with zero unsuppressed gaps (also --help, version, and --list) |
1 |
Invalid CLI arguments, missing/broken --baseline or mismatched --checkpoint, or failing/inconsistent pytest baseline |
2 |
Complete run (incomplete == 0) with at least one unsuppressed gap (input-gap, assertion-gap, source-survivor, untested-change, weakened-test) |
3 |
Incomplete run (incomplete > 0); --write-baseline does not overwrite the baseline file |
130 |
Interrupted by SIGINT or SIGTERM (worker process groups are terminated and reaped) |
Every JSON report (--format json) and JSONL summary row (--format jsonl) satisfies two exact accounting identities:
counts.mutants_run == counts.killed + counts.survivedcounts.survived == counts.survivor_breakdown.reported + counts.survivor_breakdown.suppressed
Execution work is tracked separately in counts.mutation_replays (overlay runs), counts.source_runs (physical runs), counts.avoided (pruned input-gaps), counts.audit_runs, counts.resumed (checkpoint hits), and—when active—counts.forkserver_runs.
Formats, suppressions & stable IDs
- Terminal safety (
text): Strips 7-bit/8-bit ANSI escape sequences, C0/C1 control characters, Unicode BiDi overrides, and embedded newlines from untrusted project strings onstdoutandstderr, while leaving string fields unstripped injson,jsonl, andsarif. - Versioned JSON & JSONL (
schema: 1):threshold_intervalbounds anddistinguishing_inputare serialized as base-10/decimal strings (ornullwhen unbounded) so arbitrary-precision Python integers beyond 64 bits never lose precision.operandspreserves exact type tags (inthex,byteshex,float,str). - SARIF 2.1.0 (
sarif): Emits unsuppressed gaps (warning) and unsuppressed incomplete verdicts (error) with%SRCROOT%-relative URIs, UTF-16startColumn/endColumnoffsets,invocations[].executionSuccessful, andpartialFingerprints["targetedMutationId/v1"]. - Inline suppressions (
# tmt:ignore/# pragma: no mutate): Add# tmt:ignore [reason]or Mutmut-compatible# pragma: no mutateon a line intersecting a candidate's AST span or on standalone comment line(s) immediately above its first line. Suppressed gaps record"suppression"("<reason>","pragma: no mutate","inline directive", or"baseline"), incrementsurvivor_breakdown.suppressed, and do not trigger exit code2. - Move-resilient IDs: Candidate IDs hash
(repo_relative_path, enclosing_scope, normalized_ast, occurrence_in_scope, rule, replacement), so adding lines or moving an unchanged function within its file preserves--baselineand--shardassignments.
Mutation profiles & operator catalogue
Profiles (--mutators)
| Profile | Shorthand | What runs |
|---|---|---|
targeted (default) |
(none) | Instruments standalone <, <=, >, >=, ==, != comparisons; evaluates boundary and negation swaps plus observation-synthesized int/float thresholds and variable-RHS int margins. |
conventional |
--conventional |
Runs the static boundary and negation swaps on standalone comparisons without threshold/margin synthesis and without --deterministic pruning. |
full |
--full |
Combines targeted comparison probes with the complete Python AST source mutation catalogue below. Under --deterministic, observation pruning also reuses recorded evidence for comparison literal edits (integer-step, float-step, string-literal, signed numeric literals), side-effect-free constant conditions (condition-constant), short-circuiting and/or expressions (boolean-operand, boolean-operator), chained comparisons, and exact-int arithmetic/unary operations directly inside comparisons—keeping all --full mutant IDs intact. |
source-only |
--source-only |
Evaluates the complete static AST mutation catalogue exclusively through isolated physical source edits without an instrumented probe baseline. |
Rule catalogue (for reports & --exclude-rule <RULE>)
| Rule name | Profile | Generated mutations |
|---|---|---|
comparison-operator |
all | Standalone < ↔ <=, > ↔ >=, and negation (< ↔ >=, <= ↔ >, == ↔ !=). full and source-only add all remaining ordered replacements, in ↔ not in, is ↔ is not, and per-operator edits inside chained comparisons (a < x <= b). |
comparison-threshold |
targeted, full |
Nearest undistinguished constant-RHS threshold: n - 1 / n + 1 for int, or adjacent IEEE-754 finite float via math.nextafter for float. |
comparison-margin |
targeted, full |
Nearest undistinguished variable-RHS integer margin: a >= (b - 1) / a >= (b + 1) when observed exact integers leave unit slack. |
arithmetic-operator |
full, source-only |
+ ↔ -; * → /, //; / → *, //; // → /, *; % → *; ** → *; @ → *; & / | / ^ swaps; << ↔ >>. |
augassign-operator |
full, source-only |
Compound assignments (+= ↔ -=, *= → /=, //=, /= → *=, //=, //= → /=, *=, %= → *=, &=/|=/^=, <<= ↔ >>=). |
statement-delete |
full, source-only |
Replaces standalone non-docstring expression statements and augmented assignments inside functions, branches, and loops with pass. |
rounding-order |
full, source-only |
(a * b) / c → ((a / c) * b), ((b / c) * a) (and the same for floor division //). |
boolean-operator |
full, source-only |
and ↔ or. |
boolean-operand |
full, source-only |
Drops each individual operand in an and / or expression (a and b → a, b). |
unary-operator |
full, source-only |
Removes not x → x and ~x → x; swaps unary +x ↔ -x. |
condition-constant |
full, source-only |
Replaces if and conditional expression (a if cond else b) conditions with True and False, and while conditions with False. |
integer-step |
full, source-only |
Replaces int literals (excluding bool) with n - 1 and n + 1. |
float-step |
full, source-only |
Replaces float literals with x - 1.0 and x + 1.0. |
boolean-literal |
full, source-only |
Swaps True ↔ False. |
string-literal |
full, source-only |
Replaces non-empty str/bytes literals with ""/b"" and empty literals with "mutated"/b"mutated" (standalone expression docstrings, f-strings, match patterns, and type annotations are excluded). |
return-value |
full, source-only |
Replaces return expr values with None, True, False, and 0. |
call-substitution |
full, source-only |
Swaps calls matching these function or attribute names: min ↔ max, all ↔ any, ceil ↔ floor, startswith ↔ endswith, lstrip ↔ rstrip, find ↔ rfind, index ↔ rindex. |
git-revert |
--undo-changes |
Reverts each SequenceMatcher diff block in selected modified tracked files back to --since REV to detect UNTESTED CHANGE. |
CLI workflows & option reference
Common recipes
# Fast local boundary & assertion check with verified pytest suggestions
tmtpy analyze --deterministic --verify-witnesses
# Narrow to specific files, line ranges, test nodes, and extra pytest arguments after --
tmtpy analyze src/cart.py --lines src/cart.py:10-40 --test tests/test_cart.py -- -k "discount or shipping"
# Pull request gate: changed lines + untracked files, change-block reversion, weakened-test check, and SARIF output
tmtpy analyze --since origin/main --undo-changes --format sarif --output tmt.sarif
# Incremental adoption: record current gaps once, then block only new gaps in CI
tmtpy analyze --deterministic --write-baseline .tmt-baseline.json
tmtpy analyze --deterministic --baseline .tmt-baseline.json
# 4-way CI sharding with per-shard crash-recoverable checkpoint journals
tmtpy analyze --full --shard 0/4 --checkpoint .tmt-shard-0.jsonl --format jsonl
tmtpy analyze --full --list --shard 0/4 --format json
# Cross-check pruned and overlay verdicts against independent physical source edits
tmtpy analyze --deterministic --audit
# Experimental Linux pytest forkserver (preloads pytest in a guarded broker per worker lane)
tmtpy analyze --deterministic --runner forkserver -j 4
Option reference (tmtpy analyze [options] [paths...] [-- pytest_args...])
Target & Scope
| Option | Default | Description |
|---|---|---|
[paths...] |
src if present, else . |
Python files or directories relative to --root (test directories, conftest.py, test_*.py, *_test.py, and symlinks are skipped during directory walks) |
--root <DIR> |
current directory | Target pytest project root |
--lines <PATH:FIRST[-LAST]> |
— | Restrict mutations to specific 1-based line ranges (repeatable; intersects --since) |
--since <REV> |
— | Restrict mutations to lines changed since Git <REV> plus untracked .py files, and check modified conventional test files (test*/, test_*.py, *_test.py, conftest.py) for WEAKENED TEST |
--undo-changes |
false |
Also revert diff blocks in selected modified tracked Python files back to --since (requires --since; newly added or deleted files are not reverted) |
--no-weakened-tests |
false |
Skip replaying current gaps against test files restored from --since |
--exclude <GLOB> |
— | Exclude matching repository-relative source paths from discovery (repeatable) |
--copy-exclude <GLOB> |
— | Exclude matching files or directories when snapshotting the project workspace (repeatable) |
--copy-include <GLOB> |
— | Override automatic Cargo target/ snapshot exclusion for matching repository-relative paths or globs (repeatable; does not override --copy-exclude or default omits) |
Profiles & Filtering
| Option | Default | Description |
|---|---|---|
--mutators <PROFILE> |
targeted |
Select targeted, conventional, full, or source-only |
--full / --source-only / --conventional |
— | Shorthand flags for --mutators (mutually exclusive) |
--exclude-rule <RULE> |
— | Exclude a specific rule name from evaluation (repeatable; see rule catalogue above) |
--list |
false |
List static mutation candidates without running pytest (observation-synthesized thresholds/margins require a live run) |
Execution, Determinism & Verification
| Option | Default | Description |
|---|---|---|
--test <SELECTOR> |
— | Pytest file path or node ID passed to baseline and mutation trials (repeatable; additional raw pytest flags follow --, while witness verification runs its own synthetic test file) |
-j, --jobs <N> |
1 |
Concurrent mutation trial workers |
--timeout <SECONDS> |
adaptive (max(5s, 5s + 5×baseline)) |
Timeout per pytest process execution |
--runner <spawn|forkserver> |
spawn |
Trial process backend (forkserver is experimental and supported on Linux only) |
--deterministic |
false |
Enable observation-based replay pruning for equivalent comparisons and in-memory import overlays |
--verify-survivors |
false |
Replay comparison edits even when --deterministic observations predict survival |
--audit |
false |
Re-run pruned and overlay verdicts against independent physical source edits and report mismatches as audit-disagreement |
--verify-witnesses, --suggest-assertions |
false |
Verify synthesized pytest assertions against both the original snapshot and physical source mutants |
Output, Baselines, Sharding & Checkpoints
| Option | Default | Description |
|---|---|---|
--format <FMT> |
text |
Report format: text, json, jsonl, or sarif |
--output <FILE> |
stdout |
Write the rendered report atomically to <FILE> |
--baseline-log <FILE> |
— | Atomically write the full baseline pytest log to <FILE> (useful when many tests fail and stderr output is truncated) |
--show-unreached |
false |
Include UNREACHED edits in text output |
--baseline <FILE> |
— | Suppress known finding IDs recorded in <FILE> |
--write-baseline <FILE> |
— | Atomically write current gap IDs (excluding inline # tmt:ignore) to <FILE> when exit_code != 3 |
--shard <INDEX/COUNT> |
0/1 |
Partition candidate IDs deterministically (int(id, 16) % COUNT == INDEX, 0 <= INDEX < COUNT) |
--checkpoint <FILE> |
— | Lock and resume completed verdicts from an append-only JSONL journal bound to the exact snapshot, interpreter, environment, baseline signature, observations, and edit plan |
-q, --quiet |
false |
Suppress progress updates and advisory warnings on stderr |
--no-config |
false |
Ignore [tool.tmt] defaults in pyproject.toml |
Project configuration (pyproject.toml)
You can store default analyze options under [tool.tmt] in <root>/pyproject.toml (loaded automatically unless --no-config is passed; explicit CLI flags always override):
[tool.tmt]
paths = ["src"]
deterministic = true
jobs = 4
format = "text"
exclude_rule = ["return-value"]
How it works, soundness & limits
flowchart LR
A["Resolve Scope & AST Sites<br/>(move-resilient IDs)"] --> B["Pytest Baseline Gate<br/>(ordinary + probe when applicable)"]
B --> C["Summarize Exact Scalars<br/>(int deltas, float extrema, 3-bit classes)"]
C --> D["Plan Edits<br/>(operators, thresholds, margins, AST rules)"]
D -->|"--deterministic & same"| E["INPUT GAP [observed]<br/>(0 replays)"]
D -->|"--deterministic probe edit"| F["Import Overlay Replay<br/>(+ audit-hook fallback)"]
D -->|"default / non-probe AST / --source-only"| G["Physical Source Replay<br/>(opcode/line activation trace)"]
F --> H["KILLED / GAP / Witness Check"]
G --> H
Execution & soundness guarantees
- Baseline parity gate. Before running any mutation,
tmtpyruns an ordinarypytestbaseline in a clean snapshot. Whenever comparison probes are selected (targeted,conventional, orfullwith comparison sites), it runs a second instrumentedpytestbaseline and verifies identical collected node lists, execution order, and per-phase outcomes. - In-frame operand observation. Standalone comparisons stay in their original Python stack frame so operand evaluation order, short-circuiting, and
sys._getframecallers remain intact. Constant-RHS scalar comparisons use a single callback (constant_rhs); dynamic comparisons pair frame-keyedleftandrightcallbacks. Only exactint(excludingbool), finitefloat, and boundedstr/bytes(<= 4096units) are summarized; custom types, subclasses, mixed scalar types,NaN,±inf, or interrupted evaluations mark the siteunknownand disable proof-based pruning. - Interval & 3-bit mask algebra. Observed
intdifferences (left - right) directly yield the closed interval of equivalent thresholds or variable-RHS margins in a constant number of arithmetic operations regardless of interval width, supporting arbitrary-precision Python integers. Unshifted operator replacements are decided by a 3-bit(less, equal, greater)mask proven equivalent to pairwise evaluation in Observation.lean. - Causally gated
killedverdicts. Physical source replays track bytecode instruction offsets (f_trace_opcodes) for expressions and line events for diff reverts; import overlays wrap replaced expressions with an activation tap. A failing trial is classified askilledonly if pytest exited with test failures, execution followed the baseline prefix, and a test failed after activating the mutated site—preventing broken imports or unrelated flaky tests from masquerading as killed mutants. - Isolated snapshots & process-group cleanup. The snapshot excludes
.git,.venv, caches,dist/build,node_modules, and external symlinks (rewriting internal absolute symlinks into snapshot-relative links). Per-trial copies try nativecopyfile(3)(COPYFILE_CLONE) on macOS andcp -a --reflink=autoon Linux before falling back tocp/shutil.copytree, and workers run in dedicated sessions (start_new_session=True) waited viakqueue/pidfd(withsubprocess.waitfallback) and cleaned up withSIGKILLto the process group. - Guarded Linux forkserver (
--runner forkserver). On Linux, an opt-in broker preloadspytestonce per worker lane and forks isolated trial processes while keeping fresh subprocesses for baselines and--audit. During startup and warm-baseline validation, custom startup hooks (sitecustomize,usercustomize, or executable.pthimports other than standard setuptoolsdistutils-precedence.pth), module shadowing, or baseline mismatches fall back tospawnwith a diagnostic onstderr; broker failures after dispatching a trial surface as incomplete evidence rather than risking duplicate execution (see docs/design/forkserver.md).
Assumptions & known limits
- Determinism contract:
--deterministicassumes repeatable test collection, execution order, operand values, and side effects. Nondeterministic suites should stick to the default physical mode or pair--deterministicwith--verify-survivors/--audit. - Serial pytest inside workers: Run pytest in its standard serial mode inside each trial (do not pass
pytest-xdist-nflags); scale horizontally withtmtpy analyze -j <N>ortmtpy analyze --shard <INDEX/COUNT>. - Tracing & loader boundaries: Child subprocesses, C extensions, custom import loaders, or pytest plugins that replace
sys.settrace(such as coverage tracers) can prevent activation or observation tracking; detected subprocess spawns and observed-file loader bypasses disable pruning, while lost trace hooks surface as incomplete evidence (exit3). - Witness synthesis scope: Concrete
[verified]assertions cover both direct comparison-returning functions (forINPUT GAPandASSERTION GAP) and in-place assertion strengthening for bare calls in existing tests (including class methods, multi-line functions, andSOURCE SURVIVORgaps). Reported distinguishing operands are algebraic comparison witnesses that may still be constrained by higher-level callers. - External side effects: Relative file writes stay inside each disposable trial copy, whereas tests writing to hardcoded absolute paths or external network services carry the same side effects as running
pytestdirectly.
Benchmarks
benchmarks/README.md documents reproducible serial comparisons against Mutmut 3.8.1, pytest-gremlins 1.15.0, and Cosmic Ray 8.9.0 on CPython 3.12 / pytest 9.2 (confirming verdict parity on matched conventional edits while inferring additional threshold survivors without replay), alongside paired measurements for native CoW/wait/probe optimizations (23–28% campaign wall-time reduction; docs/design/performance.md) and the Linux forkserver (26–27% reduction in an isolated Linux guest).
Development & formal verification
python -m pip install -e . ruff
python -m pytest
ruff check .
# Combinatorial PICT seed checks (5 models under verification/pict/)
for model in campaign copy-paths fast-paths forkserver probe-paths; do
pict "verification/pict/${model}.pict" "/e:verification/pict/${model}.seed.tsv" > "/tmp/${model}.tsv"
python3 scripts/pict-check "/tmp/${model}.tsv" "verification/pict/${model}.seed.tsv"
done
# TLA+ / TLC protocol verification (baseline gating, worker waits, and forkserver ownership)
for model in Campaign WorkerWait ForkServer; do
tla2tools -workers 1 -config "verification/tla/${model}.cfg" "verification/tla/${model}.tla"
done
Design notes:
- Core architecture & execution model
- Replay & observation performance
- Linux pytest forkserver protocol
- Lean 4 order-class & boundary proofs
Related implementations & prior work
targeted-mutation-python is the Python sibling of:
- Rust (
cargo tmt): github.com/t-k/targeted-mutation - JavaScript / TypeScript (
targeted-mutation): github.com/t-k/targeted-mutation-ts - Go (
targeted-mutation-go): github.com/t-k/targeted-mutation-go
Generating mutants from runtime test observations is known in the literature as test-aware mutant generation, alongside related lines of work such as SEMu (symbolic execution to kill surviving mutants), DSpot (assertion amplification), the W-method (distinguishing sequences for finite state machines), and Meta's ACH. Like its Rust, TypeScript, and Go siblings, targeted-mutation-python occupies the SMT-solver-free, AI-free corner of that design space: record compact runtime extrema and solve undistinguished intervals directly.
License
Licensed under the Apache License, Version 2.0.
Metadata
Release files for targeted-mutation 0.1.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| targeted_mutation-0.1.2.tar.gz | 135.9 kB | With provenance | Details for targeted_mutation-0.1.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| targeted_mutation-0.1.2-py3-none-any.whl | Python 3 | none | any | Details for targeted_mutation-0.1.2-py3-none-any.whl |
Total release size: 219.5 kB
Release files / targeted_mutation-0.1.2.tar.gz
| Download URL | targeted_mutation-0.1.2.tar.gz |
|---|---|
| Size | 135.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
740ddc700024487dafb17c2ccb3a83e7360505cc3b0c5ee6f9113fe9e4df2489
|
|
BLAKE2b-256 checksum How to use checksums |
6530f33d3cde9fc25ae65ce72ed37e29696d297853fb8e09542616ac06877e02
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logRelease files / targeted_mutation-0.1.2-py3-none-any.whl
| Download URL | targeted_mutation-0.1.2-py3-none-any.whl |
|---|---|
| Size | 83.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
d97fdfd58cf7adb83a3187b9f8a29fde746141d132cb79a293b31833d9b63978
|
|
BLAKE2b-256 checksum How to use checksums |
4b628fc13141eafcf84db8912d1e7536b4a704bd2f31c8100c0603fbad07e151
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logSecurity for targeted-mutation 0.1.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for targeted_mutation-0.1.2.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.