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