Skip to main content

fallow_api/mutation/
mod.rs

1//! The dynamic half of mutation testing: the runner protocol, the embedded
2//! companion, the transport, the scheduler and the result model.
3//!
4//! The static half (selection, the test map, pruning, ranking and the
5//! instrumented code) is `fallow_engine::mutation`. The entry points are
6//! [`crate::run_mutation`] and [`crate::plan_mutation`].
7
8pub(crate) mod companion;
9pub(crate) mod companion_temp;
10pub(crate) mod discovery;
11pub(crate) mod journal;
12pub(crate) mod kill_matrix;
13pub(crate) mod last_report;
14pub(crate) mod manifest;
15pub(crate) mod node_args;
16pub(crate) mod protocol;
17pub(crate) mod recorded_args;
18pub(crate) mod replay;
19pub(crate) mod report;
20pub(crate) mod result_cache;
21pub(crate) mod run_dir;
22pub(crate) mod runner_select;
23pub(crate) mod runner_version;
24pub(crate) mod scheduler;
25pub(crate) mod transport;
26pub(crate) mod typecheck;
27pub(crate) mod verdicts;
28pub(crate) mod worktree;
29
30/// The model runs link `node_modules` with a Unix symlink.
31#[cfg(all(test, unix))]
32mod cache_model;
33#[cfg(test)]
34#[expect(clippy::unwrap_used, reason = "tests unwrap to keep assertions short")]
35mod e2e_tests;
36
37use std::path::{Path, PathBuf};
38use std::time::Duration;
39
40pub use fallow_engine::mutation::Operator;
41pub use last_report::{
42    MutationWitnessStore, last_mutation_report_path, mutation_witness_store,
43    remove_finished_mutation_journal, save_last_mutation_report,
44};
45pub use report::baseline_blocked_run_error;
46pub use scheduler::control::split_control_run_failure;
47pub use verdicts::{MAX_VERDICT_INPUT_BYTES, apply_mutation_verdicts, validate_mutation_verdicts};
48
49use crate::AnalysisOptions;
50
51/// Writes `*` to `<cache>/.gitignore` when the cache has no ignore file, so
52/// that the run directory and the saved report never show in `git status`.
53pub(crate) fn ignore_cache_dir(cache_dir: &Path) -> std::io::Result<()> {
54    std::fs::create_dir_all(cache_dir)?;
55    let ignore = cache_dir.join(".gitignore");
56    if !ignore.exists() {
57        std::fs::write(ignore, "*\n")?;
58    }
59    Ok(())
60}
61
62/// The code that a mutation run mutates.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum MutationRunScope {
65    /// The added lines against a base ref. `None` detects the base ref the
66    /// same way as `audit`. An explicit `analysis.diff_file` wins over the
67    /// base ref.
68    Changed {
69        /// The base ref.
70        base: Option<String>,
71    },
72    /// Each source file of the project.
73    All,
74    /// The files at these paths, or below these directories. A relative
75    /// path is relative to the project root.
76    Paths(Vec<PathBuf>),
77}
78
79impl Default for MutationRunScope {
80    fn default() -> Self {
81        Self::Changed { base: None }
82    }
83}
84
85/// How a run records the arguments of the changed exported functions in its
86/// dry run. The values stay in the gitignored cache directory.
87#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
88#[serde(rename_all = "snake_case")]
89pub enum RecordArgsMode {
90    /// No recording.
91    #[default]
92    Off,
93    /// Keep the types of the arguments only.
94    Shapes,
95    /// Keep the argument values, after the redaction of secrets, so that a
96    /// replay can use them.
97    Values,
98}
99
100/// Options of [`crate::replay_mutation`]: one export called on the original
101/// and on one mutant.
102#[derive(Debug, Clone, Default)]
103pub struct MutationReplayOptions {
104    /// Shared project, config and cache options.
105    pub analysis: AnalysisOptions,
106    /// The root-relative path of the file of the mutant, with forward
107    /// slashes.
108    pub file: String,
109    /// The id of the mutant.
110    pub mutant_id: String,
111    /// The original byte span of the mutant. Two mutants can share an id
112    /// in runs of other scopes, so the span selects the mutant.
113    pub span: (u32, u32),
114    /// The operator of the mutant, which finds the mutant faster and also
115    /// for an opt-in operator. `None` tries each operator.
116    pub operator: Option<Operator>,
117    /// The export to call. `None` calls the export whose declaration holds
118    /// the function of the mutant.
119    pub export: Option<String>,
120    /// The arguments of each call, in the replay encoding. `None` replays
121    /// the inputs that a `--record-args values` run recorded for the
122    /// export, up to the first witness.
123    pub args: Option<Vec<serde_json::Value>>,
124    /// The JavaScript runtime, as for a run.
125    pub runtime: Option<PathBuf>,
126    /// The config file of the test runner, as for a run.
127    pub runner_config: Option<PathBuf>,
128    /// The selected Vitest projects, as for a run.
129    pub runner_projects: Vec<String>,
130    /// The time limit of one call, at most 10 minutes. `None` uses 5
131    /// seconds.
132    pub call_timeout: Option<Duration>,
133    /// The timeout of the companion `init`. `None` uses 120 seconds.
134    pub runner_timeout: Option<Duration>,
135}
136
137/// A phase event of a mutation run, for a caller that shows progress.
138///
139/// [`crate::run_mutation_with_progress`] sends the events in run order. A
140/// run with no covered mutant and no test file skips the runner phases.
141#[derive(Debug, Clone, Copy, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum MutationProgress {
144    /// The plan is ready. The runner setup starts: the runtime, the
145    /// companion install and the runner start.
146    Setup {
147        /// The planned mutants.
148        mutants: usize,
149    },
150    /// The baseline run starts: the test files run with no active mutant.
151    Baseline {
152        /// The test files of the baseline run.
153        test_files: usize,
154    },
155    /// The mutant runs. The first event has `done` 0, and each finished
156    /// mutant sends one event.
157    Mutants {
158        /// The mutants that finished.
159        done: usize,
160        /// The mutants that this phase runs. A cached result is not in it.
161        total: usize,
162    },
163    /// The retries of survivors and timeouts. The first event has `done` 0.
164    Retries {
165        /// The retries that finished.
166        done: usize,
167        /// The retries that this phase runs.
168        total: usize,
169    },
170    /// The tests stopped. The worktree check, the survivor type check and
171    /// the report start.
172    Finalize,
173}
174
175/// Receives the [`MutationProgress`] events of a run. The scheduler sends
176/// the mutant events from its worker threads.
177pub type MutationProgressSink<'a> = &'a (dyn Fn(MutationProgress) + Sync);
178
179/// Options of [`crate::run_mutation`] and [`crate::plan_mutation`].
180#[derive(Debug, Clone, Default)]
181pub struct MutationRunOptions {
182    /// Shared project, config and cache options.
183    pub analysis: AnalysisOptions,
184    /// The code to mutate.
185    pub scope: MutationRunScope,
186    /// The operators to use. `None` uses the default set
187    /// (`Operator::DEFAULT`).
188    pub operators: Option<Vec<Operator>>,
189    /// Keep mutants near a file system, process, network or database sink.
190    /// Only an explicit caller option can set this, never project config,
191    /// because the run has no sandbox copy.
192    pub allow_side_effects: bool,
193    /// Execute all covering tests and retain complete killing test sets.
194    pub kill_matrix: bool,
195    /// The `--kill-matrix-for` targets: test files or runner test ids. Each
196    /// mutant that a target test covers runs its target tests without bail.
197    /// After a target kill, its other covering tests run with bail. A mutant
198    /// that no target kills is `not_killed_by_target`, unless
199    /// `kill_matrix_full` is set. The other mutants are `pruned`. Exclusive
200    /// with `kill_matrix`.
201    pub kill_matrix_targets: Vec<String>,
202    /// Run the other covering tests of each target mutant also when no target
203    /// kills it, and retry each survivor (`--kill-matrix-full`). Each mutant
204    /// then gets a final status. Needs `kill_matrix_targets`.
205    pub kill_matrix_full: bool,
206    /// The maximum number of covered mutants to run, in rank order. A
207    /// mutant that no dry-run test covers is `no_coverage` and does not
208    /// count. The others become `pending`.
209    pub max_mutants: Option<usize>,
210    /// The maximum number of mutants on one source line, chosen at plan time
211    /// in a fixed operator order. The others become `pending` with the reason
212    /// `sampled-out`, and the run never executes them. `None` uses the
213    /// `mutation.mutantsPerLine` config key, else keeps each mutant. A run of
214    /// `mutant_ids` never samples.
215    pub mutants_per_line: Option<usize>,
216    /// Widen each changed line of the changed-code scope to the whole
217    /// function that holds it. The other scopes ignore it. `false` still
218    /// uses the `mutation.functionScope` config key.
219    pub function_scope: bool,
220    /// Run in a dirty git worktree, or outside a git worktree. The run still
221    /// compares the worktree after the run.
222    pub allow_dirty: bool,
223    /// The JavaScript runtime. `None` uses the runtime of the runner from
224    /// `PATH`: `node` for `node:test`, `bun` for `bun test`, and `node`,
225    /// then `bun`, for Vitest.
226    pub runtime: Option<PathBuf>,
227    /// The number of companion processes. `None` uses half the logical
228    /// cores.
229    pub concurrency: Option<usize>,
230    /// The time budget of the run. Mutants that did not start before it
231    /// ends become `pending`.
232    pub time_budget: Option<Duration>,
233    /// The timeout of the companion `init` and the dry run. `None` uses
234    /// 120 seconds.
235    pub runner_timeout: Option<Duration>,
236    /// The config file of the test runner, for example a separate Vitest
237    /// config of the integration tests. A relative path is relative to the
238    /// project root. The file must exist inside the project root. `None`
239    /// uses the `mutation.runnerConfig` config key, else the default config
240    /// discovery of the runner. Only the Vitest runner reads a config file.
241    pub runner_config: Option<PathBuf>,
242    /// The names of the Vitest projects that the run uses, as the Vitest
243    /// `--project` flag selects them. Empty uses the
244    /// `mutation.runnerProjects` config key, else each project. Only the
245    /// Vitest runner reads it.
246    pub runner_projects: Vec<String>,
247    /// The files that the caller writes after the run, for example the
248    /// `--output-file` report. The worktree check leaves them out, so an old
249    /// report does not make the worktree dirty. A relative path is relative
250    /// to the process directory, as the caller writes it.
251    pub output_paths: Vec<PathBuf>,
252    /// Type-check each survived mutant through the TypeScript-Go companion
253    /// of `--type-aware`. A survivor whose mutated file does not type-check
254    /// becomes `compile_error` and leaves the score. The run fails before
255    /// the tests start when no trusted companion exists.
256    pub typecheck: bool,
257    /// Reuse the final results in the outcome journal of an interrupted
258    /// earlier run, and run only the other mutants. A journal of other
259    /// inputs stops the run with `FALLOW_MUTATION_RESUME_MISMATCH`. With no
260    /// journal, the run starts from the beginning and the report says so.
261    /// Without this option, the run starts a new journal.
262    pub resume: bool,
263    /// Run only the mutants with these ids, for example the survivors of an
264    /// earlier report after new tests. Each id must be in the plan of the
265    /// scope, or the run fails with `FALLOW_MUTATION_UNKNOWN_MUTANT`. Empty
266    /// runs each mutant of the scope.
267    pub mutant_ids: Vec<String>,
268    /// Allow a dirty worktree when each dirty path is a test file: a path
269    /// that the test path rules match, or a test file of the plan. Another
270    /// dirty path fails the run with `FALLOW_MUTATION_NON_TEST_CHANGE`, so
271    /// the run proves a change of the tests only. `allow_dirty` wins.
272    pub test_changes_only: bool,
273    /// Record the arguments of the changed exported functions in a record
274    /// pass after the mutant runs. Off by default.
275    pub record_args: RecordArgsMode,
276}