Plan: Changed-Crate cargo-mutants as an Advisory MR Signal (#887)

Status

Not started

Anchor What binds here

xtask/src/cmd/mutants.rs

The opt-in wrapper this plan extends: MutantsArgs, run and its residue-scan envelope.

xtask/mutants-baseline.toml

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 --smoke / --gated multi-package runs stop at the first survivor and keep only the last report. Tracked there, not fixed here.

ADR-080 (#1189)

The ci-integration detector on cma-runner-craig whose advisory shape and job-shape test ci-mutants follows.

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; toml and reqwest (blocking, rustls-tls) are dependencies, proptest and wiremock dev-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/n and --baseline run|skip. missed.txt holds one path:line:col: description line 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.toml sets minimum_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-mutants when the MR changes eligible Rust, ci-mutants-reconcile on every other MR update.

Out:

  • A blocking mutants gate, now or later: both jobs are allow_failure: true permanently; 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, --full and --gated paths (#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

  1. Base. --base <rev> defaults to origin/main; CI passes $CI_MERGE_REQUEST_DIFF_BASE_SHA. xtask resolves git merge-base <rev> HEAD once and bails if that fails. It never falls back to a two-dot diff: <rev>..HEAD against a moved origin/main counts main’s own changes as the MR’s.

  2. 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.

  3. 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.

  4. Patch. git diff --no-color --no-ext-diff --no-textconv --src-prefix=a/ --dst-prefix=b/ <merge-base> — '*.rs' goes to target/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 is HEAD.

  5. Resolve each path. Parse the nearest ancestor Cargo.toml with toml. 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 standalone crates/craig-partner-caps/fuzz workspace). A members entry containing * is an error: the list is literal. Otherwise the path yields CrateMember { package, dir }: package is [package].name (plugins/example gives craig-plugin-example), dir is repo-relative (the baseline’s crate format). Deduplicated and sorted.

  6. Eligibility. Only members under crates/, services/ or plugins/; the allowlist leaves a new top-level directory ineligible. xtask is 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.

  1. Crate cap. No eligible crate is Skipped(NoEligibleCrate); more than MAX_CRATES = 5 (the size of SMOKE_PACKAGES) is Skipped(TooManyCrates(n)). Neither spawns cargo-mutants. With --reconcile-only any eligible crate is an error: the job rules and D1 disagree.

  2. Version. CARGO_MUTANTS_VERSION = "25.3.1" produced the baseline; any other cargo mutants --version is refused: mutant names are version-specific.

  3. Mutant cap. cargo mutants --list --package <p>… --in-diff <patch> counts without building. 0 is Skipped(NoMutants); more than MAX_MUTANTS = 150 is Skipped(TooManyMutants(n)). The baseline header’s whole-crate runs took 3–9 s per mutant.

  4. Run. changed_run_argv returns mutants --in-place --package <p1> --package <p2>… --in-diff <patch> --output target/mutants-changed: ONE invocation, one baseline build, one report no mutants.out rotation can drop. Like mutants_argv: no --jobs (#1422), no --shard, no trailing --.

  5. 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 is Incomplete { tested, total }, where total is the listed count and tested the completed outcomes: cargo-mutants appends each outcome to missed.txt, caught.txt, timeout.txt and unviable.txt as 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/n invocations of at most 6 mutants (worst case 30 min each at the 300 s floor), each with its own --output and shards after the first with --baseline skip, started only while under budget.

  6. Exit. classify_exit(code: Option<i32>): 0, 2 and 3 are run results; a deadline termination is Incomplete; 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

  1. Source. target/mutants-changed/mutants.out/missed.txt, parsed by parse_missed_line into MissedMutant { path, line, col, kind }. A malformed line is an error, not an empty result. timeout.txt is counted.

  2. Key. SurvivorKey { crate_dir, file, kind }: the path split at the resolved member whose dir is a component-wise prefix (crates/craig-store/src/store.rs gives crates/craig-store + src/store.rs); a path under no member is an error. Baseline entries are read into a typed Baseline { missed: Vec<BaselineEntry> } (serde rename of crate), their line ignored: the lines have drifted since 2026-08-14 (store.rs:77 is no longer Store::is_local_backend), and the key is not unique (replace > with >= in OidcServiceToken::current appears three times).

  3. Classify. classify(run: &[(SurvivorKey, u32)], baseline: &[SurvivorKey]) → Classified { new, ambiguous }: per key, new = run − baseline floored at 0 (saturating_sub, commented: the floor is the specified semantics) and ambiguous = min(run, baseline). --in-diff sees 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

  1. Render. render_note(&NoteState, head_sha); states Survivors { 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 is render_note output 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 a reason. The note is always printed to the job log.

  2. Entry point. --post-mr-note (requires --changed-crates) calls mutants_note::post_mr_note(&NoteTarget, &NoteState, &str): one process owns the result; opt-in posting keeps local runs token-free.

  3. Target. From CI_API_V4_URL, CI_PROJECT_ID, CI_MERGE_REQUEST_IID (a missing one is an error); the token is CRAIG_MUTANTS_NOTE_TOKEN. Unset or empty (a fork MR, or not yet provisioned): print "note not posted", exit 0.

  4. Reconcile. GET /user gives the bot’s id; GET /projects/:id/merge_requests/:iid/notes?per_page=100, paged by x-next-page, finds the first note the bot wrote that starts with the marker. Survivors and Incomplete update it (PUT on notes/:note_id) or create one (POST); Clean and Skipped only update an existing marked note, so a clean MR gets none.

  5. Freshness (best effort). Before any write xtask reads GET /projects/:id/merge_requests/:iid and skips the write ("superseded") when its sha is 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: true lets 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.

  6. Transport. xtask’s blocking reqwest (rustls), 30 s timeout, PRIVATE-TOKEN header; no glab, no shell script (container-ops). A NoteToken newtype with a redacting Debug holds the token; errors name only endpoint and status.

  7. Token posture. CRAIG_MUTANTS_NOTE_TOKEN is a project access token (role Reporter, scope api, expiry at most one year out) in its own masked CI/CD variable, never GITLAB_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.

  8. 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-mutants is as ci-tests: it builds and tests the packages it touches, the link-step disk class that moved ci-tests to cma-runner-craig (#1645, known issues). That runner ignores image:. 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-mutants stops matching and ci-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, as docs-content-lints does.

  • 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-integration on this runner: setup (bootstrap, two cargo installs, the xtask and baseline builds) plus the 80 min RUN_BUDGET plus 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_advisory and the ci-integration job-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

a_services_member_resolves_to_its_own_package

happy

services/x/src/a.rs gives (x, services/x); two files in one member resolve once; output sorted

a_plugin_resolves_by_manifest_name_not_directory

happy

plugins/example/src/lib.rs gives craig-plugin-example

a_root_level_path_resolves_to_nothing

sad

the nearest manifest is the virtual root, so the path is dropped

a_standalone_nested_workspace_is_dropped

evil

the crates/craig-partner-caps/fuzz shape (not a member) is dropped

tooling_members_are_ineligible

sad

xtask/src/cmd/mutants.rs, tools/craig-seed/src/lib.rs are dropped

a_glob_member_entry_is_refused

sad

a members entry containing * is an error

untracked_eligible_rust_is_refused

evil

an untracked crates/x/src/new.rs is an error naming it; an untracked tools/… file is not

both_git_diffs_start_at_the_merge_base

evil

both argvs carry the merge-base SHA, never .., and --no-color; the patch argv also --no-ext-diff --no-textconv --src-prefix=a/ --dst-prefix=b/

changed_crates_conflicts_with_every_other_scope

sad

clap refuses it with --package, --shard, --full, --gated, --smoke; refuses --base, --post-mr-note, --reconcile-only without it

reconcile_only_refuses_eligible_crates

sad

an eligible crate under --reconcile-only is an error; none is Skipped

the_run_is_one_invocation_over_every_package

happy

one mutants --in-place, each --package, --in-diff, --output; no --jobs, --shard or --

only_exit_codes_0_2_3_are_run_results

sad

0, 2, 3 are Ok; 1, 4, 5, 6, 70, None are errors naming the code

a_deadline_termination_reports_incomplete

fault

a child outliving a 1 s budget is terminated; a partial missed.txt / caught.txt fixture yields Incomplete with its outcomes and tested

a_foreign_cargo_mutants_version_is_refused

sad

cargo-mutants 25.3.1 passes; 25.3.2, 26.0.0, garbage fail

no_eligible_crate_skips_before_any_spawn

sad

an empty set gives Skipped(NoEligibleCrate)

more_than_five_crates_skips_before_any_spawn

evil

6 crates give Skipped(TooManyCrates(6)); 5 run

a_mutant_count_outside_the_cap_skips

evil

0 gives NoMutants, 151 gives TooManyMutants; 1 and 150 run

missed_lines_round_trip (proptest)

happy

a formatted path:line:col: kind parses back to the same four fields

the_missed_parser_never_panics (proptest)

evil

arbitrary input returns Ok or Err, never a panic

the_committed_baseline_parses_into_member_keys

happy

every baseline entry deserializes; each crate is a member dir

classification_partitions_every_survivor (proptest)

happy

the invariants below

a_fourth_occurrence_of_a_thrice_baselined_key_is_ambiguous

evil

run 1, baseline 3 for one key: ambiguous 1, new 0, and the state is Survivors, never Clean

clean_requires_no_run_survivor

sad

zero run survivors is Clean; one baselined-key survivor is not

the_note_starts_with_the_marker_and_names_the_sha

happy

marker on line 1; the SHA’s first 8 chars; both caveats

survivors_create_a_note_when_none_is_marked

happy

exactly one POST on notes

a_second_run_updates_the_marked_note

replay

PUT to the marked note’s id, body starting with the marker; no POST

a_superseded_run_does_not_write

replay

MR sha differs from head: zero writes

clean_and_skipped_never_create_a_note

sad

no marked note: no write; a marked note: PUT starting with the marker

only_the_bots_own_marked_note_is_updated

evil

a human’s note quoting the marker is left alone

an_absent_token_skips_posting_successfully

sad

an unset or empty token gives Ok and zero requests; a missing CI_MERGE_REQUEST_IID is an error

a_notes_api_failure_fails_the_command

fault

a 401 or 500 is an error naming endpoint and status; no token text

ci_mutants_jobs_are_complementary_advisory_detectors

evil

both allow_failure: true (never false); both use the *ci_mutants_changes anchor, the reconcile job under when: never then the bare MR rule; ci-mutants on cma-runner-craig with the bootstrap and --version = + CARGO_MUTANTS_VERSION; the reconcile job passes --reconcile-only and installs no cargo-mutants; neither names GITLAB_TOKEN

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 + ambiguous equals the run’s count; no run survivor is dropped.

  • Count. new is the run’s count minus the baseline’s, or 0 if negative; ambiguous is the smaller of the two.

  • Clean. The state is Clean exactly 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 validate through .githooks/pre-push) is the sole merge gate. It runs every test above. Neither job ever gates a merge.

  • Before --changed-crates ships: interrupt a local 25.3.1 --in-diff run 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_TOKEN is provisioned, on a throwaway MR from the implementation branch (never merged):

    • add one unasserted comparison in crates/craig-common: ci-mutants posts 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-reconcile runs 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-mutants in the cma-runner-craig list;

    • 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-diff sees only changed code lines: a diff that only weakens tests yields no mutants.

  • Runner offline. With cma-runner-craig offline ci-mutants does 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, --no-textconv, the protected-variable wording

Edit this page · latest