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::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/// The code that a mutation run mutates.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum MutationRunScope {
54    /// The added lines against a base ref. `None` detects the base ref the
55    /// same way as `audit`. An explicit `analysis.diff_file` wins over the
56    /// base ref.
57    Changed {
58        /// The base ref.
59        base: Option<String>,
60    },
61    /// Each source file of the project.
62    All,
63    /// The files at these paths, or below these directories. A relative
64    /// path is relative to the project root.
65    Paths(Vec<PathBuf>),
66}
67
68impl Default for MutationRunScope {
69    fn default() -> Self {
70        Self::Changed { base: None }
71    }
72}
73
74/// How a run records the arguments of the changed exported functions in its
75/// dry run. The values stay in the gitignored cache directory.
76#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum RecordArgsMode {
79    /// No recording.
80    #[default]
81    Off,
82    /// Keep the types of the arguments only.
83    Shapes,
84    /// Keep the argument values, after the redaction of secrets, so that a
85    /// replay can use them.
86    Values,
87}
88
89/// Options of [`crate::replay_mutation`]: one export called on the original
90/// and on one mutant.
91#[derive(Debug, Clone, Default)]
92pub struct MutationReplayOptions {
93    /// Shared project, config and cache options.
94    pub analysis: AnalysisOptions,
95    /// The root-relative path of the file of the mutant, with forward
96    /// slashes.
97    pub file: String,
98    /// The id of the mutant.
99    pub mutant_id: String,
100    /// The original byte span of the mutant. Two mutants can share an id
101    /// in runs of other scopes, so the span selects the mutant.
102    pub span: (u32, u32),
103    /// The operator of the mutant, which finds the mutant faster and also
104    /// for an opt-in operator. `None` tries each operator.
105    pub operator: Option<Operator>,
106    /// The export to call. `None` calls the export whose declaration holds
107    /// the function of the mutant.
108    pub export: Option<String>,
109    /// The arguments of each call, in the replay encoding. `None` replays
110    /// the inputs that a `--record-args values` run recorded for the
111    /// export, up to the first witness.
112    pub args: Option<Vec<serde_json::Value>>,
113    /// The JavaScript runtime, as for a run.
114    pub runtime: Option<PathBuf>,
115    /// The config file of the test runner, as for a run.
116    pub runner_config: Option<PathBuf>,
117    /// The time limit of one call, at most 10 minutes. `None` uses 5
118    /// seconds.
119    pub call_timeout: Option<Duration>,
120    /// The timeout of the companion `init`. `None` uses 120 seconds.
121    pub runner_timeout: Option<Duration>,
122}
123
124/// A phase event of a mutation run, for a caller that shows progress.
125///
126/// [`crate::run_mutation_with_progress`] sends the events in run order. A
127/// run with no covered mutant and no test file skips the runner phases.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129#[non_exhaustive]
130pub enum MutationProgress {
131    /// The plan is ready. The runner setup starts: the runtime, the
132    /// companion install and the runner start.
133    Setup {
134        /// The planned mutants.
135        mutants: usize,
136    },
137    /// The baseline run starts: the test files run with no active mutant.
138    Baseline {
139        /// The test files of the baseline run.
140        test_files: usize,
141    },
142    /// The mutant runs. The first event has `done` 0, and each finished
143    /// mutant sends one event.
144    Mutants {
145        /// The mutants that finished.
146        done: usize,
147        /// The mutants that this phase runs. A cached result is not in it.
148        total: usize,
149    },
150    /// The retries of survivors and timeouts. The first event has `done` 0.
151    Retries {
152        /// The retries that finished.
153        done: usize,
154        /// The retries that this phase runs.
155        total: usize,
156    },
157    /// The tests stopped. The worktree check, the survivor type check and
158    /// the report start.
159    Finalize,
160}
161
162/// Receives the [`MutationProgress`] events of a run. The scheduler sends
163/// the mutant events from its worker threads.
164pub type MutationProgressSink<'a> = &'a (dyn Fn(MutationProgress) + Sync);
165
166/// Options of [`crate::run_mutation`] and [`crate::plan_mutation`].
167#[derive(Debug, Clone, Default)]
168pub struct MutationRunOptions {
169    /// Shared project, config and cache options.
170    pub analysis: AnalysisOptions,
171    /// The code to mutate.
172    pub scope: MutationRunScope,
173    /// The operators to use. `None` uses the default set
174    /// (`Operator::DEFAULT`).
175    pub operators: Option<Vec<Operator>>,
176    /// Keep mutants near a file system, process, network or database sink.
177    /// Only an explicit caller option can set this, never project config,
178    /// because the run has no sandbox copy.
179    pub allow_side_effects: bool,
180    /// Execute all covering tests and retain complete killing test sets.
181    pub kill_matrix: bool,
182    /// The `--kill-matrix-for` targets: test files or runner test ids. Each
183    /// mutant that a target test covers runs its target tests without bail
184    /// and its other covering tests with bail. The other mutants are
185    /// `pruned`. Exclusive with `kill_matrix`.
186    pub kill_matrix_targets: Vec<String>,
187    /// The maximum number of covered mutants to run, in rank order. A
188    /// mutant that no dry-run test covers is `no_coverage` and does not
189    /// count. The others become `pending`.
190    pub max_mutants: Option<usize>,
191    /// The maximum number of mutants on one source line, chosen at plan time
192    /// in a fixed operator order. The others become `pending` with the reason
193    /// `sampled-out`, and the run never executes them. `None` uses the
194    /// `mutation.mutantsPerLine` config key, else keeps each mutant. A run of
195    /// `mutant_ids` never samples.
196    pub mutants_per_line: Option<usize>,
197    /// Widen each changed line of the changed-code scope to the whole
198    /// function that holds it. The other scopes ignore it. `false` still
199    /// uses the `mutation.functionScope` config key.
200    pub function_scope: bool,
201    /// Run in a dirty git worktree, or outside a git worktree. The run still
202    /// compares the worktree after the run.
203    pub allow_dirty: bool,
204    /// The JavaScript runtime. `None` uses the runtime of the runner from
205    /// `PATH`: `node` for `node:test`, `bun` for `bun test`, and `node`,
206    /// then `bun`, for Vitest.
207    pub runtime: Option<PathBuf>,
208    /// The number of companion processes. `None` uses half the logical
209    /// cores.
210    pub concurrency: Option<usize>,
211    /// The time budget of the run. Mutants that did not start before it
212    /// ends become `pending`.
213    pub time_budget: Option<Duration>,
214    /// The timeout of the companion `init` and the dry run. `None` uses
215    /// 120 seconds.
216    pub runner_timeout: Option<Duration>,
217    /// The config file of the test runner, for example a separate Vitest
218    /// config of the integration tests. A relative path is relative to the
219    /// project root. The file must exist inside the project root. `None`
220    /// uses the `mutation.runnerConfig` config key, else the default config
221    /// discovery of the runner. Only the Vitest runner reads a config file.
222    pub runner_config: Option<PathBuf>,
223    /// The files that the caller writes after the run, for example the
224    /// `--output-file` report. The worktree check leaves them out, so an old
225    /// report does not make the worktree dirty. A relative path is relative
226    /// to the process directory, as the caller writes it.
227    pub output_paths: Vec<PathBuf>,
228    /// Type-check each survived mutant through the TypeScript-Go companion
229    /// of `--type-aware`. A survivor whose mutated file does not type-check
230    /// becomes `compile_error` and leaves the score. The run fails before
231    /// the tests start when no trusted companion exists.
232    pub typecheck: bool,
233    /// Reuse the final results in the outcome journal of an interrupted
234    /// earlier run, and run only the other mutants. A journal of other
235    /// inputs stops the run with `FALLOW_MUTATION_RESUME_MISMATCH`. With no
236    /// journal, the run starts from the beginning and the report says so.
237    /// Without this option, the run starts a new journal.
238    pub resume: bool,
239    /// Run only the mutants with these ids, for example the survivors of an
240    /// earlier report after new tests. Each id must be in the plan of the
241    /// scope, or the run fails with `FALLOW_MUTATION_UNKNOWN_MUTANT`. Empty
242    /// runs each mutant of the scope.
243    pub mutant_ids: Vec<String>,
244    /// Allow a dirty worktree when each dirty path is a test file: a path
245    /// that the test path rules match, or a test file of the plan. Another
246    /// dirty path fails the run with `FALLOW_MUTATION_NON_TEST_CHANGE`, so
247    /// the run proves a change of the tests only. `allow_dirty` wins.
248    pub test_changes_only: bool,
249    /// Record the arguments of the changed exported functions in a record
250    /// pass after the mutant runs. Off by default.
251    pub record_args: RecordArgsMode,
252}