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