Plan: Changed-Crate cargo-mutants as an Advisory MR Signal (#887)
Status
Not started
| Anchor | What binds here |
|---|---|
|
The opt-in wrapper this plan extends: |
|
The survivor catalogue D3 reads; its header records cargo-mutants v25.3.1. |
test-framework-hardening §D10, §D11 |
Prior art: the smoke profile and the baseline. It kept mutation testing out of CI gating (budget tightening and gate graduation were left to a future plan); this plan adds an advisory CI signal, not that gate. |
#2092 |
The existing |
ADR-080 (#1189) |
The |
Context
cargo-mutants mutates production code and re-runs the tests for each mutant; a survivor shows that no test checks that
line’s behavior, which coverage cannot show. cargo xtask mutants runs it on demand (--smoke, --full, --gated);
accepted survivors, each with a reason, are catalogued in xtask/mutants-baseline.toml. Nothing runs it in CI.
#887 asks for an advisory MR note of the survivors an MR’s own diff introduces, over only the crates it touches, in the
shapes behind past defects (authz fallback arms, day-count / FFP arithmetic, finalize-status logic: #786, #759, #782,
#785). It was parked behind #1189 because CI could not be trusted to gate. That premise does not apply to an
allow_failure: true job: the local pre-push battery is the merge gate, and CI jobs are detectors
(ADR-080 D3).
Verified facts this design builds on:
-
xtask maps no diff to crates and has no
cargo_metadata;tomlandreqwest(blocking,rustls-tls) are dependencies,proptestandwiremockdev-dependencies (xtask/Cargo.toml). -
The one existing note poster is
triage:stale(tools/triage/stale.sh, curl with$GITLAB_TOKEN); D4 posts from xtask with its own token. -
cargo-mutants 25.3.1 (the baseline’s version) has
--in-diff <file>(only mutants on changed lines, applied after--package), a repeatable--package,--output <dir>(writes<dir>/mutants.out/),--list,--shard k/nand--baseline run|skip.missed.txtholds onepath:line:col: descriptionline per missed mutant. Exit codes: 0 all caught, 2 missed, 3 timeouts, 1 usage, 4 baseline tests fail, 5 diff does not match the tree, 6 invalid diff, 70 internal..cargo/mutants.tomlsetsminimum_test_timeout = 300.
Scope
In:
-
cargo xtask mutants --changed-crates [--base <rev>] [--post-mr-note] [--reconcile-only]: resolve the eligible changed packages (D1), run one budgeted cargo-mutants invocation over them (D2), classify the survivors against the baseline (D3), print the note and, with--post-mr-note, reconcile it on the MR (D4). -
Two advisory jobs on MR pipelines (D5):
ci-mutantswhen the MR changes eligible Rust,ci-mutants-reconcileon every other MR update.
Out:
-
A blocking mutants gate, now or later: both jobs are
allow_failure: truepermanently; no project merge setting changes. -
Push, main, schedule or tag pipelines.
-
Changes to
.cargo/mutants.toml,SMOKE_PACKAGES,GATED_DEFAULT_PACKAGES, the baseline’s format, or the--smoke,--fulland--gatedpaths (#2092 owns the multi-package fix there; it can reuse D2’s exit classifier). -
A devstack (gated) changed-crate run. The devstack runs only in
ci-integration(ADR-080).
Design
New code goes in two sibling modules (the rules_afcars.rs prefix convention): xtask/src/cmd/mutants_changed.rs (D1 to
D3 and note rendering) and xtask/src/cmd/mutants_note.rs (D4 posting). run dispatches --changed-crates inside its
existing tree_status / residue_check envelope, and posting happens only after the residue scan has passed.
D1. Changed-package resolution
-
Base.
--base <rev>defaults toorigin/main; CI passes$CI_MERGE_REQUEST_DIFF_BASE_SHA. xtask resolvesgit merge-base <rev> HEADonce and bails if that fails. It never falls back to a two-dot diff:<rev>..HEADagainst a movedorigin/maincounts main’s own changes as the MR’s. -
Names.
git diff --no-color --name-only --diff-filter=d <merge-base> — '*.rs'diffs against the working tree; deleted files are excluded because they have nothing to mutate. -
Untracked files.
git ls-files --others --exclude-standard — '*.rs'under an eligible member is an error naming the files ("stage or remove them"): cargo-mutants would mutate an untracked module the patch cannot describe. A CI checkout has none. -
Patch.
git diff --no-color --no-ext-diff --no-textconv --src-prefix=a/ --dst-prefix=b/ <merge-base> — '*.rs'goes totarget/mutants-changed/in-diff.patch; the flags override local git config (color, external diff and textconv drivers,diff.noprefix). Both diffs start at the merge-base and end at the working tree, so the patch’s new side is exactly the tree cargo-mutants mutates (a mismatch is exit 5). In CI the tree isHEAD. -
Resolve each path. Parse the nearest ancestor
Cargo.tomlwithtoml. Drop the path if that manifest has no[package](the root virtual manifest) or its directory is not in the root[workspace].members(today: the standalonecrates/craig-partner-caps/fuzzworkspace). Amembersentry containing*is an error: the list is literal. Otherwise the path yieldsCrateMember { package, dir }:packageis[package].name(plugins/examplegivescraig-plugin-example),diris repo-relative (the baseline’scrateformat). Deduplicated and sorted. -
Eligibility. Only members under
crates/,services/orplugins/; the allowlist leaves a new top-level directory ineligible.xtaskis the harness running the job (an in-place run would mutate the running tool);tools/*is dev and test tooling, and #887’s defect classes are shipped code.
D2. One budgeted invocation
In order: crate cap, version, mutant cap, run. Each skip decision is a pure function, and a skip exits 0.
-
Crate cap. No eligible crate is
Skipped(NoEligibleCrate); more thanMAX_CRATES = 5(the size ofSMOKE_PACKAGES) isSkipped(TooManyCrates(n)). Neither spawns cargo-mutants. With--reconcile-onlyany eligible crate is an error: the job rules and D1 disagree. -
Version.
CARGO_MUTANTS_VERSION = "25.3.1"produced the baseline; any othercargo mutants --versionis refused: mutant names are version-specific. -
Mutant cap.
cargo mutants --list --package <p>… --in-diff <patch>counts without building. 0 isSkipped(NoMutants); more thanMAX_MUTANTS = 150isSkipped(TooManyMutants(n)). The baseline header’s whole-crate runs took 3–9 s per mutant. -
Run.
changed_run_argvreturnsmutants --in-place --package <p1> --package <p2>… --in-diff <patch> --output target/mutants-changed: ONE invocation, one baseline build, one report nomutants.outrotation can drop. Likemutants_argv: no--jobs(#1422), no--shard, no trailing--. -
Budget. xtask waits at most
RUN_BUDGET = 80 min(the job’s 2 h less setup and posting). At the deadline it terminates cargo-mutants' process group; the result isIncomplete { tested, total }, wheretotalis the listed count andtestedthe completed outcomes: cargo-mutants appends each outcome tomissed.txt,caught.txt,timeout.txtandunviable.txtas it lands, so the completed ones are parsed and reported. Before the flag ships, the implementation checks that append behaviour on an interrupted local 25.3.1 run; if it does not hold, the run becomes sequential--shard k/ninvocations of at most 6 mutants (worst case 30 min each at the 300 s floor), each with its own--outputand shards after the first with--baseline skip, started only while under budget. -
Exit.
classify_exit(code: Option<i32>): 0, 2 and 3 are run results; a deadline termination isIncomplete; 1, 4, 5, 6, 70, any other code or another signal is a failure naming the code and its upstream meaning.
D3. Survivors: new or ambiguous
-
Source.
target/mutants-changed/mutants.out/missed.txt, parsed byparse_missed_lineintoMissedMutant { path, line, col, kind }. A malformed line is an error, not an empty result.timeout.txtis counted. -
Key.
SurvivorKey { crate_dir, file, kind }: the path split at the resolved member whosediris a component-wise prefix (crates/craig-store/src/store.rsgivescrates/craig-store+src/store.rs); a path under no member is an error. Baseline entries are read into a typedBaseline { missed: Vec<BaselineEntry> }(serderename ofcrate), theirlineignored: the lines have drifted since 2026-08-14 (store.rs:77is no longerStore::is_local_backend), and the key is not unique (replace > with >= in OidcServiceToken::currentappears three times). -
Classify.
classify(run: &[(SurvivorKey, u32)], baseline: &[SurvivorKey]) → Classified { new, ambiguous }: per key,new = run − baselinefloored at 0 (saturating_sub, commented: the floor is the specified semantics) andambiguous = min(run, baseline).--in-diffsees only changed lines while the baseline counts the whole crate, so a run survivor whose key is baselined may be that entry or a new one; it is reported as ambiguous, never absorbed. Each entry carries its run lines for display. Clean means the run found no surviving mutant at all.
D4. The MR note
-
Render.
render_note(&NoteState, head_sha); statesSurvivors { new, ambiguous, timeouts },Incomplete { new, ambiguous, tested, total },Clean { timeouts }("No surviving mutants on the changed lines at <sha>." plus "(N timed out)" when N > 0),Skipped(reason)("Not run at <sha>: <reason>."). Every state isrender_noteoutput with the marker<!-- ci-mutants-signal -->on line 1, then the head SHA (git rev-parse HEAD, first 8 characters) and the packages. New and ambiguous survivors are listed separately (crate_dir/file, kind, count, lines). Two fixed caveats: (a) crate-local context, where#[ignore = "requires devstack"]suites do not run while the baseline’s craig-mq and craig-cases entries come from gated runs; (b) catch variance (#1472): a survivor is a gap to triage; kill it with a test or catalogue it with areason. The note is always printed to the job log. -
Entry point.
--post-mr-note(requires--changed-crates) callsmutants_note::post_mr_note(&NoteTarget, &NoteState, &str): one process owns the result; opt-in posting keeps local runs token-free. -
Target. From
CI_API_V4_URL,CI_PROJECT_ID,CI_MERGE_REQUEST_IID(a missing one is an error); the token isCRAIG_MUTANTS_NOTE_TOKEN. Unset or empty (a fork MR, or not yet provisioned): print "note not posted", exit 0. -
Reconcile.
GET /usergives the bot’s id;GET /projects/:id/merge_requests/:iid/notes?per_page=100, paged byx-next-page, finds the first note the bot wrote that starts with the marker.SurvivorsandIncompleteupdate it (PUTonnotes/:note_id) or create one (POST);CleanandSkippedonly update an existing marked note, so a clean MR gets none. -
Freshness (best effort). Before any write xtask reads
GET /projects/:id/merge_requests/:iidand skips the write ("superseded") when itsshais not the run’s. GitLab has no conditional note write, so a push between the check and the write can still land an older run’s note;interruptible: truelets GitLab cancel the older run, and the newer run’s own reconcile overwrites it. Every note names its SHA, so a stale note is visible as such. -
Transport. xtask’s blocking
reqwest(rustls), 30 s timeout,PRIVATE-TOKENheader; noglab, no shell script (container-ops). ANoteTokennewtype with a redactingDebugholds the token; errors name only endpoint and status. -
Token posture.
CRAIG_MUTANTS_NOTE_TOKENis a project access token (role Reporter, scopeapi, expiry at most one year out) in its own masked CI/CD variable, neverGITLAB_TOKEN. It is not protected: protected variables do not reach pipelines on the ordinary unprotected feature branches MRs come from, so anyone who can push a branch can read it, as can a fork-MR pipeline a maintainer runs in the parent project. Least privilege is the control. -
Exit status. When the run finished or hit its budget and the note step succeeded, xtask exits 0 whatever the survivor count; the note is the signal. A failed (yellow) job means the tool, the runner or the job timeout broke the run, and the log names which.
D5. The jobs
.ci-mutants-changes: &ci_mutants_changes
- "crates/**/*.rs"
- "services/**/*.rs"
- "plugins/**/*.rs"
- ".gitlab-ci.yml"
ci-mutants:
stage: scan
tags:
- cma-runner-craig
timeout: 2h
interruptible: true
variables:
GIT_DEPTH: "0"
before_script:
- !reference [.cma-runner-bootstrap, before_script]
- cargo install cargo-nextest --locked
- cargo install cargo-mutants --version =25.3.1 --locked
script:
- cargo xtask mutants --changed-crates --base "$CI_MERGE_REQUEST_DIFF_BASE_SHA" --post-mr-note
artifacts:
paths:
- target/mutants-changed/
when: always
expire_in: 14 days
allow_failure: true
rules:
- if: $CI_MERGE_REQUEST_IID
changes: *ci_mutants_changes
ci-mutants-reconcile:
stage: scan
image: ${RUST_IMAGE}
tags:
- dhs-aws-autoscaler-docker.medium
interruptible: true
variables:
GIT_DEPTH: "0"
before_script:
- apk add --no-cache curl git openssl
script:
- cargo xtask mutants --changed-crates --reconcile-only --base "$CI_MERGE_REQUEST_DIFF_BASE_SHA" --post-mr-note
allow_failure: true
rules:
- if: $CI_MERGE_REQUEST_IID
changes: *ci_mutants_changes
when: never
- if: $CI_MERGE_REQUEST_IID
-
Runner.
ci-mutantsis asci-tests: it builds and tests the packages it touches, the link-step disk class that movedci-teststocma-runner-craig(#1645, known issues). That runner ignoresimage:. No devstack. -
Reconcile. An MR pipeline’s
changes:compares the MR’s whole diff, so when a push removes the MR’s last eligible change,ci-mutantsstops matching andci-mutants-reconcile(the exact complement) runs, resolves no eligible crate and updates an existing note to "Not run". It builds only xtask, on the concurrent pool, asdocs-content-lintsdoes. -
Installs. Both surface errors (no
|| true); nextest is.cargo/mutants.toml’s `test_tool. -
History.
GIT_DEPTH: "0": the merge-base needs the base commit; new projects default to a depth of 20. -
Timeout. 2h, as
ci-integrationon this runner: setup (bootstrap, two cargo installs, the xtask and baseline builds) plus the 80 minRUN_BUDGETplus posting. The report is always an artifact. -
Shape pin. A text-matching unit test pins both jobs, the house style of
policy_drift_ci_job_is_schedule_discriminated_and_advisoryand theci-integrationjob-shape test.
Test matrix
Unit tests live in the two new modules; resolver tests build tempfile fixture trees under a root virtual manifest; note
tests run against wiremock (the rules_promote.rs pattern).
Erratum (2026-10-26, #2705): the paragraph above no longer requires each test to carry the listed // @axis: tag, and
§ Verification no longer runs the axis-coverage lint; the tags and that gate are retired. The Axis column below names each
test’s intended axis only.
| Test | Axis | Asserts |
|---|---|---|
|
happy |
|
|
happy |
|
|
sad |
the nearest manifest is the virtual root, so the path is dropped |
|
evil |
the |
|
sad |
|
|
sad |
a |
|
evil |
an untracked |
|
evil |
both argvs carry the merge-base SHA, never |
|
sad |
clap refuses it with |
|
sad |
an eligible crate under |
|
happy |
one |
|
sad |
0, 2, 3 are |
|
fault |
a child outliving a 1 s budget is terminated; a partial
|
|
sad |
|
|
sad |
an empty set gives |
|
evil |
6 crates give |
|
evil |
0 gives |
|
happy |
a formatted |
|
evil |
arbitrary input returns |
|
happy |
every baseline entry deserializes; each |
|
happy |
the invariants below |
|
evil |
run 1, baseline 3 for one key: ambiguous 1, new
0, and the state is |
|
sad |
zero run survivors is |
|
happy |
marker on line 1; the SHA’s first 8 chars; both caveats |
|
happy |
exactly one |
|
replay |
|
|
replay |
MR sha differs from head: zero writes |
|
sad |
no marked note: no write; a marked note: |
|
evil |
a human’s note quoting the marker is left alone |
|
sad |
an unset or empty token gives |
|
fault |
a 401 or 500 is an error naming endpoint and status; no token text |
|
evil |
both |
classification_partitions_every_survivor generates a run of 0–40 (key, line) pairs and a baseline of 0–40 keys from a
four-key alphabet, so keys collide. The invariants:
-
Partition. For every key,
new + ambiguousequals the run’s count; no run survivor is dropped. -
Count.
newis the run’s count minus the baseline’s, or 0 if negative;ambiguousis the smaller of the two. -
Clean. The state is
Cleanexactly when the run is empty. -
Line independence. Renumbering every run line leaves the
(key, new, ambiguous)triples unchanged.
Verification
-
The implementation MR’s pre-push battery (
cargo xtask validatethrough.githooks/pre-push) is the sole merge gate. It runs every test above. Neither job ever gates a merge. -
Before
--changed-cratesships: interrupt a local 25.3.1--in-diffrun mid-way and confirm the per-outcome files hold the finished outcomes (D2 Budget); record the result on #887. -
Live acceptance, once
CRAIG_MUTANTS_NOTE_TOKENis provisioned, on a throwaway MR from the implementation branch (never merged):-
add one unasserted comparison in
crates/craig-common:ci-mutantsposts one marked note naming that mutant as new; -
push a test that kills it, keeping the comparison: the same note becomes "No surviving mutants on the changed lines";
-
separately, revert the comparison while a docs change stays:
ci-mutants-reconcileruns and the note becomes "Not run at <sha>: no eligible crate". Close the MR and record the three transitions on #887.
-
-
Doc updates the implementation owes, in the same MR:
-
testing-reference: § Mutation testing, a changed-crate row (flags, caps, the budget, the crate-local caveat, token provisioning) and the exact pin in the Install row and the xtask command table; § .gitlab-ci.yml, both jobs under Stage 1: scan; § Runner Tags,
ci-mutantsin thecma-runner-craiglist; -
local-dev § CI vs Local Differences: a mutation-testing row;
-
CHANGELOG.adoc== Unreleased=== Added: the flags, both jobs, the token variable and its provisioning ops note.
-
Rollout + risks
-
One implementation MR (effort M, weight 3),
Closes #887. Without the token both jobs print the note and post nothing; the maintainer then provisions the token (D4) and renews it on expiry. -
Gated-context false positives. A craig-mq or craig-cases mutant only a devstack suite kills shows up (caveat a).
-
Catch variance (#1472). Catching on weakly covered lines is nondeterministic: a survivor is a candidate.
-
Ambiguity noise. A change on a line near a baselined survivor lists it as ambiguous until the baseline is refreshed.
-
cargo-mutants version bump. It regenerates the baseline in the same MR; the const, the CI pin and the shape test make the bump explicit.
-
Test-only changes.
--in-diffsees only changed code lines: a diff that only weakens tests yields no mutants. -
Runner offline. With
cma-runner-craigofflineci-mutantsdoes not run. The pre-push hook is unaffected.
Review log
| Round | Vendor | Resolved model | Verdict |
|---|---|---|---|
1 |
Anthropic — the landing review of the teammate’s plan MR (plan checked against main, upstream docs and the rules) |
Claude Opus 5.5 |
no-ship (blocker B1) — B1, M1–M4, the minor factual claims, the plan-lifecycle / testing-discipline / preflight items and the nits folded |
verify |
Anthropic — one fresh contextless verifier over the folds |
Claude Opus 5.5 |
ship — no blocker; 9 fold defects fixed |
2 |
maintainer-run (2026-09-29) |
as reported |
no-ship — 8 findings folded: the reconcile job for reverts, the three
acceptance transitions, ambiguous baselined keys, best-effort freshness, untracked files, the run budget and report
artifact, |