1use std::path::{Path, PathBuf};
8use std::sync::Arc;
9use std::time::{Duration, Instant};
10
11use fallow_engine::mutation::{
12 DiffIndex, MutantDisposition, MutationPlan, MutationPlanRequest, MutationScope,
13 plan_mutations_for_session_with,
14};
15use fallow_engine::session::AnalysisSession;
16use fallow_output::{
17 MutationCacheOutput, MutationPlanOutput, MutationPlanSchemaVersion, MutationReport,
18 MutationResumeOutput, MutationRunnerOutput, MutationRuntimeOutput, MutationSchemaVersion,
19 MutationScopeKind, MutationScopeOutput, MutationTimings, MutationUnmatchedPath,
20 MutationWorktreeCheck,
21};
22use fallow_types::envelope::ElapsedMs;
23use rustc_hash::FxHashSet;
24
25use super::mutation_record::{record_and_search, settle_recording};
26use super::mutation_runner_options::{runner_config, runner_projects};
27use super::mutation_witness::{WitnessSearch, search_witnesses};
28use crate::ProgrammaticError;
29use crate::analysis_context::{ProgrammaticAnalysisContext, resolve_programmatic_analysis_context};
30use crate::mutation::companion::{COMPANION_FILES, install};
31use crate::mutation::discovery::{JsRuntime, discover_runtime};
32use crate::mutation::journal::{JOURNAL_FORMAT, Journal, JournalHeader, JournalMismatch};
33use crate::mutation::last_report::ignore_cache_dir;
34use crate::mutation::manifest::{Manifest, RunnerRange, manifest};
35use crate::mutation::node_args::node_test_args;
36use crate::mutation::protocol::{InitOptions, InitRequest};
37use crate::mutation::recorded_args::RecordPass;
38use crate::mutation::report::{
39 CompletionFacts, baseline_failures, completion, function_results, issues, kebab,
40 mutant_results, plan_counts, plan_files, plan_mutants, skipped_files, skipped_tests_issue,
41 summary, tool_version, unmatched_paths,
42};
43use crate::mutation::result_cache::{KeyFiles, NOT_KEYED, ResultCache};
44use crate::mutation::run_dir::{RunFile, write_run_dir};
45use crate::mutation::runner_select::{Runner, select_runner};
46use crate::mutation::runner_version::{plan_runner, runner_version_help};
47use crate::mutation::scheduler::clock::SystemClock;
48use crate::mutation::scheduler::{
49 OutcomeJournal, ResultLookup, ScheduleConfig, ScheduleError, ScheduleIssue, ScheduleOutcome,
50 SchedulePlan, ScheduledMutant, run_schedule_with_progress,
51};
52use crate::mutation::transport::ProcessSpawner;
53use crate::mutation::typecheck::typecheck_survivors;
54use crate::mutation::worktree::{Exclusions, WorktreeSnapshot, canonical_path, snapshot};
55use crate::mutation::{
56 MutationProgress, MutationProgressSink, MutationRunOptions, MutationRunScope,
57};
58
59pub(super) type ProgrammaticResult<T> = Result<T, ProgrammaticError>;
60
61pub(super) const DEFAULT_RUNNER_TIMEOUT: Duration = Duration::from_secs(120);
63
64pub(super) fn mutation_error(code: &str, message: impl Into<String>) -> ProgrammaticError {
65 ProgrammaticError::new(message, 2).with_code(code)
66}
67
68#[expect(
69 clippy::cast_possible_truncation,
70 reason = "a run lasts far less than 2^64 milliseconds"
71)]
72pub(super) const fn millis(duration: Duration) -> u64 {
73 duration.as_millis() as u64
74}
75
76fn validate(options: &MutationRunOptions) -> ProgrammaticResult<()> {
77 if options.concurrency == Some(0) {
78 return Err(mutation_error(
79 "FALLOW_INVALID_MUTATION_OPTIONS",
80 "the mutation concurrency must be at least 1",
81 )
82 .with_context("mutation.concurrency"));
83 }
84 if options.max_mutants == Some(0) {
85 return Err(mutation_error(
86 "FALLOW_INVALID_MUTATION_OPTIONS",
87 "the mutant limit must be at least 1",
88 )
89 .with_context("mutation.maxMutants"));
90 }
91 if options.mutants_per_line == Some(0) {
92 return Err(mutation_error(
93 "FALLOW_INVALID_MUTATION_OPTIONS",
94 "the mutants per line limit must be at least 1",
95 )
96 .with_context("mutation.mutantsPerLine"));
97 }
98 if options.kill_matrix && !options.kill_matrix_targets.is_empty() {
99 return Err(mutation_error(
100 "FALLOW_INVALID_MUTATION_OPTIONS",
101 "the full kill matrix and the kill matrix for targets are exclusive; pass only one of them",
102 ));
103 }
104 if options.kill_matrix_full && options.kill_matrix_targets.is_empty() {
105 return Err(mutation_error(
106 "FALLOW_INVALID_MUTATION_OPTIONS",
107 "--kill-matrix-full needs at least one --kill-matrix-for target",
108 ));
109 }
110 if options
111 .kill_matrix_targets
112 .iter()
113 .any(|target| target.trim().is_empty())
114 {
115 return Err(mutation_error(
116 "FALLOW_INVALID_MUTATION_OPTIONS",
117 "a kill matrix target must name a test file or a test id",
118 ));
119 }
120 if options.time_budget.is_some_and(|budget| budget.is_zero())
121 || options
122 .runner_timeout
123 .is_some_and(|timeout| timeout.is_zero())
124 {
125 return Err(mutation_error(
126 "FALLOW_INVALID_MUTATION_OPTIONS",
127 "a mutation time limit must be more than zero",
128 ));
129 }
130 Ok(())
131}
132
133const TEST_ID_SEPARATOR: &str = "::";
135
136fn normalize_target(root: &Path, target: &str) -> String {
140 let (file, name) = target
141 .split_once(TEST_ID_SEPARATOR)
142 .map_or((target, None), |(file, name)| (file, Some(name)));
143 let file = file.trim();
144 let path = Path::new(file);
145 let relative = if path.is_absolute() {
146 let canonical_root = root.canonicalize().ok();
147 path.strip_prefix(root)
148 .ok()
149 .or_else(|| {
150 canonical_root
151 .as_deref()
152 .and_then(|root| path.strip_prefix(root).ok())
153 })
154 .map_or_else(|| file.to_owned(), |rel| rel.to_string_lossy().into_owned())
155 } else {
156 file.to_owned()
157 };
158 let relative = relative.replace('\\', "/");
159 let mut trimmed = relative.as_str();
160 while let Some(rest) = trimmed.strip_prefix("./") {
161 trimmed = rest;
162 }
163 let relative = trimmed.to_owned();
164 match name {
165 Some(name) => format!("{relative}{TEST_ID_SEPARATOR}{name}"),
166 None => relative,
167 }
168}
169
170fn with_normalized_targets(
174 options: &MutationRunOptions,
175 root: &Path,
176) -> ProgrammaticResult<Option<MutationRunOptions>> {
177 if options.kill_matrix_targets.is_empty() {
178 return Ok(None);
179 }
180 let mut targets: Vec<String> = Vec::new();
181 for raw in &options.kill_matrix_targets {
182 let target = normalize_target(root, raw);
183 if target.is_empty() || target.starts_with(TEST_ID_SEPARATOR) {
184 return Err(mutation_error(
185 "FALLOW_INVALID_MUTATION_OPTIONS",
186 format!("the kill matrix target `{raw}` names no test file"),
187 ));
188 }
189 if !targets.contains(&target) {
190 targets.push(target);
191 }
192 }
193 Ok(Some(MutationRunOptions {
194 kill_matrix_targets: targets,
195 ..options.clone()
196 }))
197}
198
199fn sorted_targets(targets: &[String]) -> Vec<String> {
202 let mut sorted = targets.to_vec();
203 sorted.sort();
204 sorted
205}
206
207fn kill_matrix_mode<'a>(
209 options: &'a MutationRunOptions,
210 outcome: Option<&'a ScheduleOutcome>,
211) -> crate::mutation::kill_matrix::Mode<'a> {
212 use crate::mutation::kill_matrix::Mode;
213 if !options.kill_matrix_targets.is_empty() {
214 return Mode::Targets {
215 requested: &options.kill_matrix_targets,
216 resolved: outcome.map_or(&[], |outcome| outcome.targets.as_slice()),
217 full: options.kill_matrix_full,
218 };
219 }
220 if options.kill_matrix {
221 Mode::Full
222 } else {
223 Mode::Disabled
224 }
225}
226
227fn load_session(
230 analysis: &crate::AnalysisOptions,
231 operators: Option<&[fallow_engine::mutation::Operator]>,
232) -> ProgrammaticResult<AnalysisSession> {
233 let run =
234 crate::run::resolve_programmatic_run(analysis, &crate::run::ProgrammaticEntry::Mutation)?;
235 let dead_code = crate::run::runnable(&run, fallow_config::PlannedAnalysis::DeadCode)?;
236 crate::run::open_session_adjusted(&dead_code, |config| {
237 let negates = match operators {
242 Some(operators) => {
243 operators.contains(&fallow_engine::mutation::Operator::NegateCondition)
244 }
245 None => config.mutation.operators.as_ref().is_none_or(|names| {
246 names.iter().any(|name| {
247 name.as_str() == fallow_engine::mutation::Operator::NegateCondition.as_str()
248 })
249 }),
250 };
251 if negates && config.rules.constant_parameters == fallow_config::Severity::Off {
252 config.rules.constant_parameters = fallow_config::Severity::Warn;
253 }
254 })
255}
256
257fn scope_output(options: &MutationRunOptions, base_ref: Option<String>) -> MutationScopeOutput {
258 MutationScopeOutput {
259 kind: match options.scope {
260 MutationRunScope::Changed { .. } => MutationScopeKind::Changed,
261 MutationRunScope::All => MutationScopeKind::All,
262 MutationRunScope::Paths(_) => MutationScopeKind::Paths,
263 },
264 base_ref,
265 }
266}
267
268fn engine_scope(
270 options: &MutationRunOptions,
271 resolved: &ProgrammaticAnalysisContext,
272) -> ProgrammaticResult<(MutationScope, Option<String>)> {
273 let root = resolved.root();
274 match &options.scope {
275 MutationRunScope::All => Ok((MutationScope::All, None)),
276 MutationRunScope::Paths(paths) => Ok((MutationScope::Paths(paths.clone()), None)),
277 MutationRunScope::Changed { base } => {
278 if options.analysis.diff_file.is_some()
279 && let Some(request) = &resolved.diff_request
280 && request.status == fallow_output::RequestStatus::NotApplied
281 {
282 return Err(mutation_error(
283 "FALLOW_MUTATION_DIFF_NOT_APPLIED",
284 format!(
285 "cannot use {} for mutation scope ({}); regenerate the patch from the project or repository root",
286 request.requested,
287 request.reason.as_deref().unwrap_or("not-applied"),
288 ),
289 )
290 .with_context("analysis.diffFile"));
291 }
292 if let Some(diff) = &resolved.diff {
293 return Ok((MutationScope::ChangedSinceBase(diff.clone()), None));
294 }
295 let resolved_base = crate::audit_run::resolve_audit_base(root, base.as_deref())
296 .map_err(|error| {
297 let message = match error {
298 crate::audit_run::AuditBaseError::InvalidRef { value, reason, .. } => {
299 format!("invalid base ref `{value}`: {reason}")
300 }
301 crate::audit_run::AuditBaseError::NotDetected => {
302 "no base branch to compare against; pass a base ref or mutate all files"
303 .to_owned()
304 }
305 };
306 mutation_error("FALLOW_MUTATION_BASE_NOT_FOUND", message)
307 .with_context("mutation.base")
308 })?;
309 let text =
310 fallow_engine::changed_files::try_get_mutation_diff(root, &resolved_base.git_ref)
311 .map_err(|error| {
312 mutation_error(
313 "FALLOW_CHANGED_FILES_FAILED",
314 format!(
315 "cannot diff against `{}`: {}",
316 resolved_base.git_ref,
317 error.describe()
318 ),
319 )
320 })?;
321 let label = format!("git diff {}", resolved_base.git_ref);
322 let index = fallow_engine::diff_source::place_diff(
323 DiffIndex::from_unified_diff(&text),
324 root,
325 &fallow_engine::diff_source::diff_base_candidates(root),
326 &label,
327 )
328 .map_err(|stand_down| {
329 let (_, message) = stand_down.into_parts();
330 mutation_error("FALLOW_CHANGED_FILES_FAILED", message)
331 })?;
332 Ok((
333 MutationScope::ChangedSinceBase(index),
334 Some(resolved_base.git_ref),
335 ))
336 }
337 }
338}
339
340fn config_operators(
344 session: &AnalysisSession,
345) -> ProgrammaticResult<Option<Vec<fallow_engine::mutation::Operator>>> {
346 let Some(names) = &session.config().mutation.operators else {
347 return Ok(None);
348 };
349 names
350 .iter()
351 .map(|name| {
352 fallow_engine::mutation::Operator::from_name(name.as_str()).ok_or_else(|| {
353 mutation_error(
354 "FALLOW_INVALID_MUTATION_OPTIONS",
355 format!("unknown mutation operator `{}`", name.as_str()),
356 )
357 .with_context("mutation.operators")
358 })
359 })
360 .collect::<ProgrammaticResult<Vec<_>>>()
361 .map(Some)
362}
363
364pub(super) struct Planned {
365 pub(super) resolved: ProgrammaticAnalysisContext,
366 pub(super) cache_dir: PathBuf,
367 pub(super) runner: Runner,
369 pub(super) plan: MutationPlan,
370 base_ref: Option<String>,
371 pub(super) runner_config: Option<String>,
373 pub(super) runner_projects: Vec<String>,
375 operators: Option<Vec<String>>,
377}
378
379pub(super) fn plan_for(
380 options: &MutationRunOptions,
381 before_plan: impl FnOnce(&Path, &Path) -> ProgrammaticResult<()>,
382) -> ProgrammaticResult<Planned> {
383 plan_with_wraps(options, before_plan, false)
384}
385
386pub(super) fn plan_with_wraps(
391 options: &MutationRunOptions,
392 before_plan: impl FnOnce(&Path, &Path) -> ProgrammaticResult<()>,
393 record_exports: bool,
394) -> ProgrammaticResult<Planned> {
395 validate(options)?;
396 let resolved = resolve_programmatic_analysis_context(&options.analysis)?;
397 let session = load_session(&options.analysis, options.operators.as_deref())?;
398 let cache_dir = session.config().cache_dir.clone();
399 let configured = session.config().mutation.runner;
400 before_plan(resolved.root(), &cache_dir)?;
401 let (scope, base_ref) = engine_scope(options, &resolved)?;
402 let operators = match &options.operators {
403 Some(operators) => Some(operators.clone()),
404 None => config_operators(&session)?,
405 };
406 let operator_names = operators.as_deref().map(operator_names);
407 let mutation_config = &session.config().mutation;
408 let mutants_per_line = options
411 .mutant_ids
412 .is_empty()
413 .then(|| {
414 options
415 .mutants_per_line
416 .or(mutation_config.mutants_per_line)
417 })
418 .flatten();
419 let request = MutationPlanRequest {
420 scope,
421 operators,
422 allow_side_effects: options.allow_side_effects,
423 max_mutants: options.max_mutants,
424 mutants_per_line,
425 function_scope: options.function_scope || mutation_config.function_scope == Some(true),
426 skip_component_files: false,
427 mutant_ids: (!options.mutant_ids.is_empty())
428 .then(|| options.mutant_ids.iter().cloned().collect()),
429 record_exports,
430 };
431 let mut selected = None;
434 let plan = resolved
435 .install(|| {
436 plan_mutations_for_session_with(&session, &request, |plan| {
437 let runner = select_runner(configured, resolved.root(), &plan.test_files);
438 selected = Some(runner);
439 !runner.loads_component_files()
440 })
441 })
442 .map_err(|error| mutation_error("FALLOW_MUTATION_PLAN_FAILED", error.to_string()))?;
443 let runner =
444 selected.unwrap_or_else(|| select_runner(configured, resolved.root(), &plan.test_files));
445 let runner_config = runner_config(options, &session, resolved.root(), runner)?;
446 let runner_projects = runner_projects(options, &session, runner)?;
447 Ok(Planned {
448 resolved,
449 cache_dir,
450 runner,
451 plan,
452 base_ref,
453 runner_config,
454 runner_projects,
455 operators: operator_names,
456 })
457}
458
459pub fn plan_mutation(options: &MutationRunOptions) -> ProgrammaticResult<MutationPlanOutput> {
466 let started = Instant::now();
467 let planned = plan_for(options, |_, _| Ok(()))?;
468 let plan = &planned.plan;
469 Ok(MutationPlanOutput {
470 schema_version: MutationPlanSchemaVersion::V1,
471 version: tool_version(),
472 elapsed_ms: ElapsedMs(millis(started.elapsed())),
473 scope: scope_output(options, planned.base_ref.clone()),
474 counts: plan_counts(plan),
475 mutants: plan_mutants(plan),
476 files: plan_files(plan),
477 test_files: plan.test_files.clone(),
478 no_test_files: plan.no_test_files,
479 framework_config_checked: plan.framework_config_checked,
480 skipped_files: skipped_files(plan),
481 unmatched_paths: unmatched_paths(plan),
482 unmatched_path_reasons: unmatched_path_reasons(plan, planned.resolved.root()),
483 runner: plan_runner(planned.runner, planned.resolved.root())
484 .map_err(|message| mutation_error("FALLOW_MUTATION_PROTOCOL_INVALID", message))?,
485 })
486}
487
488fn unsafe_cache_dir(message: String) -> ProgrammaticError {
489 mutation_error("FALLOW_MUTATION_UNSAFE_CACHE_DIR", message)
490 .with_help(
491 "set FALLOW_CACHE_DIR, or cache.dir inside the project, to a directory that holds no project file, such as .fallow",
492 )
493 .with_context("cache.dir")
494}
495
496pub(super) fn guard_cache_dir(root: &Path, cache_dir: &Path) -> ProgrammaticResult<()> {
501 if !canonical_path(root).starts_with(canonical_path(cache_dir)) {
502 return Ok(());
503 }
504 Err(unsafe_cache_dir(format!(
505 "the cache directory `{}` is the project root or a directory above it, so the worktree check cannot see stray writes",
506 cache_dir.display()
507 )))
508}
509
510fn guard_cache_holds_no_planned_file(
512 root: &Path,
513 cache_dir: &Path,
514 plan: &MutationPlan,
515) -> ProgrammaticResult<()> {
516 let root = canonical_path(root);
517 let cache = canonical_path(cache_dir);
518 let inside = plan
519 .files
520 .iter()
521 .map(|file| file.path.as_str())
522 .chain(plan.test_files.iter().map(String::as_str))
523 .find(|path| root.join(path).starts_with(&cache));
524 let Some(path) = inside else {
525 return Ok(());
526 };
527 Err(unsafe_cache_dir(format!(
528 "the cache directory `{}` holds the project file `{path}`, so the worktree check cannot see stray writes",
529 cache_dir.display()
530 )))
531}
532
533fn take_worktree_snapshot(
534 root: &Path,
535 cache_dir: &Path,
536 output_paths: &[PathBuf],
537 start: Option<&WorktreeSnapshot>,
538) -> ProgrammaticResult<Option<WorktreeSnapshot>> {
539 let cwd = std::env::current_dir().unwrap_or_else(|_| root.to_path_buf());
542 let outputs = output_paths.iter().map(|path| cwd.join(path));
543 let exclusions = Exclusions {
547 paths: std::iter::once(cache_dir.join("mutation"))
548 .chain(outputs)
549 .collect(),
550 ignored: vec![cache_dir.to_path_buf()],
551 };
552 snapshot(root, &exclusions, start)
553 .map_err(|message| mutation_error("FALLOW_MUTATION_WORKTREE_CHECK_FAILED", message))
554}
555
556struct WorktreeEnd {
558 changed_paths: Vec<String>,
560 check_error: Option<String>,
562}
563
564fn settle_worktree(
567 start: Option<&WorktreeSnapshot>,
568 take_end: impl FnOnce(&WorktreeSnapshot) -> ProgrammaticResult<Option<WorktreeSnapshot>>,
569) -> WorktreeEnd {
570 let Some(start) = start else {
571 return WorktreeEnd {
572 changed_paths: Vec::new(),
573 check_error: None,
574 };
575 };
576 match take_end(start) {
577 Ok(end) => WorktreeEnd {
578 changed_paths: end.map(|end| start.changed_paths(&end)).unwrap_or_default(),
579 check_error: None,
580 },
581 Err(error) => WorktreeEnd {
582 changed_paths: Vec::new(),
583 check_error: Some(error.message),
584 },
585 }
586}
587
588fn with_worktree_facts(mut error: ProgrammaticError, end: &WorktreeEnd) -> ProgrammaticError {
590 if !end.changed_paths.is_empty() {
591 error.message = format!(
592 "{}; the run changed these worktree paths: {}",
593 error.message,
594 end.changed_paths.join(", ")
595 );
596 }
597 if let Some(check_error) = &end.check_error {
598 error.message = format!(
599 "{}; the end-of-run worktree check failed: {check_error}",
600 error.message
601 );
602 }
603 error
604}
605
606const fn path_noun(count: usize) -> &'static str {
607 if count == 1 { "path" } else { "paths" }
608}
609
610fn guard_worktree(allow_dirty: bool, start: Option<&WorktreeSnapshot>) -> ProgrammaticResult<()> {
611 if allow_dirty {
612 return Ok(());
613 }
614 let Some(start) = start else {
615 return Err(mutation_error(
616 "FALLOW_MUTATION_NOT_A_REPOSITORY",
617 "mutation testing runs the tests against changed code and needs a git worktree to detect stray writes",
618 )
619 .with_help("run inside a git worktree, or pass --allow-dirty"));
620 };
621 let dirty = start.dirty_paths();
622 if dirty.is_empty() {
623 return Ok(());
624 }
625 let shown: Vec<&str> = dirty.iter().take(10).map(String::as_str).collect();
626 Err(mutation_error(
627 "FALLOW_MUTATION_DIRTY_WORKTREE",
628 format!(
629 "the git worktree has {} uncommitted {}: {}",
630 dirty.len(),
631 path_noun(dirty.len()),
632 shown.join(", ")
633 ),
634 )
635 .with_help("commit or stash the changes, or pass --allow-dirty"))
636}
637
638fn guard_planned(
641 options: &MutationRunOptions,
642 planned: &Planned,
643 start: Option<&WorktreeSnapshot>,
644) -> ProgrammaticResult<()> {
645 if options.test_changes_only && !options.allow_dirty {
646 guard_test_changes_only(planned, start)?;
647 }
648 guard_mutant_ids(options, &planned.plan)?;
649 guard_cache_holds_no_planned_file(planned.resolved.root(), &planned.cache_dir, &planned.plan)?;
650 guard_typecheck_companion(options.typecheck, planned.resolved.root())
651}
652
653fn guard_test_changes_only(
658 planned: &Planned,
659 start: Option<&WorktreeSnapshot>,
660) -> ProgrammaticResult<()> {
661 let Some(start) = start else {
662 return Ok(());
663 };
664 let root = planned.resolved.root();
665 let test_files: FxHashSet<&str> = planned.plan.test_files.iter().map(String::as_str).collect();
666 let changed: Vec<String> = start
667 .dirty_paths()
668 .into_iter()
669 .filter(|path| {
670 !test_files.contains(path.as_str())
671 && !fallow_engine::test_paths::is_test_path_str(root, path)
672 })
673 .collect();
674 if changed.is_empty() {
675 return Ok(());
676 }
677 let shown: Vec<&str> = changed.iter().take(10).map(String::as_str).collect();
678 Err(mutation_error(
679 "FALLOW_MUTATION_NON_TEST_CHANGE",
680 format!(
681 "the git worktree changes {} {} that {} not a test file: {}",
682 changed.len(),
683 path_noun(changed.len()),
684 if changed.len() == 1 { "is" } else { "are" },
685 shown.join(", ")
686 ),
687 )
688 .with_help(
689 "a recheck proves a change of the tests only; commit or stash the other changes, then run `fallow mutation` again for new results",
690 ))
691}
692
693fn guard_mutant_ids(options: &MutationRunOptions, plan: &MutationPlan) -> ProgrammaticResult<()> {
696 if options.mutant_ids.is_empty() {
697 return Ok(());
698 }
699 let planned: FxHashSet<&str> = plan
700 .mutants
701 .iter()
702 .map(|mutant| mutant.mutant.id.as_str())
703 .collect();
704 let mut missing: Vec<&str> = options
705 .mutant_ids
706 .iter()
707 .map(String::as_str)
708 .filter(|id| !planned.contains(id))
709 .collect();
710 if missing.is_empty() {
711 return Ok(());
712 }
713 missing.sort_unstable();
714 missing.dedup();
715 Err(mutation_error(
716 "FALLOW_MUTATION_UNKNOWN_MUTANT",
717 format!(
718 "the plan has no mutant with the {} {}",
719 if missing.len() == 1 { "id" } else { "ids" },
720 missing.join(", ")
721 ),
722 )
723 .with_context("mutation.mutantId")
724 .with_help(
725 "a mutant id changes when its source changes; run `fallow mutation` again for new ids",
726 ))
727}
728
729fn schedule_error(
733 error: &ScheduleError,
734 runner: &RunnerRange,
735 setup_timeout: Duration,
736) -> ProgrammaticError {
737 let (code, stderr_tail) = match error {
738 ScheduleError::Integrity(_) => ("FALLOW_MUTATION_COMPANION_INTEGRITY", None),
739 ScheduleError::RunnerVersion(_) => ("FALLOW_MUTATION_RUNNER_UNSUPPORTED", None),
740 ScheduleError::Setup { stderr_tail, .. } => {
741 ("FALLOW_MUTATION_RUNNER_FAILED", stderr_tail.clone())
742 }
743 ScheduleError::RunPath { .. } => ("FALLOW_MUTATION_RUNNER_FAILED", None),
744 ScheduleError::UnknownHit(_) => ("FALLOW_MUTATION_PLAN_MISMATCH", None),
745 ScheduleError::Baseline(_) => ("FALLOW_MUTATION_BASELINE_FAILED", None),
746 ScheduleError::UnmatchedTargets(_) | ScheduleError::TargetsNeedTestFilter => {
747 ("FALLOW_MUTATION_TARGET_UNMATCHED", None)
748 }
749 ScheduleError::DuplicateTargetTestIds(_) => {
750 ("FALLOW_MUTATION_TARGET_DUPLICATE_TEST_ID", None)
751 }
752 };
753 let mut help = Vec::new();
754 if matches!(error, ScheduleError::RunnerVersion(_)) {
755 help.push(runner_version_help(runner));
756 }
757 if let ScheduleError::RunPath { help: run_path, .. } = error {
758 help.push(run_path.clone());
759 }
760 if matches!(
761 error,
762 ScheduleError::Setup {
763 timed_out: true,
764 ..
765 }
766 ) {
767 help.push(format!(
768 "the runner setup took longer than {}s; on a slow or busy host, pass --setup-timeout with a longer duration, for example 5m",
769 setup_timeout.as_secs()
770 ));
771 }
772 if let Some(tail) = stderr_tail.filter(|tail| !tail.trim().is_empty()) {
773 help.push(format!("companion stderr:\n{}", tail.trim_end()));
774 }
775 let public = mutation_error(code, error.to_string());
776 if help.is_empty() {
777 public
778 } else {
779 public.with_help(help.join("\n"))
780 }
781}
782
783fn default_concurrency() -> usize {
784 std::thread::available_parallelism()
785 .map_or(1, std::num::NonZeroUsize::get)
786 .div_ceil(2)
787 .max(1)
788}
789
790pub(super) fn runtime_error(runner: Runner, message: String) -> ProgrammaticError {
791 mutation_error("FALLOW_MUTATION_RUNTIME_NOT_FOUND", message)
792 .with_help(runner.runtime_help())
793 .with_context("mutation.runtime")
794}
795
796fn scheduled(plan: &MutationPlan, disposition: MutantDisposition) -> Vec<ScheduledMutant> {
797 plan.mutants
798 .iter()
799 .filter(|mutant| mutant.disposition == disposition)
800 .map(|mutant| ScheduledMutant {
801 id: mutant.mutant.id.as_str().to_owned(),
802 file: mutant.file.clone(),
803 })
804 .collect()
805}
806
807fn schedule_plan(plan: &MutationPlan) -> SchedulePlan {
808 SchedulePlan {
809 mutants: scheduled(plan, MutantDisposition::Planned),
810 unreached: scheduled(plan, MutantDisposition::NoCoverage),
811 pending: scheduled(plan, MutantDisposition::Pending),
812 sampled_out: scheduled(plan, MutantDisposition::SampledOut),
813 known_ids: plan
814 .mutants
815 .iter()
816 .map(|mutant| mutant.mutant.id.as_str().to_owned())
817 .collect::<FxHashSet<_>>(),
818 test_files: plan.test_files.clone(),
819 file_test_files: plan
820 .files
821 .iter()
822 .map(|file| (file.path.clone(), file.static_test_files.clone()))
823 .collect(),
824 }
825}
826
827struct Execution {
829 outcome: Option<ScheduleOutcome>,
830 runner: Option<MutationRunnerOutput>,
831 cache: Option<MutationCacheOutput>,
832 resume: Option<MutationResumeOutput>,
833 setup_ms: u64,
834 record: Option<RecordPass>,
836 witness: Option<WitnessSearch>,
839}
840
841fn recording_and_witnesses(
844 options: &MutationRunOptions,
845 planned: &Planned,
846 execution: &Execution,
847 results: &mut [fallow_output::MutantResult],
848) -> Option<fallow_output::MutationRecordingOutput> {
849 let recording = settle_recording(options, &planned.cache_dir, execution.record.as_ref());
850 if let Some(search) = &execution.witness {
851 search_witnesses(
852 search,
853 &planned.plan,
854 planned.resolved.root(),
855 &planned.cache_dir,
856 results,
857 );
858 }
859 recording
860}
861
862pub(super) fn run_files(plan: &MutationPlan) -> Vec<RunFile<'_>> {
864 plan.files
865 .iter()
866 .map(|file| RunFile {
867 path: &file.path,
868 code: &file.instrumented_code,
869 })
870 .collect()
871}
872
873fn shown_path(root: &Path, path: &Path) -> String {
876 let relative = path.strip_prefix(root).map(Path::to_path_buf).or_else(|_| {
877 canonical_path(path)
878 .strip_prefix(canonical_path(root))
879 .map(Path::to_path_buf)
880 });
881 relative.map_or_else(
882 |_| path.display().to_string(),
883 |relative| {
884 relative
885 .components()
886 .map(|part| part.as_os_str().to_string_lossy())
887 .collect::<Vec<_>>()
888 .join("/")
889 },
890 )
891}
892
893fn operator_names(operators: &[fallow_engine::mutation::Operator]) -> Vec<String> {
896 let mut names: Vec<String> = operators
897 .iter()
898 .map(|operator| operator.as_str().to_owned())
899 .collect();
900 names.sort_unstable();
901 names.dedup();
902 names
903}
904
905fn scope_path(root: &Path, path: &Path) -> String {
908 let relative = path.strip_prefix(root).unwrap_or(path);
909 relative
910 .components()
911 .filter(|part| !matches!(part, std::path::Component::CurDir))
912 .map(|part| part.as_os_str().to_string_lossy())
913 .collect::<Vec<_>>()
914 .join("/")
915}
916
917fn unmatched_path_reasons(plan: &MutationPlan, root: &Path) -> Vec<MutationUnmatchedPath> {
920 plan.unmatched_paths
921 .iter()
922 .map(|entry| MutationUnmatchedPath {
923 path: scope_path(root, Path::new(&entry.path)),
924 reason: kebab(&entry.reason),
925 })
926 .collect()
927}
928
929fn scope_label(options: &MutationRunOptions, base_ref: Option<&str>, root: &Path) -> String {
933 match &options.scope {
934 MutationRunScope::All => "all".to_owned(),
935 MutationRunScope::Paths(paths) => {
936 let mut paths: Vec<String> = paths.iter().map(|path| scope_path(root, path)).collect();
937 paths.sort_unstable();
938 paths.dedup();
939 format!("paths {}", paths.join(","))
940 }
941 MutationRunScope::Changed { .. } => base_ref.map_or_else(
942 || "changed lines of a diff".to_owned(),
943 |base| format!("changed against {base}"),
944 ),
945 }
946}
947
948fn resume_mismatch(mismatch: &JournalMismatch, journal: &str) -> ProgrammaticError {
949 mutation_error(
950 "FALLOW_MUTATION_RESUME_MISMATCH",
951 format!(
952 "the journal {journal} belongs to a run with other inputs: {}",
953 mismatch.differences.join("; ")
954 ),
955 )
956 .with_help("run without --resume to start a new run; that run replaces the journal")
957 .with_context("mutation.resume")
958}
959
960fn unread_journal(options: &MutationRunOptions, planned: &Planned) -> Option<MutationResumeOutput> {
963 options.resume.then(|| MutationResumeOutput {
964 journal: shown_path(
965 planned.resolved.root(),
966 &Journal::path(&planned.cache_dir.join("mutation")),
967 ),
968 reused: 0,
969 rejected: 0,
970 note: Some("the run read no journal, because no mutant needs a test run".to_owned()),
971 })
972}
973
974fn open_stores(
977 options: &MutationRunOptions,
978 planned: &Planned,
979 mutation_cache: &Path,
980 runtime: &str,
981 run_dir: &Path,
982) -> ProgrammaticResult<(Option<Arc<ResultCache>>, RunJournal)> {
983 let root = planned.resolved.root();
984 let name = planned.runner.name();
985 let files = key_files(
986 &planned.plan,
987 planned.runner_config.as_deref(),
988 &planned.runner_projects,
989 );
990 let result_cache = open_result_cache(
991 planned.resolved.no_cache,
992 mutation_cache,
993 root,
994 name,
995 files.clone(),
996 );
997 let keys = result_cache
998 .clone()
999 .unwrap_or_else(|| Arc::new(ResultCache::keys_only(mutation_cache, root, name, files)));
1000 let header = JournalHeader {
1001 journal_format: JOURNAL_FORMAT,
1002 fallow_version: env!("CARGO_PKG_VERSION").to_owned(),
1003 runner: name.to_owned(),
1004 runtime: runtime.to_owned(),
1005 run_dir: run_dir
1006 .file_name()
1007 .map(|hash| hash.to_string_lossy().into_owned())
1008 .unwrap_or_default(),
1009 runner_config: planned.runner_config.clone(),
1010 runner_projects: planned.runner_projects.clone(),
1011 scope: scope_label(options, planned.base_ref.as_deref(), root),
1012 operators: planned.operators.clone(),
1013 allow_side_effects: options.allow_side_effects,
1014 kill_matrix: options.kill_matrix,
1015 kill_matrix_targets: sorted_targets(&options.kill_matrix_targets),
1016 kill_matrix_full: options.kill_matrix_full,
1017 };
1018 let run_journal = start_journal(options, planned, mutation_cache, &header, keys)?;
1019 Ok((result_cache, run_journal))
1020}
1021
1022struct RunJournal {
1024 journal: Arc<Journal>,
1025 shown: String,
1027 note: Option<String>,
1029}
1030
1031fn start_journal(
1034 options: &MutationRunOptions,
1035 planned: &Planned,
1036 mutation_cache: &Path,
1037 header: &JournalHeader,
1038 keys: Arc<ResultCache>,
1039) -> ProgrammaticResult<RunJournal> {
1040 let shown = shown_path(planned.resolved.root(), &Journal::path(mutation_cache));
1041 let opened = Journal::open(mutation_cache, header, keys, options.resume)
1042 .map_err(|mismatch| resume_mismatch(&mismatch, &shown))?;
1043 Ok(RunJournal {
1044 journal: Arc::new(opened.journal),
1045 shown,
1046 note: opened.note,
1047 })
1048}
1049
1050fn settle_journal(
1053 options: &MutationRunOptions,
1054 run_journal: RunJournal,
1055 outcome: &mut ScheduleOutcome,
1056) -> Option<MutationResumeOutput> {
1057 if let Some(message) = run_journal.journal.write_error() {
1058 outcome.issues.push(ScheduleIssue {
1059 code: "journal-write-failed",
1060 message: format!(
1061 "the outcome journal was not written, so an interrupted run cannot resume each result: {message}"
1062 ),
1063 mutant_id: None,
1064 stderr_tail: None,
1065 });
1066 }
1067 options.resume.then(|| MutationResumeOutput {
1068 journal: run_journal.shown,
1069 reused: outcome
1070 .results
1071 .values()
1072 .filter(|result| result.resumed)
1073 .count(),
1074 rejected: run_journal.journal.rejected(),
1075 note: run_journal.note,
1076 })
1077}
1078
1079fn open_result_cache(
1081 no_cache: bool,
1082 mutation_cache: &Path,
1083 root: &Path,
1084 runner: &str,
1085 files: KeyFiles,
1086) -> Option<Arc<ResultCache>> {
1087 (!no_cache).then(|| Arc::new(ResultCache::open(mutation_cache, root, runner, files)))
1088}
1089
1090fn key_files(
1094 plan: &MutationPlan,
1095 runner_config: Option<&str>,
1096 runner_projects: &[String],
1097) -> KeyFiles {
1098 let mut files = KeyFiles {
1099 runner_projects: runner_projects.to_vec(),
1100 ..KeyFiles::from_plan(plan)
1101 };
1102 if let Some(config) = runner_config
1103 && !files.support_files.iter().any(|file| file == config)
1104 {
1105 files.support_files.push(config.to_owned());
1106 }
1107 files
1108}
1109
1110fn store_results(cache: &ResultCache, outcome: &mut ScheduleOutcome) -> MutationCacheOutput {
1113 let counts = cache.record(outcome);
1114 if let Err(message) = cache.save() {
1115 outcome.issues.push(ScheduleIssue {
1116 code: "cache-write-failed",
1117 message: format!("the mutation result cache was not saved: {message}"),
1118 mutant_id: None,
1119 stderr_tail: None,
1120 });
1121 }
1122 MutationCacheOutput {
1123 hits: counts.hits,
1124 stored: counts.stored,
1125 not_keyed: NOT_KEYED.iter().map(|&item| item.to_owned()).collect(),
1126 }
1127}
1128
1129pub(super) fn init_options(
1135 runner: Runner,
1136 root: &Path,
1137 static_test_files: &[String],
1138 projects: &[String],
1139) -> InitOptions {
1140 let node_args = match runner {
1141 Runner::NodeTest => node_test_args(root),
1142 Runner::Vitest | Runner::BunTest => Vec::new(),
1143 };
1144 let extra_test_files = match runner {
1145 Runner::NodeTest | Runner::BunTest => static_test_files.to_vec(),
1146 Runner::Vitest => Vec::new(),
1147 };
1148 InitOptions {
1149 extra_test_files,
1150 node_args,
1151 projects: projects.to_vec(),
1152 ..InitOptions::default()
1153 }
1154}
1155
1156fn runner_output(
1158 outcome: &ScheduleOutcome,
1159 name: &str,
1160 manifest: &Manifest,
1161 runtime: &JsRuntime,
1162) -> Option<MutationRunnerOutput> {
1163 outcome.ready.as_ref().map(|ready| MutationRunnerOutput {
1164 name: name.to_owned(),
1165 version: ready.runner_version.clone(),
1166 protocol_version: manifest.wire_protocol_version,
1167 runtime: MutationRuntimeOutput {
1168 name: runtime.kind.name().to_owned(),
1169 version: runtime.version.clone(),
1170 },
1171 concurrency: outcome.workers,
1172 notes: ready
1173 .notes
1174 .iter()
1175 .filter(|note| manifest.ready_notes.contains(note))
1176 .cloned()
1177 .collect(),
1178 })
1179}
1180
1181fn execute(
1183 options: &MutationRunOptions,
1184 planned: &Planned,
1185 deadline: Option<Instant>,
1186 progress: MutationProgressSink<'_>,
1187) -> ProgrammaticResult<Execution> {
1188 let plan = &planned.plan;
1189 let schedule = schedule_plan(plan);
1190 if schedule.mutants.is_empty()
1193 && (schedule.unreached.is_empty() || schedule.test_files.is_empty())
1194 {
1195 return Ok(Execution {
1196 outcome: None,
1197 runner: None,
1198 cache: None,
1199 resume: unread_journal(options, planned),
1200 setup_ms: 0,
1201 record: None,
1202 witness: None,
1203 });
1204 }
1205 progress(MutationProgress::Setup {
1206 mutants: schedule.mutants.len(),
1207 });
1208 let setup_started = Instant::now();
1209 let manifest = manifest()
1210 .map_err(|message| mutation_error("FALLOW_MUTATION_PROTOCOL_INVALID", message))?;
1211 let runner = planned.runner;
1212 let name = runner.name();
1213 let range = manifest.runner(name).ok_or_else(|| {
1214 mutation_error(
1215 "FALLOW_MUTATION_PROTOCOL_INVALID",
1216 format!("the protocol manifest has no `{name}` runner"),
1217 )
1218 })?;
1219 let runtime = discover_runtime(options.runtime.as_deref(), runner.runtimes())
1220 .map_err(|message| runtime_error(runner, message))?;
1221 let cache_error =
1222 |message: String| mutation_error("FALLOW_MUTATION_CACHE_WRITE_FAILED", message);
1223 ignore_cache_dir(&planned.cache_dir).map_err(|error| cache_error(error.to_string()))?;
1224 let mutation_cache = planned.cache_dir.join("mutation");
1225 let companion = install(&mutation_cache, COMPANION_FILES)
1226 .map_err(|message| mutation_error("FALLOW_MUTATION_COMPANION_INTEGRITY", message))?;
1227 let run_dir =
1228 write_run_dir(&mutation_cache, &run_files(plan), Some(&companion)).map_err(cache_error)?;
1229 let root = planned.resolved.root().to_path_buf();
1230 let runtime_label = format!("{} {}", runtime.kind.name(), runtime.version);
1231 let (result_cache, run_journal) = open_stores(
1232 options,
1233 planned,
1234 &mutation_cache,
1235 &runtime_label,
1236 &run_dir.dir,
1237 )?;
1238 let config = ScheduleConfig {
1239 init: InitRequest {
1240 root: root.to_string_lossy().into_owned(),
1241 runner: name.to_owned(),
1242 config_path: planned.runner_config.clone(),
1243 run_dir: run_dir.dir.to_string_lossy().into_owned(),
1244 path_map: run_dir.path_map.clone(),
1245 options: init_options(runner, &root, &plan.test_files, &planned.runner_projects),
1246 },
1247 runner: range.clone(),
1248 kill_matrix: options.kill_matrix,
1249 targets: options.kill_matrix_targets.clone(),
1250 target_full: options.kill_matrix_full,
1251 concurrency: options.concurrency.unwrap_or_else(default_concurrency),
1252 runner_timeout: options.runner_timeout.unwrap_or(DEFAULT_RUNNER_TIMEOUT),
1253 deadline,
1254 clock: Arc::new(SystemClock),
1255 cache: result_cache
1256 .clone()
1257 .map(|cache| cache as Arc<dyn ResultLookup>),
1258 journal: Some(Arc::clone(&run_journal.journal) as Arc<dyn OutcomeJournal>),
1259 };
1260 let spawner = ProcessSpawner {
1261 runtime: runtime.path.clone(),
1262 companion,
1263 root,
1264 wire_version: manifest.wire_protocol_version,
1265 session_token_env: manifest.session_token_env.clone(),
1266 };
1267 let setup_ms = millis(setup_started.elapsed());
1268 let mut outcome = run_schedule_with_progress(&spawner, &schedule, &config, progress)
1269 .map_err(|error| schedule_error(&error, &config.runner, config.runner_timeout))?;
1270 let runner = runner_output(&outcome, name, manifest, &runtime);
1271 let cache = (outcome.ready.is_some())
1272 .then(|| result_cache.map(|result_cache| store_results(&result_cache, &mut outcome)))
1273 .flatten();
1274 let resume = settle_journal(options, run_journal, &mut outcome);
1275 let (record, witness) = record_and_search(options, &outcome, spawner, &config, &mutation_cache);
1276 Ok(Execution {
1277 record,
1278 witness,
1279 outcome: Some(outcome),
1280 runner,
1281 cache,
1282 resume,
1283 setup_ms,
1284 })
1285}
1286
1287fn run_issues(
1289 plan: &MutationPlan,
1290 outcome: Option<&ScheduleOutcome>,
1291 changed_paths: &[String],
1292 check_error: Option<String>,
1293) -> Vec<fallow_output::MutationRunIssue> {
1294 let mut errors = issues(outcome);
1295 errors.extend(skipped_tests_issue(plan));
1296 if !changed_paths.is_empty() {
1297 errors.push(fallow_output::MutationRunIssue {
1298 code: "worktree-changed".to_owned(),
1299 message: format!(
1300 "the run changed {} worktree {}; a mutant or a test wrote to the project",
1301 changed_paths.len(),
1302 path_noun(changed_paths.len())
1303 ),
1304 mutant_id: None,
1305 stderr_tail: None,
1306 });
1307 }
1308 if let Some(message) = check_error {
1309 errors.push(fallow_output::MutationRunIssue {
1310 code: "worktree-check-failed".to_owned(),
1311 message: format!(
1312 "the end-of-run worktree check failed, so stray writes are unknown: {message}"
1313 ),
1314 mutant_id: None,
1315 stderr_tail: None,
1316 });
1317 }
1318 errors
1319}
1320
1321fn run_timings(
1324 outcome: Option<&ScheduleOutcome>,
1325 setup_ms: u64,
1326 plan_ms: u64,
1327 typecheck_ms: u64,
1328) -> MutationTimings {
1329 outcome.map_or_else(
1330 || MutationTimings {
1331 plan_ms,
1332 typecheck_ms,
1333 ..MutationTimings::default()
1334 },
1335 |outcome| MutationTimings {
1336 plan_ms,
1337 setup_ms: setup_ms + millis(outcome.timings.setup),
1338 dry_run_ms: millis(outcome.timings.dry_run),
1339 mutants_ms: millis(outcome.timings.mutants),
1340 retry_ms: millis(outcome.timings.retry),
1341 typecheck_ms,
1342 },
1343 )
1344}
1345
1346fn guard_typecheck_companion(enabled: bool, root: &Path) -> ProgrammaticResult<()> {
1349 if !enabled {
1350 return Ok(());
1351 }
1352 crate::type_aware::check_typecheck_companion(root).map_err(|message| {
1353 mutation_error("FALLOW_MUTATION_TYPECHECK_UNAVAILABLE", message)
1354 .with_help("install the fallow-type-aware companion, or run without --typecheck")
1355 .with_context("mutation.typecheck")
1356 })
1357}
1358
1359pub fn run_mutation(options: &MutationRunOptions) -> ProgrammaticResult<MutationReport> {
1373 run_mutation_with_progress(options, &|_| {})
1374}
1375
1376fn worktree_check(
1379 start: Option<&WorktreeSnapshot>,
1380 allow_dirty: bool,
1381 changed_paths: Vec<String>,
1382) -> MutationWorktreeCheck {
1383 MutationWorktreeCheck {
1384 checked: start.is_some(),
1385 allow_dirty,
1386 dirty_at_start: start.map(WorktreeSnapshot::dirty_paths).unwrap_or_default(),
1387 changed_paths,
1388 }
1389}
1390
1391pub fn run_mutation_with_progress(
1401 options: &MutationRunOptions,
1402 progress: MutationProgressSink<'_>,
1403) -> ProgrammaticResult<MutationReport> {
1404 let started = Instant::now();
1405 let deadline = options.time_budget.map(|budget| started + budget);
1406 let mut start_snapshot = None;
1407 let planned = plan_for(options, |root, cache_dir| {
1408 guard_cache_dir(root, cache_dir)?;
1409 start_snapshot = take_worktree_snapshot(root, cache_dir, &options.output_paths, None)?;
1410 if options.test_changes_only && !options.allow_dirty && start_snapshot.is_some() {
1411 return Ok(());
1412 }
1413 guard_worktree(options.allow_dirty, start_snapshot.as_ref())
1414 })?;
1415 guard_planned(options, &planned, start_snapshot.as_ref())?;
1416 let normalized = with_normalized_targets(options, planned.resolved.root())?;
1417 let options = normalized.as_ref().unwrap_or(options);
1418 let plan_ms = millis(started.elapsed());
1419 let execution = execute(options, &planned, deadline, progress);
1420 progress(MutationProgress::Finalize);
1421 let settle = || {
1422 settle_worktree(start_snapshot.as_ref(), |start| {
1423 take_worktree_snapshot(
1424 planned.resolved.root(),
1425 &planned.cache_dir,
1426 &options.output_paths,
1427 Some(start),
1428 )
1429 })
1430 };
1431 let execution = execution.map_err(|error| with_worktree_facts(error, &settle()))?;
1432 let plan = &planned.plan;
1433 let outcome = execution.outcome.as_ref();
1434 let mut results = mutant_results(plan, outcome);
1435 let typecheck = typecheck_survivors(
1436 options.typecheck,
1437 planned.resolved.root(),
1438 plan,
1439 &mut results,
1440 );
1441 let typecheck_ms = millis(typecheck.elapsed);
1442 let recording = recording_and_witnesses(options, &planned, &execution, &mut results);
1443 let WorktreeEnd {
1446 changed_paths,
1447 check_error,
1448 } = settle();
1449 let baseline = baseline_failures(outcome);
1450 let completion = completion(&CompletionFacts {
1451 plan,
1452 results: &results,
1453 baseline_failures: &baseline,
1454 worktree_changed: !changed_paths.is_empty(),
1455 worktree_unchecked: check_error.is_some(),
1456 unretried: outcome.is_some_and(|outcome| !outcome.unretried.is_empty()),
1457 unloaded_paths: outcome.map_or(&[], |outcome| outcome.unloaded_paths.as_slice()),
1458 undiscovered_test_files: outcome
1459 .map_or(&[], |outcome| outcome.undiscovered_test_files.as_slice()),
1460 typecheck_failed: typecheck.issue.is_some(),
1461 promoted: outcome.map_or(&[], |outcome| outcome.promoted.as_slice()),
1462 });
1463 let mut errors = run_issues(plan, outcome, &changed_paths, check_error);
1464 errors.extend(typecheck.issue);
1465 let timings = run_timings(outcome, execution.setup_ms, plan_ms, typecheck_ms);
1466 let mut report = MutationReport {
1467 schema_version: MutationSchemaVersion::V2,
1468 version: tool_version(),
1469 elapsed_ms: ElapsedMs(millis(started.elapsed())),
1470 kill_matrix: crate::mutation::kill_matrix::build(
1471 &kill_matrix_mode(options, outcome),
1472 &results,
1473 &baseline,
1474 &completion,
1475 &plan.mutants,
1476 outcome.map(|outcome| &outcome.test_files),
1477 ),
1478 completion,
1479 scope: scope_output(options, planned.base_ref.clone()),
1480 runner: execution.runner,
1481 cache: execution.cache,
1482 resume: execution.resume,
1483 summary: summary(&results),
1484 functions: function_results(plan, &results),
1485 mutants: results,
1486 no_test_files: plan.no_test_files,
1487 baseline_failures: baseline,
1488 skipped_files: skipped_files(plan),
1489 unmatched_paths: unmatched_paths(plan),
1490 unmatched_path_reasons: unmatched_path_reasons(plan, planned.resolved.root()),
1491 unloaded_paths: outcome.map_or_else(Vec::new, |outcome| outcome.unloaded_paths.clone()),
1492 worktree: worktree_check(start_snapshot.as_ref(), options.allow_dirty, changed_paths),
1493 errors,
1494 timings,
1495 files: plan_files(plan),
1496 verdicts: None,
1497 typecheck: typecheck.output,
1498 recheck: None,
1499 compare: None,
1500 gate_outcomes: None,
1501 recording,
1502 };
1503 report.withhold_target_first_scores();
1504 Ok(report)
1505}
1506
1507#[cfg(test)]
1508mod tests {
1509 use super::*;
1510
1511 fn vitest_range() -> &'static RunnerRange {
1512 manifest()
1513 .expect("manifest")
1514 .runner("vitest")
1515 .expect("vitest range")
1516 }
1517
1518 #[test]
1519 fn a_runner_version_error_names_the_supported_range_as_the_install_step() {
1520 let error = schedule_error(
1521 &ScheduleError::RunnerVersion(
1522 "vitest 4.0.18 is not supported; the supported range is >=4.1.0 <6.0.0".to_owned(),
1523 ),
1524 vitest_range(),
1525 Duration::from_secs(120),
1526 );
1527 assert_eq!(
1528 error.code.as_deref(),
1529 Some("FALLOW_MUTATION_RUNNER_UNSUPPORTED")
1530 );
1531 assert_eq!(
1532 error.help.as_deref(),
1533 Some(
1534 "install vitest 4.1.0 or a later version below 6.0.0; a vitest 4.x release from 4.1.0 is in the range"
1535 )
1536 );
1537
1538 let help: Vec<String> = manifest()
1539 .expect("manifest")
1540 .runners
1541 .iter()
1542 .map(runner_version_help)
1543 .collect();
1544 assert_eq!(
1545 help,
1546 [
1547 "install vitest 4.1.0 or a later version below 6.0.0; a vitest 4.x release from 4.1.0 is in the range",
1548 "install node 22.18.0 or a later version below 27.0.0; a node 22.x release from 22.18.0 is in the range",
1549 "install bun 1.4.0 or a later version below 2.0.0; a bun 1.x release from 1.4.0 is in the range",
1550 ]
1551 );
1552
1553 let major_start = RunnerRange {
1554 name: "vitest".to_owned(),
1555 package: "vitest".to_owned(),
1556 min_version: "5.0.0".to_owned(),
1557 max_version_exclusive: "6.0.0".to_owned(),
1558 };
1559 assert_eq!(
1560 runner_version_help(&major_start),
1561 "install vitest 5.0.0 or a later version below 6.0.0"
1562 );
1563 }
1564
1565 #[test]
1566 fn a_setup_watchdog_error_names_the_setup_timeout_flag() {
1567 let error = schedule_error(
1568 &ScheduleError::Setup {
1569 message: "the mutation companion dry_run failed".to_owned(),
1570 stderr_tail: Some("vitest started\n".to_owned()),
1571 timed_out: true,
1572 },
1573 vitest_range(),
1574 Duration::from_secs(120),
1575 );
1576 let help = error.help.as_deref().unwrap_or_default();
1577 assert!(help.contains("longer than 120s"), "{help}");
1578 assert!(help.contains("--setup-timeout"), "{help}");
1579 assert!(help.contains("companion stderr:\nvitest started"), "{help}");
1580
1581 let other = schedule_error(
1582 &ScheduleError::Setup {
1583 message: "the mutation companion init failed".to_owned(),
1584 stderr_tail: None,
1585 timed_out: false,
1586 },
1587 vitest_range(),
1588 Duration::from_secs(120),
1589 );
1590 assert_eq!(other.help, None);
1591 }
1592
1593 #[test]
1594 fn a_duplicate_target_test_id_exits_2_and_names_the_id() {
1595 let error = schedule_error(
1596 &ScheduleError::DuplicateTargetTestIds(vec!["test/a.test.ts::adds".to_owned()]),
1597 vitest_range(),
1598 Duration::from_secs(120),
1599 );
1600 assert_eq!(
1601 error.code.as_deref(),
1602 Some("FALLOW_MUTATION_TARGET_DUPLICATE_TEST_ID")
1603 );
1604 assert_eq!(error.exit_code, 2);
1605 assert!(
1606 error.message.contains("test/a.test.ts::adds"),
1607 "{}",
1608 error.message
1609 );
1610 assert!(error.message.contains("not reliable"), "{}", error.message);
1611 }
1612
1613 #[test]
1614 fn a_failed_self_check_is_a_runner_failure_with_its_own_help() {
1615 let error = schedule_error(
1616 &ScheduleError::RunPath {
1617 message: "vitest 5.0.4 executes no tests in a mutant run".to_owned(),
1618 help: "report this with the runner name and version (vitest 5.0.4)".to_owned(),
1619 },
1620 vitest_range(),
1621 Duration::from_secs(120),
1622 );
1623 assert_eq!(error.code.as_deref(), Some("FALLOW_MUTATION_RUNNER_FAILED"));
1624 assert_eq!(error.exit_code, 2);
1625 assert_eq!(
1626 error.message,
1627 "vitest 5.0.4 executes no tests in a mutant run"
1628 );
1629 assert_eq!(
1630 error.help.as_deref(),
1631 Some("report this with the runner name and version (vitest 5.0.4)")
1632 );
1633 }
1634
1635 #[test]
1636 fn a_failed_end_check_keeps_the_execute_error_and_reports_the_check_error() {
1637 let start = WorktreeSnapshot::default();
1638 let end = settle_worktree(Some(&start), |_| {
1639 Err(mutation_error(
1640 "FALLOW_MUTATION_WORKTREE_CHECK_FAILED",
1641 "git status failed",
1642 ))
1643 });
1644 assert!(end.changed_paths.is_empty());
1645 assert_eq!(end.check_error.as_deref(), Some("git status failed"));
1646
1647 let error = with_worktree_facts(
1648 mutation_error(
1649 "FALLOW_MUTATION_SETUP_FAILED",
1650 "the companion did not start",
1651 ),
1652 &end,
1653 );
1654 assert_eq!(error.code.as_deref(), Some("FALLOW_MUTATION_SETUP_FAILED"));
1655 assert!(
1656 error.message.starts_with("the companion did not start"),
1657 "{}",
1658 error.message
1659 );
1660 assert!(
1661 error.message.contains("git status failed"),
1662 "{}",
1663 error.message
1664 );
1665 }
1666
1667 #[test]
1668 fn every_config_operator_name_maps_to_an_engine_operator() {
1669 for operator in fallow_engine::mutation::Operator::ALL {
1670 let name: fallow_config::MutationOperatorName =
1671 serde_json::from_value(serde_json::json!(operator.as_str()))
1672 .expect("a config operator name");
1673 assert_eq!(
1674 fallow_engine::mutation::Operator::from_name(name.as_str()),
1675 Some(operator)
1676 );
1677 }
1678 }
1679
1680 #[test]
1681 fn no_cache_opens_no_result_cache() {
1682 let dir = tempfile::tempdir().expect("dir");
1683 let plan = MutationPlan {
1684 files: Vec::new(),
1685 mutants: Vec::new(),
1686 test_files: Vec::new(),
1687 reach_files: Vec::new(),
1688 test_file_reach: std::collections::BTreeMap::new(),
1689 support_files: Vec::new(),
1690 counts: fallow_engine::mutation::MutationPlanCounts::default(),
1691 no_test_files: false,
1692 framework_config_checked: false,
1693 skipped_files: Vec::new(),
1694 unmatched_paths: Vec::new(),
1695 skipped_tests: Vec::new(),
1696 };
1697 assert!(
1698 open_result_cache(
1699 true,
1700 dir.path(),
1701 dir.path(),
1702 "vitest",
1703 KeyFiles::from_plan(&plan)
1704 )
1705 .is_none()
1706 );
1707 assert!(
1708 open_result_cache(
1709 false,
1710 dir.path(),
1711 dir.path(),
1712 "vitest",
1713 KeyFiles::from_plan(&plan)
1714 )
1715 .is_some()
1716 );
1717 }
1718
1719 fn empty_plan() -> MutationPlan {
1720 MutationPlan {
1721 files: Vec::new(),
1722 mutants: Vec::new(),
1723 test_files: Vec::new(),
1724 reach_files: Vec::new(),
1725 test_file_reach: std::collections::BTreeMap::new(),
1726 support_files: Vec::new(),
1727 counts: fallow_engine::mutation::MutationPlanCounts::default(),
1728 no_test_files: false,
1729 framework_config_checked: false,
1730 skipped_files: Vec::new(),
1731 unmatched_paths: Vec::new(),
1732 skipped_tests: Vec::new(),
1733 }
1734 }
1735
1736 #[test]
1737 fn an_unmatched_path_reason_is_root_relative_at_the_index_of_its_path() {
1738 use fallow_engine::mutation::{UnmatchedPath, UnmatchedReason};
1739 let root = Path::new("/project");
1740 let mut plan = empty_plan();
1741 plan.unmatched_paths = vec![
1742 UnmatchedPath {
1743 path: "/project/pkg".to_owned(),
1744 reason: UnmatchedReason::Ignored,
1745 },
1746 UnmatchedPath {
1747 path: "./src/missing.ts".to_owned(),
1748 reason: UnmatchedReason::NotFound,
1749 },
1750 ];
1751 let paths = unmatched_paths(&plan);
1752 let reasons = unmatched_path_reasons(&plan, root);
1753 assert_eq!(paths, vec!["/project/pkg", "./src/missing.ts"]);
1754 assert_eq!(
1755 reasons,
1756 vec![
1757 MutationUnmatchedPath {
1758 path: "pkg".to_owned(),
1759 reason: "ignored".to_owned(),
1760 },
1761 MutationUnmatchedPath {
1762 path: "src/missing.ts".to_owned(),
1763 reason: "not-found".to_owned(),
1764 },
1765 ]
1766 );
1767 }
1768
1769 #[test]
1770 fn a_cache_dir_at_or_above_the_root_is_refused() {
1771 let dir = tempfile::tempdir().expect("dir");
1772 let root = dir.path().join("project");
1773 std::fs::create_dir_all(root.join("src")).expect("dir");
1774 for cache in [root.clone(), root.join("."), dir.path().to_path_buf()] {
1775 let error = guard_cache_dir(&root, &cache).expect_err("refused");
1776 assert_eq!(
1777 error.code.as_deref(),
1778 Some("FALLOW_MUTATION_UNSAFE_CACHE_DIR")
1779 );
1780 assert_eq!(error.exit_code, 2);
1781 assert_eq!(error.context.as_deref(), Some("cache.dir"));
1782 }
1783 assert!(guard_cache_dir(&root, &root.join(".fallow")).is_ok());
1784 assert!(guard_cache_dir(&root, &root.join("src")).is_ok());
1785 }
1786
1787 #[test]
1788 fn a_cache_dir_that_holds_a_planned_file_is_refused() {
1789 let dir = tempfile::tempdir().expect("dir");
1790 let root = dir.path();
1791 let mut plan = empty_plan();
1792 plan.files.push(fallow_engine::mutation::PlannedFile {
1793 path: "src/a.ts".to_owned(),
1794 source_sha256: String::new(),
1795 instrumented_code: String::new(),
1796 static_test_files: Vec::new(),
1797 });
1798 plan.test_files.push("test/a.test.ts".to_owned());
1799
1800 let error = guard_cache_holds_no_planned_file(root, &root.join("src"), &plan)
1801 .expect_err("the cache holds a planned source file");
1802 assert_eq!(
1803 error.code.as_deref(),
1804 Some("FALLOW_MUTATION_UNSAFE_CACHE_DIR")
1805 );
1806 assert!(error.message.contains("src/a.ts"), "{}", error.message);
1807 let error = guard_cache_holds_no_planned_file(root, &root.join("test"), &plan)
1808 .expect_err("the cache holds a planned test file");
1809 assert!(
1810 error.message.contains("test/a.test.ts"),
1811 "{}",
1812 error.message
1813 );
1814 assert!(guard_cache_holds_no_planned_file(root, &root.join(".fallow"), &plan).is_ok());
1815 }
1816
1817 #[test]
1818 fn kill_matrix_targets_take_the_form_of_runner_test_ids() {
1819 let root = Path::new("/project");
1820 assert_eq!(normalize_target(root, "./test/a.test.ts"), "test/a.test.ts");
1821 assert_eq!(
1822 normalize_target(root, "test\\a.test.ts::adds > two"),
1823 "test/a.test.ts::adds > two"
1824 );
1825 if cfg!(unix) {
1826 assert_eq!(
1827 normalize_target(root, "/project/test/a.test.ts::a::b"),
1828 "test/a.test.ts::a::b"
1829 );
1830 assert_eq!(
1831 normalize_target(root, "/other/a.test.ts"),
1832 "/other/a.test.ts"
1833 );
1834 }
1835 }
1836
1837 #[test]
1838 fn a_target_that_normalizes_to_no_file_is_refused_and_order_does_not_matter() {
1839 let root = Path::new("/project");
1840 for raw in ["./", "././", "::name"] {
1841 let options = MutationRunOptions {
1842 kill_matrix_targets: vec![raw.to_owned()],
1843 ..MutationRunOptions::default()
1844 };
1845 let error = with_normalized_targets(&options, root).expect_err(raw);
1846 assert!(error.message.contains("names no test file"), "{raw}");
1847 }
1848 let options = MutationRunOptions {
1849 kill_matrix_targets: vec!["./b.test.ts".to_owned(), "b.test.ts".to_owned()],
1850 ..MutationRunOptions::default()
1851 };
1852 let normalized = with_normalized_targets(&options, root)
1853 .expect("valid")
1854 .expect("target mode");
1855 assert_eq!(normalized.kill_matrix_targets, ["b.test.ts"]);
1856 assert_eq!(
1857 sorted_targets(&["b".to_owned(), "a".to_owned()]),
1858 sorted_targets(&["a".to_owned(), "b".to_owned()])
1859 );
1860 }
1861
1862 #[test]
1863 fn the_full_and_the_target_kill_matrix_are_exclusive() {
1864 let both = MutationRunOptions {
1865 kill_matrix: true,
1866 kill_matrix_targets: vec!["test/a.test.ts".to_owned()],
1867 ..MutationRunOptions::default()
1868 };
1869 assert!(validate(&both).is_err());
1870 let blank = MutationRunOptions {
1871 kill_matrix_targets: vec![" ".to_owned()],
1872 ..MutationRunOptions::default()
1873 };
1874 assert!(validate(&blank).is_err());
1875 }
1876
1877 #[test]
1878 fn no_start_snapshot_needs_no_end_check() {
1879 let end = settle_worktree(None, |_| panic!("no end check without a start snapshot"));
1880 assert!(end.changed_paths.is_empty());
1881 assert!(end.check_error.is_none());
1882 }
1883
1884 #[test]
1885 fn the_glob_runners_get_the_static_test_files_and_vitest_does_not() {
1886 let dir = tempfile::tempdir().expect("dir");
1887 let files = vec![".github/tests/math.test.mjs".to_owned()];
1888 for runner in [Runner::NodeTest, Runner::BunTest] {
1889 let options = init_options(runner, dir.path(), &files, &[]);
1890 assert_eq!(options.extra_test_files, files, "{runner:?}");
1891 assert!(options.test_files.is_empty(), "{runner:?}");
1892 }
1893 let vitest = init_options(Runner::Vitest, dir.path(), &files, &[]);
1894 assert!(vitest.extra_test_files.is_empty());
1895 }
1896
1897 #[test]
1898 fn vitest_gets_the_selected_projects() {
1899 let dir = tempfile::tempdir().expect("dir");
1900 let projects = vec!["unit".to_owned(), "api-*".to_owned()];
1901 let vitest = init_options(Runner::Vitest, dir.path(), &[], &projects);
1902 assert_eq!(vitest.projects, projects);
1903 let wire = serde_json::to_value(&vitest).expect("serialize");
1904 assert_eq!(wire["projects"], serde_json::json!(["unit", "api-*"]));
1905 let none = serde_json::to_value(init_options(Runner::Vitest, dir.path(), &[], &[]))
1906 .expect("serialize");
1907 assert!(none.get("projects").is_none(), "{none}");
1908 }
1909
1910 #[test]
1911 fn equal_scopes_and_operators_give_one_fingerprint() {
1912 let root = Path::new("/project");
1913 let paths = |paths: &[&str]| MutationRunOptions {
1914 scope: MutationRunScope::Paths(paths.iter().map(PathBuf::from).collect()),
1915 ..MutationRunOptions::default()
1916 };
1917 let label = scope_label(&paths(&["src/a", "lib"]), None, root);
1918 for same in [
1919 paths(&["./src/a", "lib"]),
1920 paths(&["lib/", "src/a"]),
1921 paths(&["/project/src/a", "lib", "./lib"]),
1922 ] {
1923 assert_eq!(scope_label(&same, None, root), label, "{:?}", same.scope);
1924 }
1925 assert_ne!(scope_label(&paths(&["src/b"]), None, root), label);
1926
1927 use fallow_engine::mutation::Operator;
1928 let names = operator_names(&[
1929 Operator::RelationalOperator,
1930 Operator::ArithmeticOperator,
1931 Operator::RelationalOperator,
1932 ]);
1933 assert_eq!(
1934 names,
1935 operator_names(&[Operator::ArithmeticOperator, Operator::RelationalOperator,])
1936 );
1937 }
1938}