targeted-mutation
Targeted mutation testing for Rust (cargo tmt): finds the realistic wrong implementations your tests would let through — and tells you the exact input or assertion that catches them.
Why targeted mutation testing?
Classic mutation testing mutates code blindly (< → <=), recompiles the crate for every mutant, runs the whole test suite each time, and leaves you with "mutant survived" to diagnose by hand.
cargo tmt flips the workflow:
- It compiles your crate once with runtime-switched probes and traces what values your tests actually feed each site.
- From those observations, it uses interval arithmetic to compute the boundary mutants guaranteed to pass every test (for deterministic tests; re-verified by default) — without needing AI or an SMT solver.
- For mutants that do change an observation, it runs only the tests affected by that site, traces what changed downstream, and points straight to the missing input or weak assertion.
| Classic mutation testing | Targeted mutation testing (cargo tmt) |
|
|---|---|---|
| Builds | Rebuilds once per mutant (O(N)) |
1 build for all probe-compatible mutants |
| Test runs | Runs the whole suite per mutant | Skips provable survivors; runs only affected tests |
| Output | MISSED src/lib.rs:2 replace >= with > |
"Saw age = 17, 20 → add a test with age = 18" |
| Weak assertions | Manual debugging | Effect trace (with the mutant, ...) + verified assert_eq! (--rebuild) |
| Dependencies | — | Pure Rust, no AI, no SMT solver |
Quick start
Building cargo tmt requires Rust 1.88 or newer. The crates it analyses are built with whatever toolchain is active for them.
&&
Put this in src/lib.rs:
Run cargo tmt:
$ cargo tmt --quiet
INPUT GAP src/lib.rs:2:5
age >= 18
passes every test as: `age >= 19`, `age >= 20` [re-run: tests pass]
nearest values the tests passed: `age` = 17, 20
add a test with `age` = 18 (the original gives true)
demo: 4 sites, 1 input gaps, 0 assertion gaps, 8 mutants run (6 killed), 0 sites unreached
$ echo $?
2
Add the exact test it asks for and re-run:
$ cargo tmt --quiet
demo: 4 sites, 0 input gaps, 0 assertion gaps, 7 mutants run (7 killed), 0 sites unreached
$ echo $?
0
Deeper bugs & verified witnesses (--rebuild)
Some wrong implementations can only be caught by building source mutants one by one — and with --rebuild, cargo tmt also synthesizes and verifies concrete distinguishing tests. Append a basis-points fee function and its tests to the same src/lib.rs:
Plain cargo tmt finds nothing; cargo tmt --rebuild tries dividing before multiplying, runs a generated test against both versions, and gives the exact assertion to add:
SURVIVOR src/lib.rs:21:5
u64::from(cents) * u64::from(bps) / 10_000
passes every test as: `u64::from(cents) / 10_000 * u64::from(bps)` (divide before multiplying)
verified on `fee(10080, 125)`: original returned 126, mutant returned 125
The tests pass with the division by 10000 done first; this `cents` is not a multiple of it.
add a test with `assert_eq!(fee(10080, 125), 126);`
Security note:
cargo tmtbuilds and runs the target crate's tests and build scripts, just ascargo testdoes. Run it only on code you trust.
Understanding findings
| Finding | Meaning | What to add |
|---|---|---|
INPUT GAP |
No test passes a value separating the mutant from the original. | A test with the listed boundary input. |
ASSERTION GAP |
Tests execute the changed behaviour and still pass. | An assertion in one of the listed tests (guided by with the mutant, ...). |
SURVIVOR |
A source-built mutant (--rebuild / --source-only) passes all tests. |
A test using the verified witness (if shown) or covering the mutated code. |
UNTESTED CHANGE |
With --since REV + rebuild mode, reverting a diff hunk still passes all tests. |
A test that fails on the old code (or silence refactorings with // tmt:ignore). |
UNREACHED |
No test executes the site (shown with --show-unreached). |
A test reaching the branch/code. |
UNSTABLE |
A trace-predicted survivor failed on re-run. | Fix test nondeterminism first. |
Findings on the same source line are grouped into one block.
Input gaps & impossible-value filtering
In fixtures/eligibility, the tests only pass 17 and 20 to age >= 18, so any threshold in 18..=20 behaves identically on every test. cargo tmt derives that range directly from the two nearest observations and names age = 18.
Values no input can produce are filtered out automatically: blocks * 8 is always a multiple of 8, flags & 0xF0 only has bits of the mask, and n % 10 is strictly below 10. When no reachable value lies between the observed values — or when an expression cannot flip a comparison (n % 10 < 10, flags & 0b1100 == 1) — no bogus gap is reported. Reachability is derived from the expression's outer integer operation where tests executed it on primitive integers and the invariant holds under wrapping (power-of-two products, bit shifts modulo type width, bit masks, and remainders).
Assertion gaps & effect tracing
fixtures/batch-store has an atomic batch commit whose test checks that a failing batch returns an error, but never inspects store state afterwards:
$ cargo tmt fixtures/batch-store
ASSERTION GAP src/lib.rs:33:9
self.check_preconditions(batch)?;
passes every test as: delete `self.check_preconditions(batch)?;`
these tests run the changed code and still pass: tests::batch_writes_are_visible_after_commit, tests::commit_fails_when_an_update_target_is_missing
with the mutant, `tests::commit_fails_when_an_update_target_is_missing` now runs `self.docs.insert(key.clone(), value.clone());` (src/lib.rs:59)
add an assertion on what this code is responsible for
For each assertion gap, cargo tmt replays one surviving mutant with tracing on (effects_of in JSON) and compares its trace with the original run. When the mutant changes nothing observable in the trace, either the test ignores the mutated value, its assertion holds for both outcomes (assert_ne!(bucket(3), "none")), or the mutant is equivalent.
How it works
- Instrument. Rewrites comparisons, boolean operators, arithmetic/bitwise operators, ranges,
min/max,first/last, match arms/guards, struct fields, return exits, and deletable statements into runtime-switched probes inside an isolated working copy. The crate is compiled once. - Trace. Runs the tests once and records per-test observations (for integer comparisons: nearest
lhs - rhson each side of zero and whether operands were ever equal). - Plan. Computes provable input-gap survivor ranges by interval arithmetic, excluding impossible values within the operand types (
x >= 0for unsignedx, masks, remainders, etc.). By default one predicted survivor per gap is re-run to confirm (--no-verifyskips this). - Verify & Run. Runs remaining mutants only against the tests whose observations change, stopping at the first failure. Survivors are traced to show downstream effects (
--no-effectsskips this). - Source builds & witnesses (optional
--rebuild/--source-only). Code that cannot carry runtime probes (const fn,const/staticinitializers,impl Iterator, untyped literal pairs like60 * 60, complex compound assignment places like*map.entry(k).or_insert(0) += 1, secondary/shared targets, or probes dropped by repair) is compiled and tested per mutant. Without--rebuild, the summary tells you how many candidates need it.
What is mutated
| Code | Mutants | Provable survivor when |
|---|---|---|
a < b, a >= 18 (integers) |
shifted thresholds, negated operator | no test passes a value between old and new boundary |
x > 30.5 (floats) |
>=, thresholds between nearest observed values |
operands were never equal in any test |
comparisons on other PartialOrd types |
< ↔ <=, negation |
operands were never equal in any test |
a == b, a != b |
negation, true / false |
result was identical in every test |
a && b, a || b |
ignored operand (a && { b; true }, { a; b }), swapped operator |
ignored operand never decided the result |
+, -, *, /, % & compound assigns |
two alternatives each (+→-,*; -→+,/; *→/,+; /→*,%; %→/,+) |
both operators are defined and agree on every observed pair |
&, |, ^, <<, >> & compound assigns |
bitwise alternatives / << ↔ >> |
as above |
!x (bool), -x / -1 |
x, 1 |
always run |
| function bodies | return-type value replacements ((), 0/1/-1, bool, String, Option, Result, Vec/collections, Box, tuples/arrays, Default::default(), plus --error EXPR) |
always run |
match arm guards |
true, false |
guard had the same value in every test |
match arms before a catch-all |
arm removed (falls through) | always run |
struct literal field with ..base |
field omitted (falls back to base) |
always run |
-> bool / -> Option<T> normal exits |
true / false (bool), None (Option) |
function always returned that value |
a.max(b), a.min(b) (numbers) |
swapped min ↔ max |
operands were equal in every test |
v.first(), v.last() (slice/Vec/array/BTreeSet) |
swapped first ↔ last |
no test passed more than one element |
a..b, a..=b (integers) |
inclusive ↔ exclusive end | always run |
f(x);, check()?;, x += 1;, x = y; |
statement deleted | always run |
- Arithmetic on non-primitive types (
String + &str,Duration + Duration) and!on non-booltypes are left untouched. - Enclosing sites do not repeat inner findings (if
a > 0is always true,a > 0 && bdoes not emit a duplicate finding). - Arguments inside
assert_eq!,assert_ne!,vec!,format!,print!,println!,eprint!,eprintln!,write!,writeln!,panic!,unreachable!,todo!,unimplemented!,format_args!, andmatches!are mutated;assert!,debug_assert!, anddbg!are skipped because they stringify their argument expression. - Functions,
implblocks, and modules marked#[mutants::skip](including insidecfg_attr) are skipped. - Probes that fail to compile are dropped automatically and retried;
--rebuildevaluates their source mutants individually.
Verified witnesses (--rebuild)
When --rebuild (or --source-only) finds a surviving mutant in a library file, cargo tmt can synthesize and run a concrete distinguishing test in the working copy, reporting both observed outputs and an assert_eq! line (exposed as findings[].witness in JSON):
- Slice searches & inclusive ranges: two-match inputs distinguishing
positionvsrposition, and minimal edits to literal test slices for inclusive range bounds. - Bitmasks & Unicode length: partial multi-bit masks (any-bit vs all-bit) and non-ASCII characters (
chars().count()vs.len()). - Comparisons & sort keys: swapping same-type integer parameters/fields across a boundary, and two-record inputs separating sort-key choices.
- Post-failure state reads: borrowing a read from a nearby test to check persisted state after a failing batch operation.
- Integer rounding (
a * b / c): tryinga / c * bwith the smallest non-multiple offset from an existing test call (fixtures/rounding). - Composite keys (
format!/ tuples): omitting each argument to detect map keys that never collide in tests (fixtures/keyed). - Paired endian codecs: flipping byte order on both encode and decode to detect round-trip-only codec tests and suggest a fixed-bytes check.
- Stronger assertions on existing test calls: replaying unpinned calls (
assert_ne!(bucket(3), "none"),assert!(total(&[1, 2]) > 0),letbindings, includingsuper::f(...)inmod tests) in place inside a copy of the test to suggest exactassert_eq!values (witness.in_test,in_test_line,in_test_column).
Try the bundled witness fixtures directly:
In-place assertion replay runs a copy of the test beside the original and records the value at the exact point of the call (preserving setup before and teardown after):
- Calls already pinned by
assert_eq!/assert!(whose other side calls no function of the file), multi-line calls, closure/branch/loop calls, methods, generic/async/unsafe/constfunctions, and calls with non-literal arguments are skipped. - Tests that are
#[ignore],#[should_panic], returnResult, or shadow the function name with aletbinding are skipped. - At most 4 distinct calls (deduplicated by normalized argument tokens) are tried per function; not active with
--literal-operators. - A test that depends on its own thread name or
line!(), or holds a lock required byDebug, can differ in the copied test.
PR-scoped analysis (--since REV)
Pass --since "$(git merge-base origin/main HEAD)" to scope analysis to lines changed in a pull request plus untracked files.
Untested changes (--since + --rebuild / --source-only)
Each diff hunk in production code is reverted to REV, built, and tested. If every test still passes, the tests cannot tell the new code from the old:
$ cargo tmt --rebuild --since "$(git merge-base origin/main HEAD)"
UNTESTED CHANGE src/lib.rs:9:1
now - used < 30 && created <= used
passes every test with the code as it was: `let _ = used; now - created < 30`
no test tells this change from the code as it was at 91e1dc927360: add one that fails without it
Weakened tests (--since)
When a file's inline tests (#[cfg(test)] / #[test]) changed since REV, cargo tmt inspects the whole file and re-runs surviving mutants in unchanged lines against the tests as they were at REV. Mutants the old tests caught are reported under weakened (and as weakened-test in SARIF):
INPUT GAP src/lib.rs:27:5
age >= 18
passes every test as: `age >= 19`, `age >= 20` [re-run: tests pass]
nearest values the tests passed: `age` = 17, 20
add a test with `age` = 18 (the original gives true)
the tests as they were at e76c0bd70fff found this out: a change to the tests lets it through
- Comment-only, whitespace-only, test-only, and trailing-comma-only hunks (in braces, brackets, and plain calls) are ignored.
#[doc = ".."]passed to a macro counts as a token; doc comments do not. - Test code is kept intact when reverting production hunks (mixed hunks with unequal old/new line counts are reported as not evaluated).
- Changes inside
cfg-disabled code are skipped when the built tokens are identical (accounting forline!,column!,#[track_caller],RUSTFLAGS, and build scripts). - Hunks that fail to compile alone are retried together per file (and across files if needed).
- Changes are tried even where no probe site exists (e.g. constants), but are not tried with
--shardor--list. In JSON they appear askind: "survivor"withchange_since. - Weakened-test detection needs no
--rebuild(costs two extra builds only when tests changed), skips pre-existing gaps, falls back to changed lines if old tests do not compile/pass on new code, and does not trace standalonetests/*.rsfiles back to library files.
CLI & workflows
Run cargo tmt -h for a compact overview or cargo tmt --help for full descriptions, examples, and exit codes.
Common recipes
# Current package (fast probe mode)
# Pull request diff with source builds and verified witnesses
# Workspace streaming (preserves completed packages if one fails)
# GitHub Code Scanning / SARIF 2.1.0
# CI sharding in source-only mode
# Migrating a cargo-mutants + nextest CI job
# Preview source edits without building or running tests
Exit codes
| Code | Meaning |
|---|---|
0 |
No gaps found (also --help and --version) |
1 |
Analysis or CLI error (invalid arguments, baseline tests failed, build error) |
2 |
Test gaps, unstable predictions, or --audit discrepancies found |
3 |
Incomplete evaluation (unconfirmed parallel timeouts, no mutants executed, or --source-only timeout/unevaluated) |
Option reference
Options are grouped into the same six workflow sections shown by cargo tmt --help:
Target & Scope
| Option | Description |
|---|---|
[DIR] / -d, --dir <DIR> |
Directory of the Cargo package or workspace (default: .) |
-p, --package <PACKAGE> |
Workspace member to analyse (repeatable or comma-separated) |
--workspace |
Analyse all workspace members |
--since <REV> |
Analyse only code changed since REV, plus untracked files |
--lines <FILE:FROM-TO> |
Analyse only specific lines (FILE:FROM-TO, FILE:LINE, or FILE, relative to each package; repeatable) |
Mutation Mode
| Option | Description |
|---|---|
--rebuild |
Also build source-only mutants and synthesize/verify witnesses |
--source-only |
Build every supported mutant directly from source (use when tests clear env vars via Command::env_clear()) |
--list |
Preview source mutation candidates without building or running tests |
--error <EXPR> |
Also replace Result returns with Err(EXPR) (repeatable; e.g. --error '"mutated".into()') |
--literal-operators |
Replace only the operator token without parenthesizing operands (--source-only) |
--shard <K/N> |
Select zero-based shard K/N (--source-only) |
--sharding <slice|round-robin> |
Candidate distribution across shards (default: slice) |
--no-verify |
Trust the trace without re-running tests against predicted survivors |
--no-effects |
Skip effect tracing on surviving mutants |
--audit <N> |
Self-check: re-run up to N survivors against all tests, rebuild & compare up to N probe mutants from source, and re-record traces to catch nondeterminism |
Test Execution & Selection
| Option | Description |
|---|---|
--also-test <PACKAGE> |
Also run tests from another workspace package (repeatable) |
--dependents |
Also run tests of every workspace package depending on the analysed one |
--test-workspace[=<BOOL>] |
Run tests from all workspace members against every mutation |
--doc |
Also run doc tests (recompiled per reached mutant; slower) |
--test-tool <cargo|nextest> |
Select runner (nextest requires --source-only, Unix) |
--nextest-profile <PROFILE> |
Nextest profile to use with --test-tool nextest |
--isolate-tests |
Run one selected libtest test per process (standard libtest executables; no doc tests) |
--test-target <TARGET> |
Select Cargo test artifact names to run and, where possible, narrow builds (analysis.test_selection.build_scope) |
--include-test <NAME> / --exclude-test <NAME> |
Include/exclude exact libtest names (repeatable; enables isolation) |
--include-ignored |
Also allow #[ignore] tests |
--test-wrapper <PATH> |
Workspace-relative wrapper executable invoked with each test binary and its args (preserves status and TMT_* env) |
--wrapper-grace <SECONDS> |
Unix timeout SIGTERM grace period for --test-wrapper (default: 2, 0 kills immediately) |
Output & Baselines
| Option | Description |
|---|---|
--format <text|json|jsonl|sarif> |
Output format (default: text). --json, --jsonl, and --sarif remain as shorthand flags. |
--show-unreached |
Also list mutation sites that no test executed |
-q, --quiet |
Suppress progress output on stderr (explicit timeout warnings still print) |
--baseline <FILE> |
Suppress findings already recorded in FILE |
--write-baseline <FILE> |
Write this run's findings to FILE for future --baseline runs |
- Inline suppressions: Add
// tmt:ignore <reason>on the line itself (applies to that line only) or on a standalone comment line directly above (applies to the next line). - Stable baseline IDs: Baseline v2 identifies findings by
(kind, file, item, code, occurrence)without line numbers or mutant wording, so findings survive edits and moves (legacy fingerprint files are still read). Suppressed findings do not affect exit status. - SARIF 2.1.0: Emits repo-root-relative URIs,
partialFingerprints,properties.analysis/properties.audit, and rules for input gaps, assertion gaps, survivors, unstable predictions, weakened tests, and audit disagreements. With--workspace, emits one run per package (executionSuccessful: falseon member errors).
Performance & Cargo Build
| Option | Description |
|---|---|
-j, --jobs <N> |
Mutants to run concurrently (default: 1; raise only if tests use no fixed ports or shared files) |
--baseline-jobs <N> |
Concurrent isolated baseline tests (default: 1) |
--timeout <SECONDS> |
Per-runner timeout under a mutant (default: 5s + 5x measured baseline; warns on stderr if baseline meets/exceeds an explicit limit) |
--timeout-recheck <serial|none> |
Recheck parallel worker timeouts serially (serial, default) or leave unconfirmed (none, exits 3) |
--checkpoint |
Append and resume completed outcomes via checkpoint.jsonl in the work dir (reuses results only when source, selection, tools, and environment match) |
--opt-level <0..=3> |
Override optimisation level for test builds (greatly reduces probe overhead in tight loops) |
-F, --features <FEATURES> / --all-features / --no-default-features / --locked |
Forwarded to every Cargo command in the run |
Work Directory & Fixtures
| Option | Description |
|---|---|
--work-dir <DIR> |
Isolated working copy and build directory (default: <target-dir>/tmt; locked throughout execution and kept between runs for incremental rebuilds) |
--all-files |
Also copy gitignored files (still excludes .git, node_modules, and build caches) |
--git-index |
Create an independent Git index in the working copy for commands like git ls-files |
--copy-fixture <PATH> |
Copy a specific workspace-relative gitignored file/directory (e.g. sdk/node_modules; repeatable) |
--copy-fixture-exclude <PATH> |
Omit an entry from --copy-fixture (repeatable) |
--copy-output-fixture <FROM=TO> |
Stage a workspace file/directory under isolated Cargo output (e.g. tools/runner-node=debug/runner-node), protecting unmanaged files and rejecting case-only collisions |
Your source tree is never modified. In a Git repository, only tracked/unignored files are copied (symlinks to regular files are materialized; directory symlinks are followed only inside the workspace), Cargo intermediates stay inside the work directory even if
build.build-diris configured, and external path dependencies are rewritten to absolute paths.
Soundness, speed & prior work
What "guaranteed to survive" rests on
- Deterministic tests. Predictions come from one traced run; by default one survivor per gap is re-run and mismatches report
UNSTABLE(exit2). - Side-effect preservation. Probes evaluate every operand once in original order and drop temporaries where the original drops them (
fixtures/semanticstests this).a && { b; true }still evaluatesbwhenais true. - Consistent
PartialOrd. Comparisons callpartial_cmponce and derive</<=/>/>=from it. - Mathematical integer thresholds.
a >= b - 1(reported as(without overflow)) compares mathematical values; overflow and division by zero are never assumed equal. - Float precision. Float thresholds are computed in
f64(may differ in the last ULP forf32).
Why it is fast
- One instrumented build carries all probe-compatible mutants, toggled by environment variables.
- Provable input-gap survivors are computed analytically instead of tested one by one.
- Remaining mutants run only against tests whose observations changed, stopping at the first failure.
- Loop-heavy probes batch narrowing distances per thread (flushed on thread exit and every 20 ms) and skip recorder locks when observations are unchanged. Using
--opt-level 1eliminates almost all probe overhead in tight loops (measured 13× → ~1× unrecorded, 170× → 13× while recording). - Incremental working copy rewrites only changed instrumented files, and
--since/--linesnarrow work to code under review.
Compared with cargo-mutants & prior work
tests/parity.rs checks cargo tmt against stored cargo-mutants 27.1.0 mutation lists across eight fixture crates (plus any crate on request), and adds trace-driven mutations (shifted boundaries, ignored &&/|| operands, post-body bool/Option exits, deleted statements, min/max, first/last, and range ends).
The idea of generating mutants using test observations is known as test-aware mutant generation. Related lines of work include SEMu (symbolic execution to kill surviving mutants), DSpot (assertion amplification), the W-method (complete test suites for finite state machines), and Meta's ACH (LLM-generated mutants with tests that kill them). cargo tmt occupies the solver-free, AI-free corner of that space: read the trace and do interval arithmetic. Rather than comparing raw mutation scores across tools with different mutant sets, this project optimizes for catching real bugs per minute of CI time.
Formal verification
Core invariants of the planner, instrumenter, runner, checkpointing, output staging, and process cleanup are machine-checked (key artifacts under formal/ and tests/):
| Artifact | Tool | What it verifies |
|---|---|---|
formal/lean/Planner.lean |
Lean 4 | Soundness and exactness of integer survivor intervals, 3-value trace sufficiency, reachability (power-of-two products, masks, remainders), and sequence-end (first/last) separation |
formal/pict/{planner,workcopy,slice_ends,unpinned_calls}.pict |
PICT | 3-way combinatorial coverage tables replayed in Rust tests (plan, driver, e2e, witness::assertions) |
tests/properties.rs |
proptest |
Span validity, line-ending preservation, and valid Rust parsing over generated programs and this repo's own sources |
formal/tla/RepairLoop.tla |
TLC | Instrument → build → drop-failing-probe loop terminates and ships no uncompilable probe |
formal/tla/JobPool.tla & CampaignPhases.tla |
TLC | Exact-once execution, worker bounds, and provisional parallel timeout recheck ordering |
formal/tla/CampaignCheckpoint.tla |
TLC | Safe resume only on exact context/inventory match, including partial completion on Unable |
formal/tla/TraceBacklog.tla |
TLC | Per-thread observation batching never loses nearest distances |
formal/tla/WorkCopy.tla & TargetCoverage.tla |
TLC | Crash-safe working copy synchronization and source restoration before recording verdicts |
formal/tla/OutputFixture.tla & WorkLock.tla |
TLC | Unowned output preservation, ownership journaling, and cross-process work-directory locking |
formal/tla/Leftovers.tla & NextestStop.tla |
TLC | Subreaper/PID-1 orphan sweeping (is_left_candidate) never stops active sibling children and always drains leftovers; nextest group reaping before verdicts |
Limits
Scope, syntax & types
- Module discovery & targets: Follows explicit
moddeclarations and literalinclude!paths. Secondary targets and modules shared by multiple targets need--rebuildor--source-only(unbuilt files are reported as unevaluated at file granularity). i128andu128: Outside the probe runtime's integer specialization (i8..i64/isize,u8..u64/usize). Comparisons fall back to general ordering checks (<vs<=and negation without shifted boundaries), andi128/u128arithmetic, bitwise, range, andmin/maxprobes pass through unmutated. Use--source-onlyto mutatei128/u128operations directly.- Floats & non-numeric types: Float gaps are reported only while no test compares equal operands (rounding-distance thresholds after that are not reported). Non-numeric
PartialOrdtypes check<vs<=and negation only. - Compile-time & unsupported syntax: Inline
constblocks, array lengths, enum discriminants, const generics,const fn, and constant initializers require--rebuildor--source-only. Files starting with a BOM or#!line are not instrumented. Casts are not mutated. Functions returningimpl Trait(other thanimpl Iterator) cannot have synthetic body replacements. Result probes forbool/Optionrequire observable exits (omitted whenreturn,?, or an unexpanded macro could bypass them). Macro shadowing is recognized only for top-level definitions in the same file. - Ranges,
min/max, andfirst/last: Range probes apply only directly inforloops (other ranges and literal pairs like0..3need--rebuild);a..batT::MAXcannot be probed asa..=band is reported as not evaluated (handled by--rebuild).a.max(b)/a.min(b)borrowa(non-Copyby-value types likeStringare left untouched).v.first()/v.last()target slices,Vec, arrays of length ≥ 2, andBTreeSet(by-value iterators and&mutreceivers need--rebuild). - Duplicate/equivalent mutants: A body replaced by
trueand an exit replaced bytruecan be reported together on the same line. Equivalent mutants (a >= binmax(a, b), compile-time-constant operands) are not always eliminated.
Tracing, threads & determinism
- Worker thread pools (
tokio,rayon) & spawned threads: Observations on threads whose names do not match libtest test names — including shared worker pools such astokioandrayon, spawned threads, and all doc tests — cannot be attributed to one test and fall back to running the mutant against the whole test binary. Use--isolate-testswhen per-test attribution or process isolation is needed. - Thread name collisions: A user-spawned thread named identically to another test in the same binary is attributed to that test (
--auditdetects this). - Unnamed / long-lived threads: Unnamed threads and the main thread flush immediately (slower in loops). Named threads that are still running when the process exits may omit their last 20 ms of observations (re-run verification surfaces any resulting misprediction as
UNSTABLE). - Environment clearing &
fork: Subprocesses clearing environment variables (Command::env_clear()) bypass probes (use--source-only). Code running in a forked child beforeexec(pre_exec) is not traced (to avoid deadlocking on inherited runtime locks), though active mutants still apply there.
Evaluation semantics & probes
- Constant replacement & struct base evaluation: Probed constant replacements still evaluate operands/guards, and probed struct-field omission evaluates
..basetwice (--source-onlyremoves the field and evaluatesbaseonce). - Drop order &
DerefMut: Two edge cases differ from uninstrumented code: a temporary with aDropimpl inside a struct field with..basedrops before the next field, and*p += f()evaluates*pbeforef(). unused_parens& columns: Source operator replacements parenthesize operands when precedence changes (8 - (2 + 3)), which crates denyingunused_parensmay reject as non-compiling. Probes and source mutants preserve line numbers (line!()) but not column numbers (column!()).
Process cleanup & timeouts
- Leftover processes: Each test run inherits a locked file; processes still holding it after the run ends are stopped (requiring
/procon Linux orlsofelsewhere). SetTMT_LEAVE_PROCESSES=1to opt out. Daemons that close inherited FDs (e.g. Pythonsubprocessdefaults) are not tracked. - Parallel timeouts: With
--jobs N, each test binary shares cores (at least 2 test threads) and parallel timeouts are rechecked serially by default (--timeout-recheck serial). Heavy external machine load can still cause slow mutants to time out (counted as killed in probe mode, or exit3in--source-only).
Development & changelog
See CHANGELOG.md for release history.
The lists in tests/data/cargo-mutants are generated by running cargo mutants --list in a copy of each fixture.
Releasing
Update Cargo.toml, Cargo.lock, and CHANGELOG.md, push the release commit to main, and wait for CI to pass. Optionally run the Release workflow manually to verify the package. To publish, push a tag matching the package version (e.g. v0.7.0); the workflow verifies that the tagged commit is on main with a green CI run, validates the package again, and publishes to crates.io via Trusted Publishing.
License
Apache License, Version 2.0. See LICENSE.