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 selected Vitest projects, as for a run.
118    pub runner_projects: Vec<String>,
119    /// The time limit of one call, at most 10 minutes. `None` uses 5
120    /// seconds.
121    pub call_timeout: Option<Duration>,
122    /// The timeout of the companion `init`. `None` uses 120 seconds.
123    pub runner_timeout: Option<Duration>,
124}
125
126/// A phase event of a mutation run, for a caller that shows progress.
127///
128/// [`crate::run_mutation_with_progress`] sends the events in run order. A
129/// run with no covered mutant and no test file skips the runner phases.
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131#[non_exhaustive]
132pub enum MutationProgress {
133    /// The plan is ready. The runner setup starts: the runtime, the
134    /// companion install and the runner start.
135    Setup {
136        /// The planned mutants.
137        mutants: usize,
138    },
139    /// The baseline run starts: the test files run with no active mutant.
140    Baseline {
141        /// The test files of the baseline run.
142        test_files: usize,
143    },
144    /// The mutant runs. The first event has `done` 0, and each finished
145    /// mutant sends one event.
146    Mutants {
147        /// The mutants that finished.
148        done: usize,
149        /// The mutants that this phase runs. A cached result is not in it.
150        total: usize,
151    },
152    /// The retries of survivors and timeouts. The first event has `done` 0.
153    Retries {
154        /// The retries that finished.
155        done: usize,
156        /// The retries that this phase runs.
157        total: usize,
158    },
159    /// The tests stopped. The worktree check, the survivor type check and
160    /// the report start.
161    Finalize,
162}
163
164/// Receives the [`MutationProgress`] events of a run. The scheduler sends
165/// the mutant events from its worker threads.
166pub type MutationProgressSink<'a> = &'a (dyn Fn(MutationProgress) + Sync);
167
168/// Options of [`crate::run_mutation`] and [`crate::plan_mutation`].
169#[derive(Debug, Clone, Default)]
170pub struct MutationRunOptions {
171    /// Shared project, config and cache options.
172    pub analysis: AnalysisOptions,
173    /// The code to mutate.
174    pub scope: MutationRunScope,
175    /// The operators to use. `None` uses the default set
176    /// (`Operator::DEFAULT`).
177    pub operators: Option<Vec<Operator>>,
178    /// Keep mutants near a file system, process, network or database sink.
179    /// Only an explicit caller option can set this, never project config,
180    /// because the run has no sandbox copy.
181    pub allow_side_effects: bool,
182    /// Execute all covering tests and retain complete killing test sets.
183    pub kill_matrix: bool,
184    /// The `--kill-matrix-for` targets: test files or runner test ids. Each
185    /// mutant that a target test covers runs its target tests without bail.
186    /// After a target kill, its other covering tests run with bail. A mutant
187    /// that no target kills is `not_killed_by_target`, unless
188    /// `kill_matrix_full` is set. The other mutants are `pruned`. Exclusive
189    /// with `kill_matrix`.
190    pub kill_matrix_targets: Vec<String>,
191    /// Run the other covering tests of each target mutant also when no target
192    /// kills it, and retry each survivor (`--kill-matrix-full`). Each mutant
193    /// then gets a final status. Needs `kill_matrix_targets`.
194    pub kill_matrix_full: bool,
195    /// The maximum number of covered mutants to run, in rank order. A
196    /// mutant that no dry-run test covers is `no_coverage` and does not
197    /// count. The others become `pending`.
198    pub max_mutants: Option<usize>,
199    /// The maximum number of mutants on one source line, chosen at plan time
200    /// in a fixed operator order. The others become `pending` with the reason
201    /// `sampled-out`, and the run never executes them. `None` uses the
202    /// `mutation.mutantsPerLine` config key, else keeps each mutant. A run of
203    /// `mutant_ids` never samples.
204    pub mutants_per_line: Option<usize>,
205    /// Widen each changed line of the changed-code scope to the whole
206    /// function that holds it. The other scopes ignore it. `false` still
207    /// uses the `mutation.functionScope` config key.
208    pub function_scope: bool,
209    /// Run in a dirty git worktree, or outside a git worktree. The run still
210    /// compares the worktree after the run.
211    pub allow_dirty: bool,
212    /// The JavaScript runtime. `None` uses the runtime of the runner from
213    /// `PATH`: `node` for `node:test`, `bun` for `bun test`, and `node`,
214    /// then `bun`, for Vitest.
215    pub runtime: Option<PathBuf>,
216    /// The number of companion processes. `None` uses half the logical
217    /// cores.
218    pub concurrency: Option<usize>,
219    /// The time budget of the run. Mutants that did not start before it
220    /// ends become `pending`.
221    pub time_budget: Option<Duration>,
222    /// The timeout of the companion `init` and the dry run. `None` uses
223    /// 120 seconds.
224    pub runner_timeout: Option<Duration>,
225    /// The config file of the test runner, for example a separate Vitest
226    /// config of the integration tests. A relative path is relative to the
227    /// project root. The file must exist inside the project root. `None`
228    /// uses the `mutation.runnerConfig` config key, else the default config
229    /// discovery of the runner. Only the Vitest runner reads a config file.
230    pub runner_config: Option<PathBuf>,
231    /// The names of the Vitest projects that the run uses, as the Vitest
232    /// `--project` flag selects them. Empty uses the
233    /// `mutation.runnerProjects` config key, else each project. Only the
234    /// Vitest runner reads it.
235    pub runner_projects: Vec<String>,
236    /// The files that the caller writes after the run, for example the
237    /// `--output-file` report. The worktree check leaves them out, so an old
238    /// report does not make the worktree dirty. A relative path is relative
239    /// to the process directory, as the caller writes it.
240    pub output_paths: Vec<PathBuf>,
241    /// Type-check each survived mutant through the TypeScript-Go companion
242    /// of `--type-aware`. A survivor whose mutated file does not type-check
243    /// becomes `compile_error` and leaves the score. The run fails before
244    /// the tests start when no trusted companion exists.
245    pub typecheck: bool,
246    /// Reuse the final results in the outcome journal of an interrupted
247    /// earlier run, and run only the other mutants. A journal of other
248    /// inputs stops the run with `FALLOW_MUTATION_RESUME_MISMATCH`. With no
249    /// journal, the run starts from the beginning and the report says so.
250    /// Without this option, the run starts a new journal.
251    pub resume: bool,
252    /// Run only the mutants with these ids, for example the survivors of an
253    /// earlier report after new tests. Each id must be in the plan of the
254    /// scope, or the run fails with `FALLOW_MUTATION_UNKNOWN_MUTANT`. Empty
255    /// runs each mutant of the scope.
256    pub mutant_ids: Vec<String>,
257    /// Allow a dirty worktree when each dirty path is a test file: a path
258    /// that the test path rules match, or a test file of the plan. Another
259    /// dirty path fails the run with `FALLOW_MUTATION_NON_TEST_CHANGE`, so
260    /// the run proves a change of the tests only. `allow_dirty` wins.
261    pub test_changes_only: bool,
262    /// Record the arguments of the changed exported functions in a record
263    /// pass after the mutant runs. Off by default.
264    pub record_args: RecordArgsMode,
265}