1use std::cell::RefCell;
8use std::collections::{BTreeMap, BTreeSet, HashSet};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use anyhow::{Context, Result, anyhow, bail};
16
17use crate::checkpoint::{Checkpoint, Phase};
18use crate::instrument::{self, RUNTIME_MOD, Rendered, Site, SiteKind};
19use crate::output_fixture::{self, Fixture};
20use crate::plan::{self, Mutation};
21use crate::propagation::Change;
22use crate::report::{self, Finding, Report};
23use crate::scope::{self};
24use crate::trace::Trace;
25use crate::work_lock::WorkLock;
26use crate::{git_index, leftovers, progress, reverts, witness};
27
28pub use runner::summarize_baseline_log;
29
30#[derive(Debug)]
32pub enum BaselineError {
33 Timeout {
34 diagnostic: Box<report::BaselineTimeoutDiagnostic>,
35 wrapper_grace_outcomes: Option<report::WrapperGraceOutcomes>,
36 message: String,
37 },
38 Failed {
39 diagnostic: Box<report::BaselineFailureDiagnostic>,
40 wrapper_grace_outcomes: Option<report::WrapperGraceOutcomes>,
41 message: String,
42 },
43}
44
45impl BaselineError {
46 pub fn to_report(&self) -> report::BaselineErrorReport {
48 match self {
49 Self::Timeout {
50 diagnostic,
51 wrapper_grace_outcomes,
52 message,
53 } => report::BaselineErrorReport {
54 schema_version: report::SCHEMA_VERSION,
55 package: diagnostic.package.clone(),
56 evaluation: report::Evaluation::BaselineFailed,
57 error: message.clone(),
58 wrapper_grace_outcomes: *wrapper_grace_outcomes,
59 baseline_timeout: Some((**diagnostic).clone()),
60 baseline_failure: None,
61 },
62 Self::Failed {
63 diagnostic,
64 wrapper_grace_outcomes,
65 message,
66 } => report::BaselineErrorReport {
67 schema_version: report::SCHEMA_VERSION,
68 package: diagnostic.package.clone(),
69 evaluation: report::Evaluation::BaselineFailed,
70 error: message.clone(),
71 wrapper_grace_outcomes: *wrapper_grace_outcomes,
72 baseline_timeout: None,
73 baseline_failure: Some((**diagnostic).clone()),
74 },
75 }
76 }
77}
78
79impl std::fmt::Display for BaselineError {
80 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
81 match self {
82 Self::Timeout { message, .. } | Self::Failed { message, .. } => f.write_str(message),
83 }
84 }
85}
86
87impl std::error::Error for BaselineError {}
88
89fn round_millis(d: Duration) -> f64 {
90 (d.as_secs_f64() * 1000.0).round() / 1000.0
91}
92
93fn format_baseline_timings_section(
94 completed: &[report::BaselineTimingEntry],
95 failed_runner: &str,
96 failed_elapsed: f64,
97 failed_label: &str,
98 total: usize,
99) -> String {
100 if completed.is_empty() && total <= 1 {
101 return String::new();
102 }
103 const MAX_DISPLAY: usize = 10;
104 let mut out = format!(
105 "\nbaseline timings ({}/{} completed):",
106 completed.len(),
107 total
108 );
109 for entry in completed.iter().take(MAX_DISPLAY) {
110 out.push_str(&format!(
111 "\n {}: {:.3}s",
112 entry.runner, entry.elapsed_seconds
113 ));
114 }
115 if completed.len() > MAX_DISPLAY {
116 out.push_str(&format!(
117 "\n ... and {} more completed",
118 completed.len() - MAX_DISPLAY
119 ));
120 }
121 let prefix = if failed_label == "timed out" { ">" } else { "" };
122 out.push_str(&format!(
123 "\n {failed_runner}: {prefix}{failed_elapsed:.3}s ({failed_label})"
124 ));
125 out
126}
127
128fn format_log_summary_section(summary: &[String]) -> String {
129 if summary.is_empty() {
130 return String::new();
131 }
132 let mut out = String::from("\nlog summary:");
133 for line in summary {
134 out.push_str("\n ");
135 out.push_str(line);
136 }
137 out
138}
139
140#[derive(Clone)]
141pub struct Options {
142 pub dir: PathBuf,
144 pub package: Option<String>,
145 pub list: bool,
147 pub test_workspace: bool,
149 pub verify: bool,
151 pub work_dir: Option<PathBuf>,
153 pub progress: bool,
155 pub since: Option<String>,
157 pub lines: Vec<String>,
159 pub exclude_files: Vec<String>,
161 pub baseline: Option<PathBuf>,
163 pub write_baseline: Option<PathBuf>,
165 pub also_test: Vec<String>,
167 pub dependents: bool,
169 pub effects: bool,
171 pub rebuild: bool,
173 pub error_values: Vec<String>,
175 pub source_only: bool,
176 pub literal_operators: bool,
177 pub shard: Option<report::Shard>,
178 pub nextest: Option<report::Nextest>,
179 pub test_selection: TestSelection,
180 pub opt_level: Option<u8>,
182 pub timeout_seconds: Option<u64>,
184 pub baseline_timeout_seconds: Option<u64>,
186 pub baseline_jobs: usize,
187 pub serial_timeout_rechecks: bool,
188 pub wrapper_grace: Duration,
189 pub audit: Option<usize>,
191 pub cargo: CargoConfig,
193 pub jobs: usize,
195 pub all_files: bool,
197 pub git_index: bool,
198 pub copy_fixtures: Vec<PathBuf>,
199 pub copy_fixture_excludes: Vec<PathBuf>,
200 pub output_fixtures: Vec<Fixture>,
201 pub stage_external: Vec<StageExternal>,
202 pub checkpoint: bool,
203 pub doc: bool,
205}
206
207#[derive(Clone, Default)]
208pub struct TestSelection {
209 pub isolate: bool,
210 pub lib: bool,
211 pub bins: bool,
212 pub integration_tests: Vec<String>,
213 pub targets: Vec<String>,
214 pub include: Vec<String>,
215 pub filter: Vec<String>,
216 pub exclude: Vec<String>,
217 pub include_ignored: bool,
218 pub wrapper: Option<PathBuf>,
219}
220
221impl TestSelection {
222 pub(crate) fn has_target_filters(&self) -> bool {
223 self.lib || self.bins || !self.integration_tests.is_empty() || !self.targets.is_empty()
224 }
225
226 fn enabled(&self) -> bool {
227 self.isolate
228 || self.has_target_filters()
229 || !self.include.is_empty()
230 || !self.filter.is_empty()
231 || !self.exclude.is_empty()
232 || self.include_ignored
233 || self.wrapper.is_some()
234 }
235
236 pub(crate) fn matches_test(&self, test: &str, was_ignored: bool) -> bool {
237 if was_ignored && !self.include_ignored {
238 return false;
239 }
240 if self.exclude.iter().any(|name| name == test) {
241 return false;
242 }
243 if !self.include.is_empty() || !self.filter.is_empty() {
244 let exact = self.include.iter().any(|name| name == test);
245 let partial = self.filter.iter().any(|pat| test.contains(pat));
246 if !exact && !partial {
247 return false;
248 }
249 }
250 true
251 }
252}
253
254pub use crate::report::CargoConfig;
255pub use workcopy::StageExternal;
256
257impl CargoConfig {
258 pub fn flags(&self) -> Vec<String> {
260 let mut flags = vec![];
261 if !self.features.is_empty() {
262 flags.extend(["--features".to_string(), self.features.join(",")]);
263 }
264 for (on, flag) in [
265 (self.all_features, "--all-features"),
266 (self.no_default_features, "--no-default-features"),
267 (self.locked, "--locked"),
268 ] {
269 if on {
270 flags.push(flag.to_string());
271 }
272 }
273 flags
274 }
275}
276
277const NEARBY_LINES: usize = 6;
280const WORK_MARKER: &str = ".tmt-work-dir";
282const STD_ALIAS: &str = "__tmt_std";
284const MAX_REPAIR_ROUNDS: usize = 40;
286const MAX_TEST_FILTERS: usize = 200;
288
289mod cargo;
290mod repair_cache;
291mod runner;
292mod scope_blame;
293mod session;
294mod witness_runner;
295mod workcopy;
296
297use cargo::*;
298use runner::*;
299use scope_blame::*;
300use session::*;
301use witness_runner::*;
302use workcopy::*;
303
304struct SourceFile {
305 display: String,
307 path: PathBuf,
309 owners: BTreeSet<PathBuf>,
310 original: String,
311 lines: scope::LineIndex,
312 sites: Vec<Site>,
313 rebuild_sites: Vec<Site>,
315 places: Vec<(usize, usize, String)>,
318 rendered: Option<Rendered>,
319}
320
321fn write_rendered(
322 file: &mut SourceFile,
323 state: &WorkCopy,
324 suffix: &str,
325 disabled: &HashSet<u32>,
326 newly_disabled: &HashSet<u32>,
327) -> Result<()> {
328 if file.rendered.is_none()
329 || file
330 .sites
331 .iter()
332 .any(|site| newly_disabled.contains(&site.id))
333 {
334 file.rendered = Some(instrument::render(&file.original, &file.sites, &|id| {
335 !disabled.contains(&id)
336 }));
337 }
338 let rendered = file.rendered.as_ref().expect("rendered before writing");
339 if suffix.is_empty() {
340 state.write(&file.path, &rendered.text)
341 } else {
342 state.write(&file.path, &format!("{}{suffix}", rendered.text))
343 }
344}
345
346#[derive(Clone, Copy)]
347struct WorkspaceShard {
348 offset: usize,
349 total: usize,
350 member_total: usize,
351}
352
353struct CatalogueSnapshot {
354 path: PathBuf,
355 ready: std::cell::Cell<bool>,
356 _lock: WorkLock,
357}
358
359struct WorkspaceBatch<'a> {
360 metadata: &'a Metadata,
361 work: &'a Path,
362 catalogue: Option<CatalogueSnapshot>,
363}
364
365pub fn select_single_package_name(dir: &Path, cargo: &CargoConfig) -> Option<String> {
368 let canon = dir.canonicalize().ok()?;
369 let metadata = cargo_metadata(&canon, cargo).ok()?;
370 metadata
371 .packages
372 .iter()
373 .find(|p| p.manifest_path.parent() == Some(canon.as_path()))
374 .or(match &metadata.packages[..] {
375 [only] => Some(only),
376 _ => None,
377 })
378 .map(|p| p.name.clone())
379}
380
381pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
383 run_packages_with(options, names, |_, base| Ok(base.clone()))
384}
385
386pub fn run_packages_with(
388 options: &Options,
389 names: &[String],
390 options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
391) -> Result<Vec<(String, Result<Report>)>> {
392 let mut reports = vec![];
393 run_packages_each_with(options, names, options_for_package, |name, result| {
394 reports.push((name, result));
395 Ok(())
396 })?;
397 Ok(reports)
398}
399
400pub fn run_packages_each(
402 options: &Options,
403 names: &[String],
404 completed: impl FnMut(String, Result<Report>) -> Result<()>,
405) -> Result<()> {
406 run_packages_each_with(options, names, |_, base| Ok(base.clone()), completed)
407}
408
409pub fn run_packages_each_with(
412 options: &Options,
413 names: &[String],
414 mut options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
415 mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
416) -> Result<()> {
417 let dir = options
418 .dir
419 .canonicalize()
420 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
421 if dir.is_file() {
422 let given = crate::report::sanitize_inline(&options.dir.display().to_string());
423 bail!(
424 "`{given}` is a file, not a Cargo package directory; pass the workspace/package directory and `--lines <path-relative-to-package-or-workspace>` to analyse a single file"
425 );
426 }
427 let metadata = cargo_metadata(&dir, &options.cargo)?;
428 let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
429 let selected = if names.is_empty() {
430 all.clone()
431 } else {
432 names.iter().cloned().collect()
433 };
434 if let Some(unknown) = selected.difference(&all).next() {
435 bail!("no package `{unknown}` in the workspace");
436 }
437 if !options.lines.is_empty() {
438 let selected_pkgs: Vec<&Package> = metadata
439 .packages
440 .iter()
441 .filter(|p| selected.contains(&p.name))
442 .collect();
443 validate_workspace_lines(&options.lines, &metadata.workspace_root, &selected_pkgs)?;
444 }
445 let base = options
446 .work_dir
447 .clone()
448 .unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
449 fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
450 let base = base.canonicalize()?;
451 let workspace_canon = metadata.workspace_root.canonicalize()?;
452 if workspace_canon.starts_with(&base) {
453 bail!(
454 "the work directory {} contains the workspace",
455 base.display()
456 );
457 }
458 let mut member_options = Vec::with_capacity(selected.len());
459 let mut used_work_dirs: Vec<(String, PathBuf)> = Vec::new();
460 for name in selected {
461 let mut member = options_for_package(&name, options)?;
462 member.package = Some(name.clone());
463 let custom_work = member
464 .work_dir
465 .as_ref()
466 .is_some_and(|w| options.work_dir.as_ref() != Some(w));
467 let member_work = if custom_work {
468 let custom = member.work_dir.clone().expect("custom work_dir");
469 fs::create_dir_all(&custom)
470 .with_context(|| format!("creating {}", custom.display()))?;
471 let canon = custom.canonicalize()?;
472 if workspace_canon.starts_with(&canon) {
473 bail!(
474 "the work directory {} for `{name}` contains the workspace",
475 canon.display()
476 );
477 }
478 canon
479 } else {
480 base.join(&name)
481 };
482 for (other_name, other_dir) in &used_work_dirs {
483 if member_work == *other_dir
484 || member_work.starts_with(other_dir)
485 || other_dir.starts_with(&member_work)
486 {
487 bail!(
488 "overlapping work directories for `{name}` ({}) and `{other_name}` ({})",
489 member_work.display(),
490 other_dir.display()
491 );
492 }
493 }
494 used_work_dirs.push((name.clone(), member_work.clone()));
495 member.work_dir = Some(member_work);
496 member_options.push((name, member));
497 }
498 let uniform_copy_settings = member_options
499 .first()
500 .map(|(_, first)| {
501 member_options.iter().all(|(_, m)| {
502 m.all_files == first.all_files
503 && m.git_index == first.git_index
504 && m.copy_fixtures == first.copy_fixtures
505 && m.copy_fixture_excludes == first.copy_fixture_excludes
506 && m.stage_external == first.stage_external
507 })
508 })
509 .unwrap_or(true);
510 let catalogue_dir = base.join(".catalogue");
511 let catalogue = if uniform_copy_settings && (options.list || options.shard.is_some()) {
512 for (name, member_dir) in &used_work_dirs {
513 if *member_dir == catalogue_dir
514 || member_dir.starts_with(&catalogue_dir)
515 || catalogue_dir.starts_with(member_dir)
516 {
517 bail!(
518 "work directory {} for `{name}` overlaps shared workspace catalogue {}",
519 member_dir.display(),
520 catalogue_dir.display()
521 );
522 }
523 }
524 let path = work_directory(&base, ".catalogue")?;
525 Some(CatalogueSnapshot {
526 _lock: WorkLock::take(&path)?,
527 path,
528 ready: std::cell::Cell::new(false),
529 })
530 } else {
531 None
532 };
533 let batch = WorkspaceBatch {
534 metadata: &metadata,
535 work: &base,
536 catalogue,
537 };
538 let Some(shard) = options.shard else {
539 for (name, member) in member_options {
540 if crate::interrupt::is_interrupted() {
541 return Ok(());
542 }
543 let result = run_package(&member, Some(&batch), None);
544 if let Err(err) = &result
545 && crate::interrupt::is_interrupted_err(err)
546 {
547 return Err(crate::interrupt::Interrupted.into());
548 }
549 let interrupted = result.as_ref().is_ok_and(|report| report.interrupted);
550 completed(name, result)?;
551 if interrupted || crate::interrupt::is_interrupted() {
552 return Ok(());
553 }
554 }
555 return Ok(());
556 };
557 if shard.index >= shard.count || member_options.iter().any(|(_, m)| !m.source_only) {
558 bail!("shards require --source-only and a valid shard index");
559 }
560 let mut catalogues = Vec::with_capacity(member_options.len());
563 for (name, member) in member_options {
564 if crate::interrupt::is_interrupted() {
565 return Err(crate::interrupt::Interrupted.into());
566 }
567 let mut preview = member.clone();
568 preview.list = true;
569 preview.shard = None;
570 preview.progress = false;
571 let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
572 let count = report.mutants.as_ref().map_or(0, Vec::len);
573 if !member.list {
574 report.mutants = None;
575 }
576 (count, report)
577 });
578 if catalogue
579 .as_ref()
580 .is_ok_and(|(_, report)| report.interrupted)
581 || crate::interrupt::is_interrupted()
582 {
583 return Err(crate::interrupt::Interrupted.into());
584 }
585 catalogues.push((name, member, catalogue));
586 }
587 let total = catalogues
588 .iter()
589 .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
590 .map(|(count, _)| count)
591 .sum();
592 let mut offset = 0;
593 for (name, member, catalogue) in catalogues {
594 if crate::interrupt::is_interrupted() {
595 return Ok(());
596 }
597 let result = catalogue.and_then(|(member_total, mut report)| {
598 let range = WorkspaceShard {
599 offset,
600 total,
601 member_total,
602 };
603 offset += member_total;
604 if member.list {
605 report.analysis.shard = Some(shard);
606 let mut index = range.offset;
607 if let Some(mutants) = report.mutants.as_mut() {
608 mutants.retain(|_| {
609 let keep = shard.contains(index, total);
610 index += 1;
611 keep
612 });
613 }
614 Ok(report)
615 } else {
616 run_package(&member, Some(&batch), Some(range))
617 }
618 });
619 let interrupted = result.as_ref().is_ok_and(|report| report.interrupted);
620 completed(name, result)?;
621 if interrupted || crate::interrupt::is_interrupted() {
622 return Ok(());
623 }
624 }
625 Ok(())
626}
627
628struct LeftoverNote(bool);
630
631impl Drop for LeftoverNote {
632 fn drop(&mut self) {
633 use std::sync::atomic::Ordering;
634 let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
635 let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
636 if let Some(text) = leftover_note(stopped, not_stopped)
637 && self.0
638 {
639 eprintln!("tmt: {text}");
640 }
641 }
642}
643
644fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
645 let stopped = (stopped > 0).then(|| {
646 format!("stopped {stopped} processes that the tests had left running after their run")
647 });
648 let not_stopped = (not_stopped > 0).then(|| {
649 format!(
650 "after {not_stopped} runs something the tests started may still be running \
651 (it could not be found or stopped)"
652 )
653 });
654 match (stopped, not_stopped) {
655 (None, None) => None,
656 (Some(one), None) | (None, Some(one)) => Some(one),
657 (Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
658 }
659}
660
661pub fn run(options: &Options) -> Result<Report> {
662 run_package(options, None, None)
663}
664
665fn interrupted_stub_report(options: &Options, package: Option<String>) -> Report {
666 let mut report = Report {
667 package: package
668 .or_else(|| options.package.clone())
669 .unwrap_or_default(),
670 interrupted: true,
671 wrapper_grace_outcomes: options
672 .test_selection
673 .wrapper
674 .as_ref()
675 .map(|_| report::WrapperGraceOutcomes::default()),
676 ..Report::default()
677 };
678 if crate::interrupt::is_interrupted() {
679 report.interrupted = true;
680 }
681 report.record_evaluation();
682 report
683}
684
685fn run_package(
686 options: &Options,
687 batch: Option<&WorkspaceBatch<'_>>,
688 workspace_shard: Option<WorkspaceShard>,
689) -> Result<Report> {
690 let mut resolved_package: Option<String> = options.package.clone();
691 match run_package_inner(options, batch, workspace_shard, &mut resolved_package) {
692 Ok(report) => Ok(report),
693 Err(err)
694 if crate::interrupt::is_interrupted() || crate::interrupt::is_interrupted_err(&err) =>
695 {
696 Ok(interrupted_stub_report(options, resolved_package))
697 }
698 Err(err) => Err(err),
699 }
700}
701
702fn run_package_inner(
703 options: &Options,
704 batch: Option<&WorkspaceBatch<'_>>,
705 workspace_shard: Option<WorkspaceShard>,
706 resolved_package: &mut Option<String>,
707) -> Result<Report> {
708 let _leftovers = LeftoverNote(options.progress);
709 let error_values = validate_package_options(options)?;
710 let selection = &options.test_selection;
711 let effective_jobs = if options.source_only { 1 } else { options.jobs };
712 let note = |text: &str| {
713 if options.progress {
714 eprintln!("tmt: {}", report::sanitize_inline(text));
715 }
716 };
717 let dir = options
718 .dir
719 .canonicalize()
720 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
721 if dir.is_file() {
722 let given = crate::report::sanitize_inline(&options.dir.display().to_string());
723 bail!(
724 "`{given}` is a file, not a Cargo package directory; pass the package directory and `--lines <path-relative-to-package-or-workspace>` to analyse a single file"
725 );
726 }
727
728 let local_metadata;
729 let metadata = if let Some(batch) = batch {
730 batch.metadata
731 } else {
732 local_metadata = cargo_metadata(&dir, &options.cargo)?;
733 &local_metadata
734 };
735 let catalogue = batch
736 .and_then(|batch| batch.catalogue.as_ref())
737 .filter(|_| options.list);
738 let enclosing_package = metadata
739 .packages
740 .iter()
741 .filter(|p| {
742 p.manifest_path
743 .parent()
744 .is_some_and(|root| dir != root && dir.starts_with(root))
745 })
746 .max_by_key(|p| {
747 p.manifest_path
748 .parent()
749 .map_or(0, |root| root.as_os_str().len())
750 });
751 let package = match &options.package {
752 Some(name) => metadata.packages.iter().find(|p| &p.name == name),
753 None => metadata
754 .packages
755 .iter()
756 .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
757 .or(match &metadata.packages[..] {
758 [only] => Some(only),
759 _ => None,
760 }),
761 }
762 .ok_or_else(|| {
763 if let Some(name) = &options.package {
764 anyhow!(
765 "no package `{}` in workspace",
766 crate::report::sanitize_inline(name)
767 )
768 } else if let Some(owner) = enclosing_package {
769 anyhow!(
770 "`{}` is a subdirectory of package `{}` (no Cargo.toml); pass `--package {}` from the workspace/package root (and `--lines <path-relative-to-package-or-workspace>` to narrow files)",
771 crate::report::sanitize_inline(&options.dir.display().to_string()),
772 crate::report::sanitize_inline(&owner.name),
773 crate::report::sanitize_inline(&owner.name),
774 )
775 } else {
776 anyhow!("cannot tell which package to analyse; pass --package <name>")
777 }
778 })?;
779 *resolved_package = Some(package.name.clone());
780 if options.package.is_none()
781 && !dir.join("Cargo.toml").is_file()
782 && package.manifest_path.parent() != Some(dir.as_path())
783 && options.progress
784 {
785 eprintln!(
786 "tmt: note: `{}` has no Cargo.toml; analysing package `{}` (use `--lines <file>` to scope to specific files)",
787 crate::report::sanitize_inline(&options.dir.display().to_string()),
788 crate::report::sanitize_inline(&package.name),
789 );
790 }
791 let mut test_packages: Vec<&Package> = vec![package];
794 for name in &options.also_test {
795 let other = metadata
796 .packages
797 .iter()
798 .find(|p| &p.name == name)
799 .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
800 if !test_packages.iter().any(|p| p.name == other.name) {
801 test_packages.push(other);
802 }
803 }
804 if options.test_workspace {
805 test_packages.extend(
806 metadata
807 .packages
808 .iter()
809 .filter(|other| {
810 !test_packages
811 .iter()
812 .any(|selected| selected.name == other.name)
813 })
814 .collect::<Vec<_>>(),
815 );
816 }
817 if options.dependents {
818 for name in dependents_of(&package.name, &metadata.packages) {
819 if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
820 && !test_packages.iter().any(|p| p.name == other.name)
821 {
822 test_packages.push(other);
823 }
824 }
825 }
826 if !options.list {
827 validate_target_selection(&test_packages, selection)?;
828 }
829 let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
830 let root_target = package
831 .targets
832 .iter()
833 .find(|t| {
834 is_kind(
835 t,
836 &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
837 )
838 })
839 .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
840 .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
841
842 let PreparedWorkCopy {
844 workspace,
845 work,
846 work_lock,
847 copy,
848 state,
849 external_deps,
850 } = prepare_work_copy(options, metadata, batch, catalogue, ¬e)?;
851
852 let in_copy = |path: &Path| -> Result<PathBuf> {
853 let canonical = path.canonicalize()?;
854 let relative = canonical
855 .strip_prefix(&workspace)
856 .with_context(|| format!("{} is outside the workspace", path.display()))?;
857 Ok(copy.join(relative))
858 };
859 let package_dir = in_copy(
860 package
861 .manifest_path
862 .parent()
863 .expect("manifest has a parent"),
864 )?;
865 let root_file = in_copy(&root_target.src_path)?;
866 let source_dir = root_file
867 .parent()
868 .expect("source file has a parent")
869 .to_path_buf();
870
871 let mut roots = BTreeMap::new();
874 for owner in &metadata.packages {
875 for target in &owner.targets {
876 let production = owner.name == package.name && target.is_production();
877 if let Ok(path) = in_copy(&target.src_path)
878 && path.is_file()
879 {
880 let selected = roots.entry(path).or_insert(false);
881 *selected |= production;
882 }
883 }
884 }
885 let paths = source_graph(roots, ©, |path| state.original(path, &workspace))?;
886 let package_orig_dir = package
887 .manifest_path
888 .parent()
889 .expect("manifest has a parent");
890 let scope = requested_scope(
891 options,
892 &workspace,
893 package_orig_dir,
894 &package.name,
895 batch.is_some(),
896 )?;
897 let mut skipped = vec![];
898 let mut files = vec![];
899 let mut excluded_any = false;
900 let mut next_id = 0u32;
901 let want_witnesses = (options.list || options.rebuild || options.source_only)
902 && root_target.test_build_arg() == Some(("--lib", None));
903 let count_rebuild_witnesses =
904 !want_witnesses && root_target.test_build_arg() == Some(("--lib", None));
905 let mut witness_candidates = vec![];
906 let mut unbuilt_witness_candidates = vec![];
907 for (path, owners) in paths {
908 let Some(original) = state.original(&path, &workspace)? else {
909 continue; };
911 let display = relative_source(&path, &package_dir).display().to_string();
912 if scope::matches_any_glob(&options.exclude_files, &display) {
913 excluded_any = true;
914 continue;
915 }
916 let selected_file = scope.as_ref().is_none_or(|scope| {
917 let relative = path.strip_prefix(©).unwrap_or(&path).to_string_lossy();
918 scope.touches(&relative, 1, usize::MAX)
919 });
920 if !selected_file && path != root_file {
921 continue;
922 }
923 match instrument::parse_source(&original) {
924 Ok(parsed) => {
925 let mut found =
926 instrument::discover_parsed(&original, &parsed, next_id, &error_values);
927 if (want_witnesses || count_rebuild_witnesses)
929 && selected_file
930 && owners.consumers.len() == 1
931 && owners.consumers.contains(&root_file)
932 {
933 let discovered = witness::discover_parsed(
934 &original,
935 &parsed,
936 want_witnesses && !options.list,
937 )
938 .into_iter()
939 .map(|mut candidate| {
940 candidate.file = path.clone();
941 candidate
942 });
943 if want_witnesses {
944 witness_candidates.extend(discovered);
945 } else {
946 unbuilt_witness_candidates.extend(discovered);
947 }
948 if want_witnesses && !options.list && !options.literal_operators {
951 witness_candidates.extend(
952 stronger_assertions(
955 &original,
956 &parsed,
957 found.sites.iter().chain(&found.rebuild_sites),
958 )
959 .into_iter()
960 .map(|mut candidate| {
961 candidate.file = path.clone();
962 candidate
963 }),
964 );
965 }
966 }
967 next_id += found.sites.len() as u32;
968 if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
969 found.rebuild_sites.append(&mut found.sites);
970 }
971 let places = if options.list {
972 vec![]
973 } else {
974 found
975 .sites
976 .iter()
977 .chain(&found.rebuild_sites)
978 .map(|site| (site.line, site.column, report::one_line(&site.text)))
979 .collect()
980 };
981 files.push(SourceFile {
982 display,
983 path,
984 owners: owners.production,
985 lines: scope::LineIndex::new(&original),
986 original,
987 places,
988 sites: found.sites,
989 rebuild_sites: found.rebuild_sites,
990 rendered: None,
991 });
992 }
993 Err(err) => {
994 if selected_file {
995 let diagnostic = format!("{err:#}");
996 note(&format!("skipping {display}: {diagnostic}"));
997 let end_line = scope::line_of(&original, original.len());
998 let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
999 skipped.push(report::SkippedSite::new(
1000 report::Location {
1001 file: display,
1002 line: 1,
1003 column: 1,
1004 ..Default::default()
1005 },
1006 (end_line, end_column),
1007 report::SkipReason::UnparseableSource,
1008 Some(diagnostic),
1009 ));
1010 }
1011 }
1012 }
1013 }
1014
1015 let since_hunks = match options.since.as_deref() {
1018 Some(revision) if !options.list && options.shard.is_none() => {
1019 scope::hunks(&since_diff(&workspace, revision)?)
1020 }
1021 _ => vec![],
1022 };
1023 let mut tests_changed: Vec<(PathBuf, Vec<scope::Hunk>)> = vec![];
1024 let mut undo_paths: HashSet<PathBuf> = HashSet::new();
1026 let mut not_built_reverts: usize = 0;
1027 let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
1028 if let Some(scope) = &scope {
1030 for file in &mut files {
1031 let relative = file
1032 .path
1033 .strip_prefix(©)
1034 .unwrap_or(&file.path)
1035 .to_string_lossy()
1036 .into_owned();
1037 let in_scope = |site: &Site| {
1038 scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
1039 || scope.touches(&relative, site.line, site.line)
1041 };
1042 let of_file: Vec<scope::Hunk> = since_hunks
1043 .iter()
1044 .filter(|hunk| hunk.file == relative)
1045 .cloned()
1046 .collect();
1047 let changes_count = reverts::changes(&file.original, &of_file).len();
1048 if options.rebuild || options.source_only {
1049 if changes_count > 0 || reverts::mixed(&file.original, &of_file) > 0 {
1050 undo_paths.insert(file.path.clone());
1051 }
1052 } else {
1053 not_built_reverts += changes_count;
1054 }
1055 let of_tests = reverts::test_hunks(&file.original, &of_file);
1056 if of_tests.is_empty() {
1057 file.sites.retain(in_scope);
1058 } else {
1059 beyond_places.extend(
1060 file.sites
1061 .iter()
1062 .filter(|site| !in_scope(site))
1063 .map(|site| (file.path.clone(), site.start, site.end)),
1064 );
1065 tests_changed.push((file.path.clone(), of_tests));
1066 }
1067 file.rebuild_sites.retain(in_scope);
1068 }
1069 files.retain(|f| {
1070 !f.sites.is_empty()
1071 || !f.rebuild_sites.is_empty()
1072 || f.path == root_file
1073 || witness_candidates.iter().any(|c| c.file == f.path)
1074 || unbuilt_witness_candidates.iter().any(|c| c.file == f.path)
1075 || undo_paths.contains(&f.path)
1076 });
1077 }
1078 if !options.list {
1079 for candidate in witness_candidates.iter().filter(|c| !c.existing) {
1080 if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
1081 let at = witness_location(file, candidate);
1082 file.places.push((at.line, at.column, at.code));
1083 }
1084 }
1085 }
1086 let witness_in_scope = |candidate: &witness::Candidate| {
1087 let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
1088 return false;
1089 };
1090 let relative = file
1091 .path
1092 .strip_prefix(©)
1093 .unwrap_or(&file.path)
1094 .to_string_lossy();
1095 scope.as_ref().is_none_or(|scope| {
1096 let site_in_scope = if candidate.edits.len() == 1 {
1097 scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
1098 } else {
1099 candidate.edits.iter().any(|edit| {
1100 scope.touches(
1101 &relative,
1102 file.lines.line_of(edit.span.start),
1103 file.lines.line_of(edit.span.end),
1104 )
1105 })
1106 };
1107 site_in_scope
1108 || candidate
1109 .signature_lines
1110 .iter()
1111 .any(|&line| scope.touches(&relative, line, line))
1112 })
1113 };
1114 witness_candidates.retain(&witness_in_scope);
1115 unbuilt_witness_candidates.retain(&witness_in_scope);
1116 let not_built_witnesses = unbuilt_witness_candidates
1117 .iter()
1118 .filter(|candidate| !candidate.existing)
1119 .count();
1120
1121 let unassessed_test_changes: Vec<String> = if let Some(revision) = options.since.as_deref()
1122 && !options.list
1123 {
1124 let integration_prefixes: Vec<String> = test_packages
1125 .iter()
1126 .flat_map(|pkg| {
1127 let pkg_dir = pkg.manifest_path.parent().unwrap_or(&workspace);
1128 let pkg_rel = pkg_dir.strip_prefix(&workspace).ok();
1129 let pkg_tests_dir = pkg_rel.map(|rel| {
1130 let s = rel.join("tests").to_string_lossy().replace('\\', "/");
1131 format!("{s}/")
1132 });
1133 let workspace_ref = &workspace;
1134 let explicit_targets = pkg.targets.iter().flat_map(move |t| {
1135 if !t.kind.iter().any(|k| k == "test") {
1136 return vec![];
1137 }
1138 let Ok(rel) = t.src_path.strip_prefix(workspace_ref) else {
1139 return vec![];
1140 };
1141 let mut out = vec![rel.to_string_lossy().replace('\\', "/")];
1142 if let (Some(parent), Some(pkg_r)) = (rel.parent(), pkg_rel) {
1146 let is_pkg_root = parent == pkg_r;
1147 let is_src = parent == pkg_r.join("src");
1148 if !is_pkg_root && !is_src && !parent.as_os_str().is_empty() {
1149 out.push(format!("{}/", parent.to_string_lossy().replace('\\', "/")));
1150 }
1151 }
1152 out
1153 });
1154 pkg_tests_dir.into_iter().chain(explicit_targets)
1155 })
1156 .collect();
1157 let is_integration_test = |ws_rel: &str| {
1158 ws_rel.ends_with(".rs")
1159 && integration_prefixes.iter().any(|prefix| {
1160 if prefix.ends_with('/') {
1161 ws_rel.starts_with(prefix)
1162 } else {
1163 ws_rel == prefix
1164 }
1165 })
1166 };
1167 since_changed_files(&workspace, revision)?
1168 .into_iter()
1169 .filter(|f| is_integration_test(f))
1170 .collect()
1171 } else {
1172 vec![]
1173 };
1174 let total_sites: usize = files
1175 .iter()
1176 .map(|f| f.sites.len() + f.rebuild_sites.len())
1177 .sum::<usize>()
1178 + witness_candidates
1179 .iter()
1180 .filter(|candidate| !candidate.existing)
1181 .count();
1182 let files_with_sites = files
1183 .iter()
1184 .filter(|f| {
1185 !f.sites.is_empty()
1186 || !f.rebuild_sites.is_empty()
1187 || witness_candidates
1188 .iter()
1189 .any(|c| !c.existing && c.file == f.path)
1190 })
1191 .count();
1192 note(&format!(
1193 "{total_sites} sites in {files_with_sites} {}",
1194 if files_with_sites == 1 {
1195 "file"
1196 } else {
1197 "files"
1198 }
1199 ));
1200 if options.source_only {
1201 for file in &mut files {
1202 file.rebuild_sites.append(&mut file.sites);
1203 }
1204 }
1205
1206 let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
1207 let mut mutants = instrument::source_mutants(site);
1208 if include_boundary {
1209 mutants.extend(instrument::source_boundary_mutant(site));
1210 }
1211 if options.literal_operators {
1212 instrument::literal_operator_mutants(&file.original, site, &mut mutants);
1213 }
1214 instrument::keep_line_ends(&file.original, &mut mutants);
1215 mutants
1216 };
1217 let counts = options.shard.map(|_| {
1218 let regular: usize = files
1219 .iter()
1220 .map(|file| {
1221 file.rebuild_sites
1222 .iter()
1223 .map(|site| source_mutants(file, site, true).len())
1224 .sum::<usize>()
1225 })
1226 .sum();
1227 let total = regular
1228 + witness_candidates
1229 .iter()
1230 .filter(|candidate| !candidate.existing)
1231 .count();
1232 (regular, total)
1233 });
1234 if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
1235 && range.member_total != local_total
1236 {
1237 bail!("package catalogue changed while preparing its workspace shard");
1238 }
1239 let in_shard = |index| match (options.shard, counts, workspace_shard) {
1240 (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
1241 (Some(shard), Some((_, total)), _) => shard.contains(index, total),
1242 _ => true,
1243 };
1244 if let Some((mut index, _)) = counts {
1245 witness_candidates.retain(|candidate| {
1246 if candidate.existing {
1247 return true;
1248 }
1249 let selected = in_shard(index);
1250 index += 1;
1251 selected
1252 });
1253 }
1254 let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
1255
1256 let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
1257 let mut report_path = repository_prefix(package_path);
1258 if report_path.is_empty()
1259 && batch.is_some()
1260 && let Ok(relative) = package_path.strip_prefix(&workspace)
1261 {
1262 report_path = workspace_report_prefix(relative);
1263 }
1264 let mut report = Report {
1265 package: package.name.clone(),
1266 sites: if empty_shard { 0 } else { total_sites },
1267 analysis: report::Analysis {
1268 package_path: report_path,
1269 since: options.since.clone(),
1270 lines: options.lines.clone(),
1271 exclude_files: options.exclude_files.clone(),
1272 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
1273 cargo: options.cargo.clone(),
1274 opt_level: options.opt_level,
1275 timeout_seconds: options.timeout_seconds,
1276 baseline_timeout_seconds: options.baseline_timeout_seconds,
1277 baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
1278 timeout_recheck: if options.serial_timeout_rechecks {
1279 "serial"
1280 } else {
1281 "none"
1282 },
1283 wrapper_grace_seconds: selection
1284 .wrapper
1285 .as_ref()
1286 .map(|_| options.wrapper_grace.as_secs()),
1287 rebuild: options.rebuild || options.source_only,
1288 verified: options.verify && !options.source_only,
1289 doc_tests: options.doc,
1290 source_only: options.source_only,
1291 literal_operators: options.literal_operators,
1292 shard: options.shard,
1293 nextest: options.nextest.clone(),
1294 error_values: error_values
1295 .iter()
1296 .map(|value| (*value).to_owned())
1297 .collect(),
1298 test_selection: None,
1299 git_index: options.git_index,
1300 copy_fixtures: options.copy_fixtures.clone(),
1301 copy_fixture_excludes: options.copy_fixture_excludes.clone(),
1302 output_fixtures: options.output_fixtures.clone(),
1303 stage_external: options.stage_external.clone(),
1304 checkpoint: (options.checkpoint && !options.list)
1305 .then(|| work.join("checkpoint.jsonl")),
1306 },
1307 skipped,
1308 wrapper_grace_outcomes: if options.list {
1309 None
1310 } else {
1311 selection
1312 .wrapper
1313 .as_ref()
1314 .map(|_| report::WrapperGraceOutcomes::default())
1315 },
1316 baseline: if options.list {
1317 None
1318 } else {
1319 options.baseline.clone()
1320 },
1321 unassessed_test_changes,
1322 ..Report::default()
1323 };
1324 if options.list {
1325 if catalogue.is_none() {
1326 state.settle(&workspace)?;
1327 }
1328 let mut candidates = vec![];
1329 let mut index = 0;
1330 for file in &files {
1331 let sites = file
1332 .sites
1333 .iter()
1334 .map(|site| (site, false))
1335 .chain(file.rebuild_sites.iter().map(|site| (site, true)));
1336 for (site, requires_rebuild) in sites {
1337 for mutant in source_mutants(file, site, true) {
1338 if in_shard(index) {
1339 candidates.push(report::Candidate {
1340 what: mutant.what,
1341 into: mutant.into,
1342 requires_rebuild,
1343 edits: vec![candidate_edit(
1344 file,
1345 mutant.start,
1346 mutant.end,
1347 mutant.replacement,
1348 )],
1349 });
1350 }
1351 index += 1;
1352 }
1353 }
1354 }
1355 candidates.extend(
1356 witness_candidates
1357 .iter()
1358 .filter(|candidate| !candidate.existing)
1359 .filter_map(|candidate| {
1360 let file = files.iter().find(|file| file.path == candidate.file)?;
1361 Some(report::Candidate {
1362 what: "witness".into(),
1363 into: candidate.description.clone(),
1364 requires_rebuild: true,
1365 edits: candidate
1366 .edits
1367 .iter()
1368 .map(|edit| {
1369 candidate_edit(
1370 file,
1371 edit.span.start,
1372 edit.span.end,
1373 edit.replacement.clone(),
1374 )
1375 })
1376 .collect(),
1377 })
1378 }),
1379 );
1380 report.mutants = Some(candidates);
1381 return Ok(report);
1382 }
1383 let ws_package_prefix = package_dir
1384 .strip_prefix(©)
1385 .unwrap_or(Path::new(""))
1386 .to_string_lossy()
1387 .replace('\\', "/");
1388 let all_files_excluded = excluded_any && files.is_empty();
1389 let is_partial_scope =
1390 scope.is_some() || !options.exclude_files.is_empty() || options.shard.is_some();
1391 if empty_shard
1392 || ((scope.is_some() || all_files_excluded) && total_sites == 0 && undo_paths.is_empty())
1393 {
1394 state.settle(&workspace)?;
1396 if let Some(path) = &options.baseline {
1397 let loaded = crate::baseline::load(path)?;
1398 loaded.validate_for_package(&package.name, path)?;
1399 }
1400 if crate::interrupt::is_interrupted() {
1401 report.interrupted = true;
1402 }
1403 if !report.interrupted
1404 && let Some(path) = &options.write_baseline
1405 {
1406 let partial = crate::baseline::PartialScope {
1407 scope: scope.as_ref(),
1408 exclude_files: &options.exclude_files,
1409 preserve_all_existing: true,
1410 };
1411 let single_pkg = batch.is_none().then_some(package.name.as_str());
1412 let summary = crate::baseline::write_scoped(
1413 path,
1414 &package.name,
1415 &ws_package_prefix,
1416 &[],
1417 Some(&partial),
1418 single_pkg,
1419 )?;
1420 if summary.preserved > 0 {
1421 note(&format!(
1422 "baseline {}: preserved {} out-of-scope entries (no sites evaluated)",
1423 path.display(),
1424 summary.preserved
1425 ));
1426 }
1427 }
1428 if !empty_shard {
1429 report.mutants_not_built += not_built_reverts + not_built_witnesses;
1430 }
1431 if crate::interrupt::is_interrupted() {
1432 report.interrupted = true;
1433 }
1434 report.record_evaluation();
1435 if let Some(path) = report.analysis.checkpoint.as_deref() {
1436 let checkpoint = Checkpoint::open(path)?;
1437 let settings =
1438 serde_json::json!({"analysis": &report.analysis, "package": &package.name});
1439 let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
1440 checkpoint.start(&identity, settings)?;
1441 checkpoint.finish()?;
1442 }
1443 return Ok(report);
1444 }
1445
1446 for (id, site) in files
1449 .iter_mut()
1450 .flat_map(|file| &mut file.sites)
1451 .enumerate()
1452 {
1453 site.id = id as u32;
1454 }
1455 let beyond: HashSet<u32> = files
1457 .iter()
1458 .flat_map(|file| {
1459 file.sites
1460 .iter()
1461 .filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
1462 .map(|site| site.id)
1463 })
1464 .collect();
1465
1466 let root_source = state
1467 .original(&root_file, &workspace)?
1468 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
1469 let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
1470 String::new()
1471 } else {
1472 state.write(
1473 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
1474 crate::RUNTIME_SOURCE,
1475 )?;
1476 let std_alias = format!("extern crate std as {STD_ALIAS};");
1477 if root_source.contains(&std_alias) {
1478 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1479 } else {
1480 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1481 }
1482 };
1483
1484 let mut disabled: HashSet<u32> = HashSet::new();
1486 let mut repairs = BTreeMap::new();
1487 let build_target = work_directory(&work, "target")?;
1488 let target_flags = test_build_flags(&test_packages, selection, &workspace, &options.cargo);
1489 let build_scope = if target_flags.is_some() {
1490 report::TestBuildScope::SelectedTargets
1491 } else {
1492 report::TestBuildScope::PackageWide
1493 };
1494 let build_note = if selection.has_target_filters() && target_flags.is_none() {
1495 "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
1496 } else {
1497 ""
1498 };
1499 if !build_note.is_empty() {
1500 note(build_note.trim_end());
1501 }
1502 let can_build_only_observer = !options.doc
1505 && target_flags.is_none()
1506 && test_packages.len() == 1
1507 && package.targets.len() == 1
1508 && root_target.test
1509 && root_target.test_build_arg() == Some(("--lib", None));
1510 let build_test_binaries = |observer: bool| {
1511 let mut command = Command::new("cargo");
1512 isolate_copy_command(&mut command, &work);
1513 if let Some(lock) = &work_lock {
1514 lock.retain_for(&mut command);
1515 }
1516 command
1517 .args(["test", "--no-run", "--message-format=json"])
1518 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
1519 .args(target_flags.as_deref().unwrap_or_default())
1520 .args((observer && can_build_only_observer).then_some("--lib"))
1521 .args(options.cargo.flags())
1522 .current_dir(©)
1523 .env("CARGO_TARGET_DIR", &build_target)
1524 .env("CARGO_BUILD_BUILD_DIR", &build_target)
1525 .envs(profile_env(options.opt_level));
1526 run_cargo_with_progress(&mut command, options.progress && !observer)
1527 };
1528 let cargo_build = || build_test_binaries(false);
1529 let has_probe_sites = !options.source_only && files.iter().any(|f| !f.sites.is_empty());
1530 let repair_fingerprint = has_probe_sites.then(|| {
1531 let test_pkg_names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1532 repair_cache::compute_fingerprint(
1533 &state.root,
1534 ©,
1535 &workspace,
1536 &state,
1537 &external_deps,
1538 &package.name,
1539 &test_pkg_names,
1540 &options.cargo,
1541 options.opt_level,
1542 target_flags.as_deref(),
1543 &error_values,
1544 options.doc,
1545 &files,
1546 )
1547 });
1548 if let Some(fingerprint) = &repair_fingerprint {
1549 let cached = repair_cache::load(&work, fingerprint);
1550 if !cached.is_empty() {
1551 for entry in cached {
1552 if let Some(file) = files.iter().find(|f| f.display == entry.file)
1553 && let Some(site) = file.sites.get(entry.site_index)
1554 && site.start == entry.start
1555 && site.end == entry.end
1556 && site.text == entry.text
1557 && format!("{:?}", site.kind) == entry.kind
1558 {
1559 disabled.insert(site.id);
1560 repairs.entry(site.id).or_insert(entry.reason);
1561 }
1562 }
1563 if !disabled.is_empty() {
1564 note(&format!(
1565 "reusing {} cached repair exclusion(s)",
1566 disabled.len()
1567 ));
1568 }
1569 }
1570 }
1571 let mut rounds = 0;
1572 let mut newly_disabled = HashSet::new();
1573 let build = loop {
1574 for file in &mut files {
1575 let suffix = if file.path == root_file {
1576 root_suffix.as_str()
1577 } else {
1578 ""
1579 };
1580 write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
1581 }
1582 if !files.iter().any(|f| f.path == root_file) {
1583 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
1584 }
1585 if rounds == 0 {
1586 state.settle(&workspace)?;
1587 }
1588 note(if rounds == 0 {
1589 "building the instrumented crate"
1590 } else {
1591 "rebuilding without the sites that failed to compile"
1592 });
1593 let output = cargo_build()?;
1594 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1595 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
1596 if output.status.success() {
1597 if let Some(fingerprint) = &repair_fingerprint {
1598 let cached_entries: Vec<repair_cache::CachedSite> = files
1599 .iter()
1600 .flat_map(|file| {
1601 file.sites
1602 .iter()
1603 .enumerate()
1604 .filter(|(_, site)| disabled.contains(&site.id))
1605 .map(|(site_index, site)| repair_cache::CachedSite {
1606 file: file.display.clone(),
1607 site_index,
1608 start: site.start,
1609 end: site.end,
1610 text: site.text.clone(),
1611 kind: format!("{:?}", site.kind),
1612 reason: repairs.get(&site.id).cloned().unwrap_or_default(),
1613 })
1614 })
1615 .collect();
1616 let _ = repair_cache::save(&work, fingerprint, &cached_entries);
1617 }
1618 break build;
1619 }
1620 let diagnostics = || {
1621 [
1622 build.diagnostics.join("\n"),
1623 String::from_utf8_lossy(&output.stderr).into_owned(),
1624 ]
1625 .into_iter()
1626 .filter(|part| !part.trim().is_empty())
1627 .collect::<Vec<_>>()
1628 .join("\n")
1629 };
1630 if build.errors.is_empty() {
1631 bail!("the build failed:\n{build_note}{}", diagnostics());
1632 }
1633 if build
1634 .errors
1635 .iter()
1636 .any(|error| is_non_probe_error(error, &files, ©))
1637 {
1638 bail!(
1639 "the build failed with an error unrelated to instrumentation:\n{build_note}{}",
1640 diagnostics()
1641 );
1642 }
1643 rounds += 1;
1644 let before = disabled.len();
1645 let mut blamed_now: HashSet<u32> = HashSet::new();
1646 for error in &build.errors {
1647 let blamed = blame_error(error, &files, ©, &disabled);
1648 if std::env::var_os("TMT_DEBUG").is_some() {
1649 eprintln!(
1650 "tmt: debug: blaming {blamed:?} for\n{}",
1651 report::sanitize_terminal(&error.rendered)
1652 );
1653 }
1654 for id in blamed {
1655 repairs
1656 .entry(id)
1657 .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
1658 blamed_now.insert(id);
1659 }
1660 }
1661 disabled.extend(blamed_now.iter().copied());
1662 newly_disabled = blamed_now;
1663 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
1664 bail!(
1665 "the crate does not build after instrumentation.\n\
1666 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
1667 diagnostics()
1668 );
1669 }
1670 };
1671 let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
1672 let behind_cargo = features_from_flags(
1677 std::env::vars_os()
1678 .filter(|(name, _)| name.to_string_lossy().ends_with("RUSTFLAGS"))
1679 .map(|(_, value)| Some(value)),
1680 ) || build.build_scripts.iter().any(|script| {
1681 script["cfgs"].as_array().is_some_and(|cfgs| {
1682 cfgs.iter()
1683 .any(|cfg| cfg.as_str().is_some_and(|cfg| cfg.contains("feature")))
1684 })
1685 }) || configuration_names_a_feature(
1686 ©,
1687 std::env::var_os("CARGO_HOME").map(PathBuf::from),
1688 );
1689 BuiltSources::from_artifacts(&build.artifacts, &build.features, !behind_cargo, ©)
1690 } else {
1691 BuiltSources::default()
1692 };
1693 output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
1694 let checkpoint_path = report.analysis.checkpoint.as_deref();
1695 let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
1696 let doc_packages = test_packages
1697 .iter()
1698 .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
1699 if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
1700 bail!("{build_note}`{}` has no test binaries", package.name);
1701 }
1702
1703 let mut session = Session {
1705 progress: options.progress,
1706 serial_timeout_rechecks: options.serial_timeout_rechecks,
1707 package_dir,
1708 binaries: vec![],
1709 };
1710 let wrapper = selection
1711 .wrapper
1712 .as_ref()
1713 .map(|path| {
1714 let relative = wrapper_relative(path)?;
1715 let copied = copy.join(&relative);
1716 if !copied.is_file() {
1717 bail!(
1718 "test wrapper is missing from the work copy: {}",
1719 copied.display()
1720 );
1721 }
1722 Ok(copied)
1723 })
1724 .transpose()?;
1725 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
1726 let root_test_exe = |built: &BuildOutput| {
1727 built
1728 .test_binaries
1729 .iter()
1730 .find(|(name, _, owner, kind)| {
1731 *name == root_target.name && *owner == package.name && *kind == root_target.kind
1732 })
1733 .map(|(_, exe, _, _)| exe.clone())
1734 };
1735 let root_exe = (!witness_candidates.is_empty())
1736 .then(|| root_test_exe(&build))
1737 .flatten();
1738 let mut discovered_tests: Vec<String> = vec![];
1739 let mut empty_bin_targets: Vec<(String, String)> = vec![];
1740 if let Some(nextest) = &options.nextest {
1741 let mut flags: Vec<_> = test_packages
1742 .iter()
1743 .flat_map(|p| ["-p".to_owned(), p.name.clone()])
1744 .collect();
1745 flags.extend(options.cargo.flags());
1746 runners.push((
1747 "nextest".to_owned(),
1748 Runner::Nextest {
1749 copy: copy.clone(),
1750 target_dir: build_target.clone(),
1751 profile: nextest.profile.clone(),
1752 opt_level: options.opt_level,
1753 flags,
1754 },
1755 session.package_dir.clone(),
1756 ));
1757 } else {
1758 for (name, exe, owner, kind) in build.test_binaries {
1759 if !artifact_target_selected(&name, &kind, selection) {
1760 continue;
1761 }
1762 let owner_package = test_packages
1763 .iter()
1764 .find(|p| p.name == owner)
1765 .expect("binaries are filtered by these packages");
1766 let cwd = in_copy(
1767 owner_package
1768 .manifest_path
1769 .parent()
1770 .expect("manifest has a parent"),
1771 )?;
1772 if selection.enabled() {
1773 let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
1774 if all.is_empty() && kind.first().map(String::as_str) == Some("bin") {
1775 empty_bin_targets.push((owner.clone(), name.clone()));
1776 }
1777 let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
1778 for test in all {
1779 let was_ignored = ignored.contains(&test);
1780 if (!was_ignored || selection.include_ignored)
1781 && !selection.exclude.iter().any(|name| name == &test)
1782 {
1783 discovered_tests.push(test.clone());
1784 }
1785 if !selection.matches_test(&test, was_ignored) {
1786 continue;
1787 }
1788 runners.push((
1789 format!("{owner}::{}::{name}::{test}", kind.join("+")),
1790 Runner::Isolated {
1791 exe: exe.clone(),
1792 test,
1793 ignored: was_ignored,
1794 wrapper: wrapper.clone(),
1795 },
1796 cwd.clone(),
1797 ));
1798 }
1799 continue;
1800 }
1801 let name = if owner == package.name {
1803 name
1804 } else {
1805 format!("{owner}::{name}")
1806 };
1807 runners.push((name, Runner::Exe(exe), cwd));
1808 }
1809 }
1810 if selection.enabled() && runners.is_empty() {
1811 let hint = no_tests_matched_hint(
1812 &test_packages,
1813 selection,
1814 &empty_bin_targets,
1815 &discovered_tests,
1816 );
1817 bail!("{build_note}no tests matched the requested selection{hint}");
1818 }
1819 let selected_tests = selection.enabled().then(|| report::TestSelection {
1820 build_scope,
1821 wrapper: selection
1822 .wrapper
1823 .as_ref()
1824 .map(|path| path.display().to_string()),
1825 tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
1826 });
1827 for owner in doc_packages {
1828 let doc = Runner::Doc {
1829 copy: copy.clone(),
1830 target_dir: build_target.clone(),
1831 package: owner.name.clone(),
1832 opt_level: options.opt_level,
1833 flags: options.cargo.flags(),
1834 };
1835 let name = if owner.name == package.name {
1836 "doc tests".to_owned()
1837 } else {
1838 format!("{}::doc tests", owner.name)
1839 };
1840 let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
1841 runners.push((name, doc, cwd));
1842 }
1843 report.analysis.test_selection = selected_tests;
1844 let identity = if checkpoint.is_some() {
1845 let mut build_inputs: Vec<_> = build
1846 .build_scripts
1847 .iter()
1848 .map(serde_json::Value::to_string)
1849 .collect();
1850 build_inputs.sort();
1851 let settings = serde_json::json!({
1854 "build_scripts": build_inputs,
1855 "analysis": &report.analysis, "package": &package.name, "jobs": effective_jobs,
1856 "verify": options.verify, "audit": options.audit, "effects": options.effects,
1857 "all_files": options.all_files, "build_scope": build_scope,
1858 "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
1859 });
1860 let mut inputs = BTreeSet::new();
1861 for (root, artifacts) in &build.artifacts {
1862 inputs.insert(root.clone());
1863 if let Some(dependencies) = artifacts
1864 .iter()
1865 .map(|artifact| artifact_inputs(artifact, root, ©))
1866 .find(|deps| !deps.is_empty())
1867 {
1868 inputs.extend(dependencies);
1869 } else {
1870 inputs.extend(artifacts.iter().cloned());
1873 }
1874 }
1875 inputs.extend(
1876 build
1877 .build_scripts
1878 .iter()
1879 .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
1880 );
1881 inputs.retain(|path| !path.starts_with(©));
1884 inputs.extend(
1885 options
1886 .output_fixtures
1887 .iter()
1888 .map(|fixture| build_target.join(&fixture.to)),
1889 );
1890 inputs.extend(
1891 options
1892 .stage_external
1893 .iter()
1894 .map(|entry| normalize(©.join(&entry.rel))),
1895 );
1896 Some(crate::campaign_identity::compute(
1897 ©,
1898 &settings,
1899 inputs,
1900 options.nextest.is_some(),
1901 )?)
1902 } else {
1903 None
1904 };
1905 let marks = marks_dir(&work)?;
1910 let baseline_jobs = if selection.enabled() {
1911 options.baseline_jobs
1912 } else {
1913 1
1914 };
1915 if options.progress {
1916 eprintln!(
1917 "tmt: baselines: 0/{} completed ({} workers)",
1918 runners.len(),
1919 baseline_jobs
1920 );
1921 }
1922
1923 let baseline_budget = options
1924 .baseline_timeout_seconds
1925 .map(Duration::from_secs)
1926 .unwrap_or(DEFAULT_BASELINE_TIMEOUT);
1927 let baseline_stage = if options.source_only {
1928 "baseline_untraced"
1929 } else {
1930 "baseline_trace"
1931 };
1932 let diagnostic_path = work.join("baseline-timeout.json");
1933 let _ = fs::remove_file(&diagnostic_path);
1934 let completed_baselines = std::sync::atomic::AtomicUsize::new(0);
1935 let completed_timings = std::sync::Mutex::new(Vec::<report::BaselineTimingEntry>::new());
1936 let total_baselines = runners.len();
1937 let wrapper_grace_counter = selection
1938 .wrapper
1939 .as_ref()
1940 .map(|_| Arc::new(runner::WrapperGraceCounter::default()));
1941
1942 #[derive(Debug)]
1943 enum BaselinePoolError {
1944 Timeout(Box<report::BaselineTimeoutDiagnostic>),
1945 Failed(Box<report::BaselineFailureDiagnostic>),
1946 }
1947
1948 impl std::fmt::Display for BaselinePoolError {
1949 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1950 match self {
1951 Self::Timeout(diag) => write!(
1952 f,
1953 "baseline timeout in stage `{}` for `{}`",
1954 diag.stage, diag.runner
1955 ),
1956 Self::Failed(diag) => write!(f, "the tests in `{}` {}", diag.runner, diag.reason),
1957 }
1958 }
1959 }
1960
1961 impl std::error::Error for BaselinePoolError {}
1962
1963 let baseline_result = progress::track_baselines(options.progress, runners.len(), |progress| {
1964 run_pool(runners.len(), baseline_jobs, |slot| {
1965 let index = slot;
1966 let (name, runner, cwd) = runners[index].clone();
1967 let result = (|| {
1968 let trace_path = work.join(format!("trace-{index}.tsv"));
1969 let _ = fs::remove_file(&trace_path);
1970 let mut bin = TestBinary {
1971 name,
1972 cwd,
1973 marks: marks.clone(),
1974 git_ceiling: work.clone(),
1975 work_lock: work_lock.clone(),
1976 tests: BTreeSet::new(),
1977 runner,
1978 baseline: Duration::ZERO,
1979 untraced_baseline: None,
1980 timeout_diagnostic: std::sync::Once::new(),
1981 traced: Duration::ZERO,
1982 timeout: options.timeout_seconds.map(Duration::from_secs),
1983 wrapper_grace: options.wrapper_grace,
1984 wrapper_grace_counter: wrapper_grace_counter.clone(),
1985 report_slow: options.progress,
1986 filtered_timings: Default::default(),
1987 trace: Trace::default(),
1988 effects_baseline: std::sync::OnceLock::new(),
1989 };
1990 session.note(&format!("tracing `{}`", bin.name));
1991 let started = Instant::now();
1992 let trace_env = trace_path.to_string_lossy().into_owned();
1993 let trace = [("TMT_TRACE", trace_env.as_str())];
1994 let isolated_test = match &bin.runner {
1995 Runner::Isolated { test, .. } => Some(test.clone()),
1996 _ => None,
1997 };
1998 match run_baseline(
1999 &bin,
2000 if options.source_only { &[] } else { &trace },
2001 baseline_budget,
2002 &work.join(format!("baseline-{index}.log")),
2003 false,
2004 )? {
2005 BaselineRun::Passed => {}
2006 BaselineRun::TimedOut {
2007 elapsed,
2008 log,
2009 log_summary,
2010 } => {
2011 let log_path =
2012 log.unwrap_or_else(|| work.join(format!("baseline-{index}.log")));
2013 let (rerun_args, exclude_args) = match &bin.runner {
2014 Runner::Isolated { test, .. } => (
2015 vec!["--include-test".to_string(), test.clone()],
2016 vec!["--exclude-test".to_string(), test.clone()],
2017 ),
2018 Runner::Exe(_) => {
2019 let target = bin
2020 .name
2021 .rsplit_once("::")
2022 .map_or(bin.name.as_str(), |(_, t)| t)
2023 .to_string();
2024 (vec!["--test-target".to_string(), target], vec![])
2025 }
2026 Runner::Nextest { .. } | Runner::Doc { .. } => (vec![], vec![]),
2027 };
2028 let completed =
2029 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2030 let diagnostic = report::BaselineTimeoutDiagnostic {
2031 schema_version: report::SCHEMA_VERSION,
2032 package: package.name.clone(),
2033 stage: baseline_stage,
2034 runner: bin.name.clone(),
2035 test: isolated_test,
2036 elapsed_seconds: round_millis(elapsed),
2037 budget_seconds: baseline_budget.as_secs(),
2038 completed_baselines: completed,
2039 total_baselines,
2040 partial_baseline: true,
2041 log: log_path,
2042 lines: options.lines.clone(),
2043 rerun_args,
2044 exclude_args,
2045 completed_timings: Vec::new(),
2046 log_summary,
2047 };
2048 return Err(BaselinePoolError::Timeout(Box::new(diagnostic)).into());
2049 }
2050 BaselineRun::Failed {
2051 reason,
2052 elapsed,
2053 log,
2054 log_summary,
2055 } => {
2056 let completed =
2057 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2058 let diagnostic = report::BaselineFailureDiagnostic {
2059 schema_version: report::SCHEMA_VERSION,
2060 package: package.name.clone(),
2061 stage: baseline_stage,
2062 runner: bin.name.clone(),
2063 test: isolated_test,
2064 reason,
2065 elapsed_seconds: round_millis(elapsed),
2066 completed_baselines: completed,
2067 total_baselines,
2068 log,
2069 completed_timings: Vec::new(),
2070 log_summary,
2071 };
2072 return Err(BaselinePoolError::Failed(Box::new(diagnostic)).into());
2073 }
2074 }
2075 bin.traced = started.elapsed();
2076 bin.baseline = bin.traced;
2077 if options.source_only {
2078 bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
2079 }
2080 if !options.source_only && bin.traced > SLOW_TRACE {
2083 let started = Instant::now();
2084 match run_baseline(
2085 &bin,
2086 &[],
2087 bin.traced,
2088 &work.join(format!("baseline-{index}-untraced.log")),
2089 true,
2090 )? {
2091 BaselineRun::Passed => {
2092 let elapsed = started.elapsed();
2093 bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
2094 bin.baseline = elapsed;
2095 }
2096 BaselineRun::TimedOut { .. } => {
2097 bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
2098 }
2099 BaselineRun::Failed {
2100 reason,
2101 elapsed,
2102 log,
2103 log_summary,
2104 } => {
2105 let completed =
2106 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2107 let diagnostic = report::BaselineFailureDiagnostic {
2108 schema_version: report::SCHEMA_VERSION,
2109 package: package.name.clone(),
2110 stage: "baseline_untraced",
2111 runner: bin.name.clone(),
2112 test: isolated_test,
2113 reason,
2114 elapsed_seconds: round_millis(elapsed),
2115 completed_baselines: completed,
2116 total_baselines,
2117 log,
2118 completed_timings: Vec::new(),
2119 log_summary,
2120 };
2121 return Err(BaselinePoolError::Failed(Box::new(diagnostic)).into());
2122 }
2123 }
2124 }
2125 let make_baseline_failure =
2128 |stage: &'static str, reason: &'static str, log: PathBuf, detail: String| {
2129 let completed =
2130 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2131 BaselinePoolError::Failed(Box::new(report::BaselineFailureDiagnostic {
2132 schema_version: report::SCHEMA_VERSION,
2133 package: package.name.clone(),
2134 stage,
2135 runner: bin.name.clone(),
2136 test: isolated_test.clone(),
2137 reason,
2138 elapsed_seconds: round_millis(bin.baseline),
2139 completed_baselines: completed,
2140 total_baselines,
2141 log,
2142 completed_timings: Vec::new(),
2143 log_summary: vec![detail],
2144 }))
2145 };
2146 let text = match fs::read_to_string(&trace_path) {
2147 Ok(text) => text,
2148 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
2149 Err(err) => {
2150 return Err(make_baseline_failure(
2151 baseline_stage,
2152 "failed to read baseline trace",
2153 trace_path.clone(),
2154 format!("cannot read the trace of `{}`: {err}", bin.name),
2155 )
2156 .into());
2157 }
2158 };
2159 bin.trace = Trace::parse(&text);
2160 if bin.trace.malformed_lines > 0 {
2161 return Err(make_baseline_failure(
2162 baseline_stage,
2163 "produced a malformed baseline trace",
2164 trace_path.clone(),
2165 format!(
2166 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
2167 bin.name, bin.trace.malformed_lines
2168 ),
2169 )
2170 .into());
2171 }
2172 if let Runner::Exe(exe) = &bin.runner {
2173 bin.tests = match list_tests(
2174 exe,
2175 &bin.cwd,
2176 &work,
2177 false,
2178 false,
2179 work_lock.as_deref(),
2180 ) {
2181 Ok(tests) => tests,
2182 Err(err)
2183 if crate::interrupt::is_interrupted()
2184 || crate::interrupt::is_interrupted_err(&err) =>
2185 {
2186 return Err(err);
2187 }
2188 Err(err) => {
2189 return Err(make_baseline_failure(
2190 baseline_stage,
2191 "failed to list baseline tests",
2192 exe.clone(),
2193 format!("{err:#}"),
2194 )
2195 .into());
2196 }
2197 };
2198 }
2199 if let Ok(mut timings) = completed_timings.lock() {
2200 timings.push(report::BaselineTimingEntry {
2201 runner: bin.name.clone(),
2202 test: isolated_test,
2203 elapsed_seconds: round_millis(bin.baseline),
2204 });
2205 }
2206 completed_baselines.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
2207 Ok(bin)
2208 })();
2209 progress.complete(if result.is_ok() {
2210 progress::Outcome::Survived
2211 } else {
2212 progress::Outcome::Failed
2213 });
2214 result
2215 })
2216 });
2217 let collect_completed_timings = || -> Vec<report::BaselineTimingEntry> {
2218 let mut timings = completed_timings
2219 .lock()
2220 .unwrap_or_else(|e| e.into_inner())
2221 .clone();
2222 timings.sort_by(|a, b| {
2223 b.elapsed_seconds
2224 .total_cmp(&a.elapsed_seconds)
2225 .then_with(|| a.runner.cmp(&b.runner))
2226 });
2227 timings
2228 };
2229 session.binaries = match baseline_result {
2230 Ok(binaries) => binaries,
2231 Err(err) => match err.downcast::<BaselinePoolError>() {
2232 Ok(BaselinePoolError::Timeout(mut diagnostic)) => {
2233 diagnostic.completed_baselines =
2236 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2237 diagnostic.completed_timings = collect_completed_timings();
2238 let write_status = serde_json::to_string_pretty(&diagnostic)
2239 .map_err(anyhow::Error::from)
2240 .and_then(|json| {
2241 use std::io::Write as _;
2242 static NEXT_DIAG_TMP: std::sync::atomic::AtomicUsize =
2243 std::sync::atomic::AtomicUsize::new(0);
2244 let seq = NEXT_DIAG_TMP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2245 let tmp = work.join(format!(
2246 ".baseline-timeout.{}.{seq}.tmp",
2247 std::process::id()
2248 ));
2249 let mut file = fs::OpenOptions::new()
2250 .write(true)
2251 .create_new(true)
2252 .open(&tmp)?;
2253 if let Err(err) = file
2254 .write_all(format!("{json}\n").as_bytes())
2255 .and_then(|()| file.flush())
2256 {
2257 drop(file);
2258 let _ = fs::remove_file(&tmp);
2259 return Err(err.into());
2260 }
2261 drop(file);
2262 if let Err(rename_err) = fs::rename(&tmp, &diagnostic_path) {
2263 let _ = fs::remove_file(&tmp);
2264 return Err(rename_err.into());
2265 }
2266 Ok(())
2267 });
2268 let diag_note = match write_status {
2269 Ok(()) => format!("diagnostic: {}", diagnostic_path.display()),
2270 Err(write_err) => format!(
2271 "failed to write diagnostic {}: {write_err}",
2272 diagnostic_path.display()
2273 ),
2274 };
2275 let subject = match &diagnostic.test {
2276 Some(test) => format!("`{}` (test `{test}`)", diagnostic.runner),
2277 None => format!("`{}`", diagnostic.runner),
2278 };
2279 let hint =
2280 if !diagnostic.rerun_args.is_empty() && !diagnostic.exclude_args.is_empty() {
2281 format!(
2282 "; rerun separately with `{}` or exclude with `{}`",
2283 diagnostic.rerun_args.join(" "),
2284 diagnostic.exclude_args.join(" ")
2285 )
2286 } else if !diagnostic.rerun_args.is_empty() {
2287 format!(
2288 "; rerun separately with `{}`",
2289 diagnostic.rerun_args.join(" ")
2290 )
2291 } else {
2292 String::new()
2293 };
2294 let timings_section = format_baseline_timings_section(
2295 &diagnostic.completed_timings,
2296 &diagnostic.runner,
2297 diagnostic.elapsed_seconds,
2298 "timed out",
2299 diagnostic.total_baselines,
2300 );
2301 let summary_section = format_log_summary_section(&diagnostic.log_summary);
2302 let message = format!(
2303 "baseline timeout in stage `{}` for {subject}: elapsed {:.3}s exceeded budget {}s (increase with --baseline-timeout <SECONDS>; completed {}/{} baselines; partial baseline was not used as a complete trace); {diag_note}; log: {}{hint}{timings_section}{summary_section}",
2304 diagnostic.stage,
2305 diagnostic.elapsed_seconds,
2306 diagnostic.budget_seconds,
2307 diagnostic.completed_baselines,
2308 diagnostic.total_baselines,
2309 diagnostic.log.display()
2310 );
2311 return Err(BaselineError::Timeout {
2312 diagnostic,
2313 wrapper_grace_outcomes: wrapper_grace_counter.as_ref().map(|c| c.snapshot()),
2314 message,
2315 }
2316 .into());
2317 }
2318 Ok(BaselinePoolError::Failed(mut diagnostic)) => {
2319 diagnostic.completed_baselines =
2320 completed_baselines.load(std::sync::atomic::Ordering::Acquire);
2321 diagnostic.completed_timings = collect_completed_timings();
2322 let timings_section = format_baseline_timings_section(
2323 &diagnostic.completed_timings,
2324 &diagnostic.runner,
2325 diagnostic.elapsed_seconds,
2326 "failed",
2327 diagnostic.total_baselines,
2328 );
2329 let summary_section = format_log_summary_section(&diagnostic.log_summary);
2330 let message = format!(
2331 "the tests in `{}` {}; full output: {}{timings_section}{summary_section}",
2332 diagnostic.runner,
2333 diagnostic.reason,
2334 diagnostic.log.display()
2335 );
2336 return Err(BaselineError::Failed {
2337 diagnostic,
2338 wrapper_grace_outcomes: wrapper_grace_counter.as_ref().map(|c| c.snapshot()),
2339 message,
2340 }
2341 .into());
2342 }
2343 Err(other) => return Err(other),
2344 },
2345 };
2346
2347 for file in &files {
2349 for site in &file.sites {
2350 if disabled.contains(&site.id) {
2351 let fallback = options.rebuild
2352 && !matches!(site.kind, SiteKind::Body { .. })
2353 && !instrument::source_mutants(site).is_empty();
2354 match site.kind {
2355 SiteKind::Body { .. } => report.unviable_mutants += 1,
2356 _ if fallback => {}
2357 _ => report.skipped_sites += 1,
2358 }
2359 report.skipped.push(report::SkippedSite::new(
2360 report::location(&file.display, site),
2361 file.lines.position(&file.original, site.end),
2362 if fallback {
2363 report::SkipReason::ProbeReplacedBySourceRebuild
2364 } else {
2365 report::SkipReason::ProbeCompileError
2366 },
2367 repairs.get(&site.id).cloned(),
2368 ));
2369 }
2370 }
2371 if !options.rebuild && !options.source_only {
2372 report.skipped.extend(file.rebuild_sites.iter().map(|site| {
2373 report::SkippedSite::new(
2374 report::location(&file.display, site),
2375 file.lines.position(&file.original, site.end),
2376 report::SkipReason::RequiresSourceRebuild,
2377 None,
2378 )
2379 }));
2380 }
2381 }
2382 if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
2383 checkpoint.start(
2384 identity,
2385 serde_json::json!({
2386 "package": &package.name, "analysis": &report.analysis,
2387 "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
2388 "jobs": effective_jobs, "tool_version": env!("CARGO_PKG_VERSION")
2389 }),
2390 )?;
2391 }
2392 let phase = |name: &str, keys: Vec<String>| {
2393 checkpoint
2394 .as_ref()
2395 .zip(identity.as_deref())
2396 .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
2397 .transpose()
2398 };
2399 let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
2400 if checkpoint.is_none() {
2401 return Ok(None);
2402 }
2403 let locations: BTreeMap<_, _> = files
2404 .iter()
2405 .flat_map(|file| {
2406 file.sites
2407 .iter()
2408 .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
2409 })
2410 .collect();
2411 let keys = jobs
2412 .iter()
2413 .map(|job| {
2414 let tests = job
2415 .tests
2416 .iter()
2417 .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
2418 .collect::<Vec<_>>();
2419 serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
2420 })
2421 .collect::<std::result::Result<Vec<_>, _>>()?;
2422 phase(name, keys)
2423 };
2424 let scratch = work.clone();
2425 let mut jobs: Vec<Job> = vec![];
2426 let mut not_evaluated: HashSet<u32> = HashSet::new();
2429 let mut site_work: Vec<SiteWork> = vec![];
2430 let mut effect_jobs: Vec<(usize, usize)> = vec![];
2432 for file in &files {
2433 let mut primitive_arith_spans: HashSet<(usize, usize)> = HashSet::new();
2436 let mut primitive_cmp_spans: HashSet<(usize, usize)> = HashSet::new();
2437 let mut cast_probe_spans: std::collections::HashMap<(usize, usize), (u32, u32)> =
2438 std::collections::HashMap::new();
2439 for other in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2440 if matches!(other.kind, SiteKind::Cmp { .. })
2441 && session
2442 .binaries
2443 .iter()
2444 .any(|b| b.trace.bounds.contains_key(&other.id))
2445 {
2446 primitive_cmp_spans.insert((other.start, other.end));
2447 }
2448 if let SiteKind::Arith { cast_probes, .. } = &other.kind {
2449 let seen = session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
2450 if !seen.opaque && (seen.same || seen.differs || seen.same2 || seen.differs2) {
2451 primitive_arith_spans.insert((other.start, other.end));
2452 }
2453 for &(slot, start, end) in cast_probes {
2454 cast_probe_spans
2455 .entry((start, end))
2456 .or_insert((other.id, slot));
2457 }
2458 }
2459 }
2460 let primitive = |from: usize, to: usize| {
2461 let Some(mut text) = file.original.get(from..to) else {
2462 return false;
2463 };
2464 let mut start = from;
2465 loop {
2466 let trimmed = text.trim_start();
2467 start += text.len() - trimmed.len();
2468 text = trimmed.trim_end();
2469 if text.starts_with('(')
2470 && text.ends_with(')')
2471 && matches!(syn::parse_str::<syn::Expr>(text), Ok(syn::Expr::Paren(_)))
2472 && let Some(inner) = text
2473 .strip_prefix('(')
2474 .and_then(|inner| inner.strip_suffix(')'))
2475 {
2476 start += 1;
2477 text = inner;
2478 } else {
2479 break;
2480 }
2481 }
2482 primitive_arith_spans.contains(&(start, start + text.len()))
2483 };
2484 let cast_bounds = |from: usize, to: usize| -> Option<(i128, i128)> {
2485 let &(owner_id, slot) = cast_probe_spans.get(&(from, to))?;
2486 let mut recorded = session
2487 .binaries
2488 .iter()
2489 .filter_map(|b| b.trace.cast_bounds.get(&(owner_id, slot)));
2490 let first = recorded.next()?;
2491 if recorded.all(|other| other == first) {
2492 *first
2493 } else {
2494 None
2495 }
2496 };
2497 let primitive_cmp = |from: usize, to: usize| primitive_cmp_spans.contains(&(from, to));
2498 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2499 let plan = match session.plan(
2500 &file.display,
2501 site,
2502 options.verify,
2503 &primitive,
2504 &primitive_cmp,
2505 &cast_bounds,
2506 ) {
2507 Planned::Unreached if beyond.contains(&site.id) => continue,
2510 Planned::Unreached => {
2511 let at = report::location(&file.display, site);
2513 if report.unreached.last() != Some(&at) {
2514 report.unreached.push(at);
2515 }
2516 continue;
2517 }
2518 Planned::Nothing => continue,
2519 Planned::NotEvaluated => {
2520 not_evaluated.insert(site.id);
2521 continue;
2522 }
2523 Planned::Plan(plan) => plan,
2524 };
2525 let mut add =
2526 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
2527 jobs.push(session.job(site.id, mutation, tests_of));
2528 jobs.len() - 1
2529 };
2530 let gaps = plan
2531 .gaps
2532 .into_iter()
2533 .map(
2534 |PlannedGap {
2535 finding,
2536 survivors,
2537 constant_expr,
2538 }| {
2539 let confirm = if options.verify {
2542 survivors
2543 .into_iter()
2544 .map(|m| add(m, &*plan.reaching))
2545 .collect()
2546 } else {
2547 vec![]
2548 };
2549 (finding, confirm, constant_expr)
2550 },
2551 )
2552 .collect();
2553 let infected = &plan.infected;
2554 let runs = plan
2555 .run
2556 .iter()
2557 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
2558 .collect();
2559 site_work.push(SiteWork {
2560 file: &file.display,
2561 site,
2562 gaps,
2563 constant: plan.constant,
2564 cannot_differ: plan.cannot_differ,
2565 redundant_logic_swap: plan.redundant_logic_swap,
2566 runs,
2567 });
2568 }
2569 }
2570 session.note(&format!(
2571 "running {} mutants on {} thread(s)",
2572 jobs.len(),
2573 options.jobs.max(1)
2574 ));
2575 let probe_checkpoint = probe_phase("probe", &jobs)?;
2576 let mut results =
2577 session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
2578 if crate::interrupt::is_interrupted() {
2579 report.interrupted = true;
2580 }
2581 for result in &results {
2582 report.timeout_rechecks.include(result);
2583 }
2584
2585 if !report.interrupted
2588 && let Some(wanted) = options.audit
2589 {
2590 match run_audit_phase(
2591 &session,
2592 &files,
2593 &jobs,
2594 &mut results,
2595 &mut report.timeout_rechecks,
2596 &scratch,
2597 wanted,
2598 options.jobs,
2599 &probe_phase,
2600 ) {
2601 Ok(audit) => report.audit = Some(audit),
2602 Err(err)
2603 if crate::interrupt::is_interrupted()
2604 || crate::interrupt::is_interrupted_err(&err) =>
2605 {
2606 report.interrupted = true;
2607 }
2608 Err(err) => return Err(err),
2609 }
2610 if crate::interrupt::is_interrupted() {
2611 report.interrupted = true;
2612 }
2613 }
2614 #[derive(Clone, Copy, PartialEq, Eq)]
2618 enum EarlierVerdict {
2619 Killed,
2620 Survived,
2621 Unknown,
2622 }
2623 let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
2624 let asked: Vec<usize> = site_work
2625 .iter()
2626 .filter(|item| beyond.contains(&item.site.id))
2627 .flat_map(|item| {
2628 item.gaps
2629 .iter()
2630 .flat_map(|(_, confirm, _)| confirm.iter().copied())
2631 .chain(
2632 item.runs
2633 .iter()
2634 .filter(|(m, _)| !(*m == Mutation::LogicSwap && item.redundant_logic_swap))
2635 .map(|(_, job)| *job),
2636 )
2637 })
2638 .filter(|job| results[*job].survived.is_some())
2639 .collect();
2640 if !report.interrupted && !asked.is_empty() {
2641 let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
2642 session.note(&format!(
2643 "running {} surviving mutants against the tests as they were at {revision}",
2644 asked.len()
2645 ));
2646 let suffix = |file: &SourceFile| {
2647 if file.path == root_file {
2648 root_suffix.as_str()
2649 } else {
2650 ""
2651 }
2652 };
2653 let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
2655 .iter()
2656 .map(|(path, hunks)| {
2657 let file = files.iter().find(|file| file.path == *path)?;
2658 let rendered = file.rendered.as_ref()?;
2659 let mut places = hunks
2660 .iter()
2661 .map(|hunk| {
2662 let (from, to) = scope::range_of(&file.original, hunk);
2663 Some((rendered.copied(from, to)?, hunk.old.as_str()))
2664 })
2665 .collect::<Option<Vec<_>>>()?;
2666 places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
2667 let mut text = rendered.text.clone();
2668 for ((from, to), old) in places {
2669 text.replace_range(from..to, old);
2670 }
2671 Some((file, text))
2672 })
2673 .collect();
2674 let attempted = if let Some(earlier) = earlier {
2675 let attempted = (|| -> Result<Option<Vec<JobResult>>> {
2676 for (file, text) in &earlier {
2677 state.write(&file.path, &format!("{text}{}", suffix(file)))?;
2678 }
2679 if !cargo_build()?.status.success() {
2680 session.note(
2681 "the tests as they were do not build with the code as it is: what they found out is not known",
2682 );
2683 return Ok(None);
2684 }
2685 let all: Vec<&TestBinary> = session.binaries.iter().collect();
2687 if run_source_tests(&all)? != Outcome::Pass {
2688 session.note(
2689 "the tests as they were fail on the code as it is: what they found out is not known",
2690 );
2691 return Ok(None);
2692 }
2693 let against_all: Vec<Job> = asked
2694 .iter()
2695 .map(|job| Job {
2696 site: jobs[*job].site,
2697 mutation: jobs[*job].mutation,
2698 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
2699 })
2700 .collect();
2701 session
2702 .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
2703 .map(Some)
2704 })();
2705 for (file, _) in &earlier {
2707 let rendered = file.rendered.as_ref().expect("rendered before building");
2708 state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
2709 }
2710 if !crate::interrupt::is_interrupted() {
2711 match cargo_build() {
2712 Ok(output) if output.status.success() => {}
2713 Ok(_) => {
2714 bail!("the crate does not build once its tests are put back as they are");
2715 }
2716 Err(err)
2717 if crate::interrupt::is_interrupted()
2718 || crate::interrupt::is_interrupted_err(&err) =>
2719 {
2720 report.interrupted = true;
2721 }
2722 Err(err) => return Err(err),
2723 }
2724 } else {
2725 report.interrupted = true;
2726 }
2727 attempted
2728 } else {
2729 session.note(
2730 "not all changed test files could be restored as they were: what they found out is not known",
2731 );
2732 Ok(None)
2733 };
2734 match attempted {
2735 Ok(Some(again)) => {
2736 for (job, result) in asked.iter().zip(again) {
2737 let verdict = if result.unable || result.unconfirmed_timeout {
2738 EarlierVerdict::Unknown
2739 } else if result.survived.is_none() {
2740 EarlierVerdict::Killed
2741 } else {
2742 EarlierVerdict::Survived
2743 };
2744 earlier_verdict.insert(*job, verdict);
2745 }
2746 }
2747 Ok(None) => {
2748 for job in &asked {
2749 earlier_verdict.insert(*job, EarlierVerdict::Unknown);
2750 }
2751 }
2752 Err(err)
2753 if crate::interrupt::is_interrupted()
2754 || crate::interrupt::is_interrupted_err(&err) =>
2755 {
2756 report.interrupted = true;
2757 for job in &asked {
2758 earlier_verdict.insert(*job, EarlierVerdict::Unknown);
2759 }
2760 }
2761 Err(err) => return Err(err),
2762 }
2763 if crate::interrupt::is_interrupted() {
2764 report.interrupted = true;
2765 }
2766 }
2767 let pre_job_not_evaluated = not_evaluated.len();
2768 let unable = results
2769 .iter()
2770 .filter(|r| r.unable || r.unconfirmed_timeout)
2771 .count();
2772 not_evaluated.extend(
2773 jobs.iter()
2774 .zip(&results)
2775 .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
2776 .map(|(job, _)| job.site),
2777 );
2778 if !options.rebuild || report.interrupted {
2779 report.mutants_not_evaluated = pre_job_not_evaluated + unable;
2780 }
2781 report.mutants_run = results.len() - unable;
2782 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
2783 report.mutants_survived = report.mutants_run - report.mutants_killed;
2784 report.mutants_timed_out = results
2785 .iter()
2786 .filter(|r| r.timed_out && !r.unconfirmed_timeout)
2787 .count();
2788
2789 let mut finding_run_survivors: Vec<usize> = vec![];
2792 let mut killed_by_loc: BTreeMap<(String, usize, usize, &'static str), usize> = BTreeMap::new();
2794
2795 let confirmed = |w: &SiteWork| {
2798 w.gaps
2799 .iter()
2800 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
2801 };
2802 let constants: BTreeSet<(&str, usize, usize)> = site_work
2803 .iter()
2804 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
2805 .map(|w| (w.file, w.site.start, w.site.end))
2806 .collect();
2807 for item in &site_work {
2808 let at = report::location(item.file, item.site);
2809 for (finding, confirm, constant_expr) in &item.gaps {
2810 let repeats = constant_expr
2813 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
2814 let survived_count = confirm
2815 .iter()
2816 .filter(|j| results[**j].survived.is_some())
2817 .count();
2818 if beyond.contains(&item.site.id) {
2819 let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
2821 let killed_before = confirm
2822 .iter()
2823 .any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
2824 if confirmed && !repeats && killed_before {
2825 report.weakened.push(finding.at().clone());
2826 report.findings.push(finding.clone());
2827 finding_run_survivors.push(survived_count);
2828 } else if !confirmed {
2829 report.survivor_breakdown.unconfirmed_gap += survived_count;
2830 } else if repeats {
2831 report.survivor_breakdown.redundant_constant += survived_count;
2832 } else {
2833 for job in confirm {
2834 if results[*job].survived.is_some() {
2835 if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
2836 report.survivor_breakdown.preexisting_unchanged += 1;
2837 } else {
2838 report.survivor_breakdown.unchanged_not_compared += 1;
2839 }
2840 }
2841 }
2842 }
2843 continue;
2844 }
2845 match Prediction::of(confirm.iter().map(|j| &results[*j])) {
2846 Prediction::Refuted => {
2847 report.unstable.push(at.clone());
2848 report.survivor_breakdown.unconfirmed_gap += survived_count;
2849 }
2850 Prediction::Confirmed if !repeats => {
2851 report.findings.push(finding.clone());
2852 finding_run_survivors.push(survived_count);
2853 }
2854 Prediction::Confirmed => {
2855 report.survivor_breakdown.redundant_constant += survived_count;
2856 }
2857 Prediction::Unknown => {
2859 report.survivor_breakdown.unconfirmed_gap += survived_count;
2860 }
2861 }
2862 }
2863 if let SiteKind::Body {
2866 sole_expr: Some((start, end)),
2867 ..
2868 } = item.site.kind
2869 && constants.contains(&(item.file, start, end))
2870 {
2871 report.survivor_breakdown.redundant_constant += item
2872 .runs
2873 .iter()
2874 .filter(|(_, job)| results[*job].survived.is_some())
2875 .count();
2876 continue;
2877 }
2878 let mut survivors = vec![];
2879 let mut passing_tests = BTreeSet::new();
2880 for (mutation, job) in &item.runs {
2881 let res = &results[*job];
2882 if !res.unable && !res.unconfirmed_timeout && res.survived.is_none() {
2883 *killed_by_loc
2884 .entry((
2885 item.file.to_string(),
2886 item.site.line,
2887 item.site.column,
2888 "assertion_gap",
2889 ))
2890 .or_insert(0) += 1;
2891 }
2892 if let Some(tests) = &res.survived {
2893 if *mutation == Mutation::LogicSwap && item.redundant_logic_swap {
2894 report.survivor_breakdown.redundant_constant += 1;
2895 continue;
2896 }
2897 if beyond.contains(&item.site.id) {
2898 match earlier_verdict.get(job) {
2899 Some(EarlierVerdict::Killed) => {}
2900 Some(EarlierVerdict::Survived) => {
2901 report.survivor_breakdown.preexisting_unchanged += 1;
2902 continue;
2903 }
2904 Some(EarlierVerdict::Unknown) | None => {
2905 report.survivor_breakdown.unchanged_not_compared += 1;
2906 continue;
2907 }
2908 }
2909 }
2910 survivors.push(report::describe(item.site, *mutation));
2911 passing_tests.extend(tests.iter().cloned());
2912 }
2913 }
2914 if !survivors.is_empty() {
2915 let first = item.runs.iter().find(|(mutation, job)| {
2917 !(*mutation == Mutation::LogicSwap && item.redundant_logic_swap)
2918 && results[*job].survived.is_some()
2919 && (!beyond.contains(&item.site.id)
2920 || earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
2921 });
2922 if beyond.contains(&item.site.id) {
2923 report.weakened.push(at.clone());
2924 }
2925 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
2926 finding_run_survivors.push(survivors.len());
2927 report.findings.push(Finding::AssertionGap {
2928 at,
2929 survivors,
2930 tests: passing_tests.into_iter().collect(),
2931 effects: vec![],
2932 effects_of: None,
2933 witness: None,
2934 });
2935 }
2936 }
2937
2938 if !report.interrupted && options.effects && !effect_jobs.is_empty() {
2940 match run_effects_phase(
2941 &session,
2942 &files,
2943 &jobs,
2944 &effect_jobs,
2945 &scratch,
2946 options.jobs,
2947 &mut report.findings,
2948 ) {
2949 Ok(()) => {}
2950 Err(err)
2951 if crate::interrupt::is_interrupted()
2952 || crate::interrupt::is_interrupted_err(&err) =>
2953 {
2954 report.interrupted = true;
2955 }
2956 Err(err) => return Err(err),
2957 }
2958 if crate::interrupt::is_interrupted() {
2959 report.interrupted = true;
2960 }
2961 }
2962
2963 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
2967 let build_regular_mutants = options.rebuild || options.source_only;
2968 let mut index = 0;
2969 for file in &files {
2970 let retried = file.sites.iter().filter(|site| {
2973 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
2974 || not_evaluated.contains(&site.id)
2975 });
2976 for site in file.rebuild_sites.iter().chain(retried) {
2977 let mutants = source_mutants(file, site, true);
2978 if build_regular_mutants {
2979 built.extend(mutants.into_iter().filter_map(|mutant| {
2980 let selected = in_shard(index);
2981 index += 1;
2982 selected.then_some((file, site, mutant, None))
2983 }));
2984 } else {
2985 report.mutants_not_built += mutants.len();
2986 }
2987 }
2988 }
2989 if !build_regular_mutants {
2990 report.mutants_not_built += not_built_witnesses;
2991 }
2992 if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
2995 let mut twins = vec![];
2996 for file in &files {
2997 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2998 let integers = session.binaries.iter().all(|bin| {
3000 let seen = bin.trace.merged(site.id);
3001 !seen.reached() || seen.valued()
3002 });
3003 let candidates = jobs_for_site(&jobs, site.id);
3004 let job_of = |mutation: Mutation| {
3005 candidates
3006 .clone()
3007 .find(|&index| jobs[index].mutation == mutation)
3008 };
3009 let mut compared = vec![];
3010 let mut mutants = instrument::source_mutants(site);
3011 instrument::keep_line_ends(&file.original, &mut mutants);
3012 for mutant in mutants {
3013 let job = mutations_like(site, &mutant, integers)
3015 .into_iter()
3016 .find_map(job_of);
3017 if let Some(job) = job {
3018 compared.push(job);
3019 twins.push((file, site, mutant, Some(job)));
3020 }
3021 }
3022 if let (SiteKind::Cmp { op, .. }, Some(job)) =
3025 (&site.kind, job_of(Mutation::Negate))
3026 && !compared.contains(&job)
3027 {
3028 let negated = instrument::SourceMutant {
3029 start: site.start,
3030 end: site.end,
3031 replacement: format!("!({})", site.text),
3032 what: op.symbol().to_string(),
3033 into: "!".to_string(),
3034 };
3035 twins.push((file, site, negated, Some(job)));
3036 }
3037 }
3038 }
3039 let chosen = spread(twins.len(), wanted);
3040 audit.rebuilt = chosen.len();
3041 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
3042 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
3043 }
3044 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
3045 by_speed.sort_by_key(|bin| bin.baseline);
3046 let root_mutant_suffix = if files.iter().any(|file| {
3048 file.path != root_file
3049 && file
3050 .rendered
3051 .as_ref()
3052 .is_some_and(|rendered| rendered.text != file.original)
3053 }) {
3054 root_suffix.as_str()
3055 } else {
3056 ""
3057 };
3058 if !built.is_empty() && report.interrupted {
3059 report.mutants_not_evaluated += built
3060 .iter()
3061 .filter(|(_, _, _, twin)| twin.is_none())
3062 .count();
3063 } else if !built.is_empty() {
3064 if options.timeout_seconds.is_some()
3065 && built
3066 .iter()
3067 .any(|(file, _, _, _)| built_sources.contains(file))
3068 {
3069 for bin in &by_speed {
3070 bin.warn_timeout_conflict(None);
3071 }
3072 }
3073 let source_checkpoint = if checkpoint.is_some() {
3074 let keys = built
3075 .iter()
3076 .map(|(file, _, mutation, twin)| {
3077 serde_json::to_string(&(
3078 &file.display,
3079 mutation.start,
3080 mutation.end,
3081 &mutation.replacement,
3082 twin,
3083 ))
3084 })
3085 .collect::<std::result::Result<Vec<_>, _>>()?;
3086 phase("source", keys)?
3087 } else {
3088 None
3089 };
3090 session.note(&format!(
3091 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
3092 built.len()
3093 ));
3094 let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
3095 if file.path == root_file {
3096 format!("{text}{suffix}")
3097 } else {
3098 text.to_string()
3099 }
3100 };
3101 let mut skipped_targets = BTreeSet::new();
3104 let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
3106 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
3107 progress::track(
3108 options.progress,
3109 "source mutants",
3110 built.len(),
3111 |progress| -> Result<()> {
3112 for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
3113 if crate::interrupt::is_interrupted() {
3114 report.mutants_not_evaluated += built[index..]
3115 .iter()
3116 .filter(|(_, _, _, t)| t.is_none())
3117 .count();
3118 report.interrupted = true;
3119 break;
3120 }
3121 let cached = source_checkpoint
3122 .as_ref()
3123 .map(|phase| phase.get::<Option<Outcome>>(index))
3124 .transpose()?
3125 .flatten();
3126 let left_out = left_out
3127 .entry(&file.path)
3128 .or_insert_with(|| built_sources.left_out(file))
3129 .iter()
3130 .any(|(from, to)| *from <= site.start && site.end <= *to);
3131 if left_out || !built_sources.contains(file) {
3132 if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
3133 {
3134 phase.record(index, &Some(Outcome::Unable))?;
3135 }
3136 if twin.is_none() {
3137 report.mutants_not_evaluated += 1;
3138 report.mutants_not_compiled += 1;
3139 if skipped_targets.insert((&file.path, site.start, site.end)) {
3140 report.skipped.push(report::SkippedSite::new(
3141 report::location(&file.display, site),
3142 file.lines.position(&file.original, site.end),
3143 report::SkipReason::SourceNotBuilt,
3144 left_out.then(|| {
3145 "under a `cfg` that the features of this build turn off"
3146 .to_string()
3147 }),
3148 ));
3149 }
3150 } else if let Some(audit) = report.audit.as_mut() {
3151 audit.not_compared += 1;
3152 }
3153 progress.complete(progress::Outcome::Unable);
3154 continue;
3155 }
3156 let outcome = if let Some(cached) = cached {
3157 cached
3158 } else {
3159 let mutated = format!(
3160 "{}{}{}",
3161 &file.original[..mutant.start],
3162 mutant.replacement,
3163 &file.original[mutant.end..]
3164 );
3165 let attempt = || -> Result<Option<Outcome>> {
3167 state.write(
3168 &file.path,
3169 &instrumented(file, &mutated, root_mutant_suffix),
3170 )?;
3171 match source_build(&cargo_build()?) {
3172 SourceBuild::Built => run_source_tests(&by_speed).map(Some),
3173 SourceBuild::Refused => Ok(None),
3174 SourceBuild::Failed(why) => {
3177 session.note(&format!(
3178 "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
3179 ));
3180 Ok(Some(Outcome::Unable))
3181 }
3182 }
3183 };
3184 let attempted = attempt();
3185 let rendered = file.rendered.as_ref().expect("rendered before building");
3187 state.write(
3188 &file.path,
3189 &instrumented(file, &rendered.text, &root_suffix),
3190 )?;
3191 let outcome = match attempted {
3192 Ok(outcome) => outcome,
3193 Err(err)
3194 if crate::interrupt::is_interrupted()
3195 || crate::interrupt::is_interrupted_err(&err) =>
3196 {
3197 report.mutants_not_evaluated += built[index..]
3198 .iter()
3199 .filter(|(_, _, _, t)| t.is_none())
3200 .count();
3201 report.interrupted = true;
3202 break;
3203 }
3204 Err(err) => return Err(err),
3205 };
3206 if let Some(phase) = &source_checkpoint
3209 && outcome != Some(Outcome::Unable)
3210 {
3211 phase.record(index, &outcome)?;
3212 }
3213 outcome
3214 };
3215 progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
3216 if let Some(job) = twin {
3217 let as_probe = results[*job].survived.is_some();
3219 let Some(audit) = report.audit.as_mut() else {
3220 continue;
3221 };
3222 match audit_source_comparison(&results[*job], outcome) {
3225 Some(disagrees) => {
3226 audit.compared += 1;
3227 if disagrees {
3228 let verdict =
3229 |passes: bool| if passes { "passes" } else { "fails" };
3230 audit.source_disagreements.push(report::SourceDisagreement {
3231 at: report::location(&file.display, site),
3232 mutant: report::describe(site, mutation_of(site, mutant)),
3233 as_probe: verdict(as_probe).to_string(),
3234 built: verdict(!as_probe).to_string(),
3235 });
3236 }
3237 }
3238 None => audit.not_compared += 1,
3239 }
3240 continue;
3241 }
3242 match outcome {
3243 None => report.unviable_mutants += 1,
3244 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
3245 Some(outcome) => {
3246 report.mutants_run += 1;
3247 if outcome != Outcome::Pass {
3248 report.mutants_killed += 1;
3249 *killed_by_loc
3250 .entry((
3251 file.display.clone(),
3252 site.line,
3253 site.column,
3254 "survivor",
3255 ))
3256 .or_insert(0) += 1;
3257 }
3258 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
3259 report.mutants_survived += (outcome == Outcome::Pass) as usize;
3260 }
3261 }
3262 let survived = outcome == Some(Outcome::Pass);
3263 if survived {
3264 let at = report::location(&file.display, site);
3265 let removed = mutant.replacement.trim().is_empty();
3267 let text = match (&site.kind, removed) {
3268 (SiteKind::Field { .. }, true) => {
3269 format!("without the field `{}`", report::one_line(&site.text))
3270 }
3271 (
3272 SiteKind::LiteralSet {
3273 receiver, argument, ..
3274 },
3275 true,
3276 ) => format!(
3277 "without `{}` in `{}.contains({})`",
3278 report::one_line(&mutant.into),
3279 report::one_line(receiver),
3280 report::one_line(argument)
3281 ),
3282 _ => report::describe(site, mutation_of(site, mutant)),
3283 };
3284 match survivors.last_mut() {
3285 Some((last, texts)) if *last == at => texts.push(text),
3286 _ => survivors.push((at, vec![text])),
3287 }
3288 }
3289 }
3290 Ok(())
3291 },
3292 )?;
3293 if !report.interrupted
3294 && let Some(phase) = &source_checkpoint
3295 {
3296 phase.finish_if_complete()?;
3297 }
3298 for (at, survivors) in survivors {
3299 finding_run_survivors.push(survivors.len());
3300 report.findings.push(Finding::Survivor {
3301 at,
3302 survivors,
3303 witness: None,
3304 change_since: None,
3305 advice: None,
3306 });
3307 }
3308 }
3309
3310 if !report.interrupted
3312 && let Some(revision) = options
3313 .since
3314 .as_deref()
3315 .filter(|_| !options.list && options.shard.is_none())
3316 {
3317 let hunks = scope::hunks(&since_diff(&workspace, revision)?);
3318 let not_built_changes = std::cell::Cell::new(0usize);
3319 let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
3320 .iter()
3321 .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
3322 .filter_map(|file| {
3323 let relative = file
3324 .path
3325 .strip_prefix(©)
3326 .ok()?
3327 .to_string_lossy()
3328 .replace('\\', "/");
3329 let of_file: Vec<_> = hunks
3330 .iter()
3331 .filter(|hunk| hunk.file == relative)
3332 .cloned()
3333 .collect();
3334 let mut changes = reverts::changes(&file.original, &of_file);
3335 if options.rebuild || options.source_only {
3338 for change in &mut changes {
3339 change.outside = change.undone.as_deref().is_some_and(|undone| {
3342 built_sources.same_program(file, &file.original, undone)
3343 });
3344 }
3345 not_built_changes.set(
3346 not_built_changes.get()
3347 + changes.iter().filter(|change| change.outside).count(),
3348 );
3349 }
3350 (!changes.is_empty()).then_some((file, changes))
3351 })
3352 .collect();
3353 let not_built_changes = not_built_changes.get();
3354 report.mutants_not_evaluated += not_built_changes;
3355 report.mutants_not_compiled += not_built_changes;
3356 let total: usize = changed
3358 .iter()
3359 .map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
3360 .sum();
3361 let mixed: usize = files
3364 .iter()
3365 .map(|file| {
3366 let relative = file
3367 .path
3368 .strip_prefix(©)
3369 .unwrap_or(&file.path)
3370 .to_string_lossy()
3371 .replace('\\', "/");
3372 let of_file: Vec<_> = hunks
3373 .iter()
3374 .filter(|hunk| hunk.file == relative)
3375 .cloned()
3376 .collect();
3377 reverts::mixed(&file.original, &of_file)
3378 })
3379 .sum();
3380 if mixed > 0 && (options.rebuild || options.source_only) {
3381 report.mutants_not_evaluated += mixed;
3382 session.note(&format!(
3383 "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
3384 ));
3385 }
3386 if !(options.rebuild || options.source_only) {
3387 report.mutants_not_built += not_built_reverts;
3388 } else if total > 0
3389 || changed.iter().any(|(_, changes)| {
3390 changes.iter().filter(|change| !change.is_subhunk()).count() > 1
3391 })
3392 {
3393 let reverts_result = (|| -> Result<()> {
3394 session.note(&format!(
3397 "building {total} changes undone, one by one (the code as it was at {})",
3398 report::short_revision(revision)
3399 ));
3400 let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
3401 let suffix = if file.path == root_file { suffix } else { "" };
3402 state.write(&file.path, &format!("{text}{suffix}"))
3403 };
3404 let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
3406 let attempted = (|| -> Result<Option<Outcome>> {
3407 for (file, text) in edits {
3408 write(file, text, root_mutant_suffix)?;
3409 }
3410 Ok(match source_build(&cargo_build()?) {
3411 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
3412 SourceBuild::Refused => None,
3413 SourceBuild::Failed(why) => {
3414 session.note(&format!(
3415 "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
3416 ));
3417 Some(Outcome::Unable)
3418 }
3419 })
3420 })();
3421 for (file, _) in edits {
3423 let rendered = file.rendered.as_ref().expect("rendered before building");
3424 write(file, &rendered.text, &root_suffix)?;
3425 }
3426 attempted
3427 };
3428 let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
3429 match outcome {
3430 None => report.unviable_mutants += 1,
3431 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
3432 Some(outcome) => {
3433 report.mutants_run += 1;
3434 report.mutants_killed += (outcome != Outcome::Pass) as usize;
3435 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
3436 report.mutants_survived += (outcome == Outcome::Pass) as usize;
3437 }
3438 }
3439 if outcome == Some(Outcome::Pass) {
3440 finding_run_survivors.push(1);
3441 report.findings.push(Finding::Survivor {
3442 at,
3443 survivors: vec![what],
3444 witness: None,
3445 advice: None,
3446 change_since: Some(revision.to_string()),
3447 });
3448 }
3449 };
3450 let place = |file: &SourceFile, change: &reverts::Change| report::Location {
3451 file: file.display.clone(),
3452 line: change.line,
3453 column: 1,
3454 code: change.code.clone(),
3455 ..Default::default()
3456 };
3457 let mut stuck_files = 0;
3460 for (file, changes) in &changed {
3461 let mut stuck = false;
3462 let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
3463 let whole_alone = changes
3464 .iter()
3465 .filter(|change| !change.is_subhunk() && !change.outside)
3466 .count();
3467 for change in changes.iter().filter(|change| !change.outside) {
3468 let outcome = match &change.undone {
3469 Some(text) => undone(&[(file, text.as_str())])?,
3470 None => None,
3471 };
3472 if !change.is_subhunk() {
3473 stuck |= outcome.is_none();
3474 }
3475 judged(outcome, place(file, change), change.describe());
3476 }
3477 let whole = reverts::all_undone(&file.original, changes);
3482 let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
3483 let tried: Vec<reverts::Change> = changes
3484 .iter()
3485 .filter(|change| !change.outside)
3486 .cloned()
3487 .collect();
3488 let left_out_matter = whole_alone < whole_total
3489 && match (&whole, reverts::all_undone(&file.original, &tried)) {
3490 (Some(all), Some(without)) => !same(all, &without),
3491 _ => true,
3492 };
3493 let another = whole
3495 .as_deref()
3496 .is_none_or(|all| !same(all, &file.original));
3497 if whole_total > 1 && another && (stuck || left_out_matter) {
3498 let outcome = match &whole {
3499 Some(text) => undone(&[(file, text.as_str())])?,
3500 None => None,
3501 };
3502 stuck = outcome.is_none();
3503 let first_whole = changes
3504 .iter()
3505 .find(|change| !change.is_subhunk())
3506 .unwrap_or(&changes[0]);
3507 judged(
3508 outcome,
3509 place(file, first_whole),
3510 format!("with all {whole_total} changes to this file undone"),
3511 );
3512 }
3513 stuck_files += usize::from(stuck);
3514 }
3515 let with_left_out = changed.iter().any(|(_, changes)| {
3519 changes
3520 .iter()
3521 .any(|change| !change.is_subhunk() && change.outside)
3522 });
3523 if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
3524 let whole: Option<Vec<String>> = changed
3525 .iter()
3526 .map(|(file, changes)| reverts::all_undone(&file.original, changes))
3527 .collect();
3528 let same = |file: &SourceFile, a: &str, b: &str| {
3529 built_sources.same_program(file, a, b)
3530 };
3531 let another = whole.as_ref().is_none_or(|texts| {
3533 changed
3534 .iter()
3535 .zip(texts)
3536 .any(|((file, _), text)| !same(file, text, &file.original))
3537 });
3538 let left_out_matter = whole.as_ref().is_none_or(|texts| {
3541 changed.iter().zip(texts).any(|((file, changes), text)| {
3542 let tried: Vec<reverts::Change> = changes
3543 .iter()
3544 .filter(|change| !change.outside)
3545 .cloned()
3546 .collect();
3547 reverts::all_undone(&file.original, &tried)
3548 .is_none_or(|without| !same(file, text, &without))
3549 })
3550 });
3551 if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
3552 let outcome = match &whole {
3553 Some(texts) => {
3554 let edits: Vec<(&SourceFile, &str)> = changed
3555 .iter()
3556 .zip(texts)
3557 .map(|((file, _), text)| (*file, text.as_str()))
3558 .collect();
3559 undone(&edits)?
3560 }
3561 None => None,
3562 };
3563 let (file, changes) = &changed[0];
3564 judged(
3565 outcome,
3566 place(file, &changes[0]),
3567 format!("with every change undone, in all {} files", changed.len()),
3568 );
3569 }
3570 }
3571 Ok(())
3572 })();
3573 match reverts_result {
3574 Ok(()) => {}
3575 Err(err)
3576 if crate::interrupt::is_interrupted()
3577 || crate::interrupt::is_interrupted_err(&err) =>
3578 {
3579 report.interrupted = true;
3580 }
3581 Err(err) => return Err(err),
3582 }
3583 }
3584 }
3585
3586 let mut witness_files: Vec<&PathBuf> = vec![];
3589 for candidate in &witness_candidates {
3590 if !witness_files.contains(&&candidate.file) {
3591 witness_files.push(&candidate.file);
3592 }
3593 }
3594 let witness_result = (|| -> Result<()> {
3595 for witness_file in witness_files {
3596 if report.interrupted || crate::interrupt::is_interrupted() {
3597 report.interrupted = true;
3598 break;
3599 }
3600 let in_root = *witness_file == root_file;
3601 let witness_candidates: Vec<&witness::Candidate> = witness_candidates
3602 .iter()
3603 .filter(|candidate| candidate.file == *witness_file)
3604 .collect();
3605 let file = files
3606 .iter()
3607 .find(|file| file.path == *witness_file)
3608 .expect("witness candidates are of files that are analysed");
3609 let rendered = file.rendered.as_ref().expect("rendered before building");
3610 let left_out_here = built_sources.left_out(file);
3611 let restore = if in_root {
3612 format!("{}{root_suffix}", rendered.text)
3613 } else {
3614 rendered.text.clone()
3615 };
3616 let library_runners: Vec<_> = session
3617 .binaries
3618 .iter()
3619 .filter(|bin| {
3620 root_exe
3621 .as_deref()
3622 .is_some_and(|exe| bin.runner.executable() == Some(exe))
3623 })
3624 .collect();
3625 let ignored = library_runners
3626 .iter()
3627 .find_map(|bin| match &bin.runner {
3628 Runner::Exe(exe) => Some(list_tests(
3629 exe,
3630 &bin.cwd,
3631 &bin.git_ceiling,
3632 true,
3633 false,
3634 bin.work_lock.as_deref(),
3635 )),
3636 _ => None,
3637 })
3638 .transpose()?
3639 .unwrap_or_default();
3640 let runner_for = |scenario: &witness::Scenario| {
3641 library_runners.iter().copied().find(|bin| {
3642 scenario
3643 .source_test
3644 .as_ref()
3645 .is_none_or(|required| match &bin.runner {
3646 Runner::Exe(_) if !in_root => {
3649 let inner = format!("::{required}");
3650 bin.tests
3651 .iter()
3652 .any(|test| test.ends_with(&inner) && !ignored.contains(test))
3653 }
3654 Runner::Exe(_) => {
3655 bin.tests.contains(required) && !ignored.contains(required)
3656 }
3657 Runner::Isolated { test, .. } if !in_root => {
3658 test.ends_with(&format!("::{required}"))
3659 }
3660 Runner::Isolated { test, .. } => test == required,
3661 Runner::Doc { .. } | Runner::Nextest { .. } => false,
3662 })
3663 })
3664 };
3665 let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
3666 let Some(source) = witness::render_edits(&file.original, edits, None) else {
3667 return Ok(false);
3668 };
3669 let suffix = if in_root { root_mutant_suffix } else { "" };
3670 state.write(&file.path, &format!("{source}{suffix}"))?;
3671 Ok(true)
3672 };
3673 let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
3674 if !write_edits(edits)? {
3675 return Ok(None);
3676 }
3677 Ok(match source_build(&cargo_build()?) {
3678 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
3679 SourceBuild::Refused => None,
3680 SourceBuild::Failed(why) => {
3681 session.note(&format!(
3682 "a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
3683 ));
3684 Some(Outcome::Unable)
3685 }
3686 })
3687 };
3688 let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
3689 if !write_edits(edits)? {
3690 return Ok(None);
3691 }
3692 let build = build_test_binaries(true)?;
3693 if !build.status.success() {
3694 return Ok(None);
3695 }
3696 let artifacts = parse_build_output(
3697 &String::from_utf8_lossy(&build.stdout),
3698 &[package.name.as_str()],
3699 );
3700 Ok(root_test_exe(&artifacts))
3701 };
3702 let observe = |scenario: &witness::Scenario,
3703 baseline: &TestBinary,
3704 edits: &[witness::Edit],
3705 field_path: Option<&str>,
3706 expected: Option<&str>|
3707 -> Result<Option<witness::Observation>> {
3708 let test = scenario.test_edit_with_field(
3709 &file.original,
3710 witness::TEST_NAME,
3711 field_path,
3712 expected,
3713 );
3714 let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
3715 let Some(exe) = compile_observer(&edits)? else {
3716 return Ok(None);
3717 };
3718 observe_witness(
3719 baseline,
3720 exe,
3721 wrapper.as_deref(),
3722 scenario,
3723 witness::TEST_NAME,
3724 expected.is_some(),
3725 in_root,
3726 )
3727 };
3728 let witness_checkpoint = if checkpoint.is_some() {
3729 let keys = witness_candidates
3730 .iter()
3731 .map(|candidate| {
3732 let edits = candidate
3733 .edits
3734 .iter()
3735 .map(|edit| (&edit.span, &edit.replacement))
3736 .collect::<Vec<_>>();
3737 serde_json::to_string(&(&candidate.description, edits))
3738 })
3739 .collect::<std::result::Result<Vec<_>, _>>()?;
3740 let name = if in_root {
3741 "witness".to_string()
3742 } else {
3743 format!("witness:{}", file.display)
3744 };
3745 phase(&name, keys)?
3746 } else {
3747 None
3748 };
3749 let mut survivors = vec![];
3750 let mut claimed = BTreeSet::new();
3751 progress::track(
3752 options.progress,
3753 "source witness mutants",
3754 witness_candidates.len(),
3755 |progress| -> Result<()> {
3756 for (index, candidate) in witness_candidates.iter().copied().enumerate() {
3757 let cached = witness_checkpoint
3758 .as_ref()
3759 .map(|phase| phase.get::<WitnessTrial>(index))
3760 .transpose()?
3761 .flatten();
3762 let at = witness_location(file, candidate);
3763 if !built_sources.contains(file)
3765 || candidate.edits.iter().any(|edit| {
3766 left_out_here.iter().any(|(from, to)| {
3767 *from <= edit.span.start && edit.span.end <= *to
3768 })
3769 })
3770 {
3771 if let Some(phase) =
3772 witness_checkpoint.as_ref().filter(|_| cached.is_none())
3773 {
3774 phase.record(index, &WitnessTrial::Inapplicable)?;
3775 }
3776 if !candidate.existing {
3777 report.mutants_not_evaluated += 1;
3778 report.mutants_not_compiled += 1;
3779 let span = &candidate.edits[0].span;
3780 report.skipped.push(report::SkippedSite::new(
3781 at,
3782 file.lines.position(&file.original, span.end),
3783 report::SkipReason::SourceNotBuilt,
3784 Some(
3785 "under a `cfg` that the features of this build turn off"
3786 .to_string(),
3787 ),
3788 ));
3789 }
3790 progress.complete(progress::Outcome::Unable);
3791 continue;
3792 }
3793 let existing = candidate
3794 .existing
3795 .then(|| {
3796 report.findings.iter().position(|finding| {
3797 let location = finding.at();
3798 location.file == at.file
3799 && location.line == at.line
3800 && location.column == at.column
3801 && finding.survivors().contains(&candidate.description)
3802 && (candidate.finding_at.is_none()
3803 || !matches!(finding, Finding::InputGap { .. }))
3804 })
3805 })
3806 .flatten();
3807 let existing = existing.filter(|index| {
3811 candidate.finding_at.is_none() || !claimed.contains(index)
3812 });
3813 let scenarios: Vec<_> = candidate
3814 .scenarios
3815 .iter()
3816 .filter_map(|scenario| {
3817 runner_for(scenario).map(|runner| (scenario, runner))
3818 })
3819 .take(4)
3820 .collect();
3821 let paired = candidate.edits.len() > 1;
3822 if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
3823 || (paired && scenarios.is_empty())
3824 {
3825 if let Some(phase) =
3826 witness_checkpoint.as_ref().filter(|_| cached.is_none())
3827 {
3828 phase.record(index, &WitnessTrial::Inapplicable)?;
3829 }
3830 progress.complete(progress::Outcome::Unable);
3831 continue;
3832 }
3833 let trial = if let Some(cached) = cached {
3836 cached
3837 } else {
3838 let attempted = (|| -> Result<WitnessTrial> {
3839 if paired {
3840 for edit in &candidate.edits {
3841 match suite(std::slice::from_ref(edit))? {
3842 Some(Outcome::Fail) => {}
3843 Some(Outcome::Unable) => {
3844 return Ok(WitnessTrial::Evaluated(
3845 Outcome::Unable,
3846 ));
3847 }
3848 _ => return Ok(WitnessTrial::Inapplicable),
3849 }
3850 }
3851 }
3852 Ok(suite(&candidate.edits)?
3853 .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
3854 })();
3855 state.write(&file.path, &restore)?;
3856 let trial = attempted?;
3857 if let Some(phase) = &witness_checkpoint
3858 && !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
3859 {
3860 phase.record(index, &trial)?;
3861 }
3862 trial
3863 };
3864 let outcome = match trial {
3865 WitnessTrial::Inapplicable => {
3866 progress.complete(progress::Outcome::Unable);
3867 continue;
3868 }
3869 WitnessTrial::Unviable => {
3870 progress.complete(progress::Outcome::Unable);
3871 report.unviable_mutants += usize::from(!candidate.existing);
3872 continue;
3873 }
3874 WitnessTrial::Evaluated(outcome) => outcome,
3875 };
3876 progress.complete(outcome.into());
3877 if !candidate.existing {
3878 match outcome {
3879 Outcome::Unable => report.mutants_not_evaluated += 1,
3880 Outcome::Pass => {
3881 report.mutants_run += 1;
3882 report.mutants_survived += 1;
3883 }
3884 Outcome::Fail => {
3885 report.mutants_run += 1;
3886 report.mutants_killed += 1;
3887 }
3888 Outcome::Timeout => {
3889 report.mutants_run += 1;
3890 report.mutants_killed += 1;
3891 report.mutants_timed_out += 1;
3892 }
3893 }
3894 }
3895 if outcome == Outcome::Pass {
3896 survivors.push(WitnessSurvivor {
3897 candidate,
3898 at,
3899 existing,
3900 scenarios,
3901 });
3902 }
3903 }
3904 Ok(())
3905 },
3906 )?;
3907
3908 if let Some(phase) = &witness_checkpoint {
3909 phase.finish()?;
3910 }
3911 let originals = shared_witnesses(
3912 &file.original,
3913 &survivors,
3914 wrapper.as_deref(),
3915 in_root,
3916 compile_observer,
3917 note,
3918 );
3919 if !survivors.is_empty() {
3920 state.write(&file.path, &restore)?;
3921 }
3922 let originals = originals?;
3923
3924 progress::track(
3925 options.progress,
3926 "distinguishing tests",
3927 survivors.len(),
3928 |progress| -> Result<()> {
3929 for (survivor, original) in survivors.into_iter().zip(originals) {
3930 if survivor.existing.is_some_and(|index| {
3931 survivor.candidate.finding_at.is_some() && claimed.contains(&index)
3932 }) {
3933 progress.complete(progress::Outcome::Unable);
3934 continue;
3935 }
3936 let mut evidence = None;
3937 let mut original = original;
3938 for (scenario, baseline) in survivor.scenarios {
3939 let shared = original.take();
3940 let distinction = (|| -> Result<_> {
3941 if let Some(shared) = shared {
3942 let edits: Vec<_> = survivor
3944 .candidate
3945 .edits
3946 .iter()
3947 .chain(shared.tests.iter())
3948 .cloned()
3949 .collect();
3950 if let Some(exe) = compile_observer(&edits)?
3951 && let Some(mutant) = observe_witness(
3952 baseline,
3953 exe,
3954 wrapper.as_deref(),
3955 scenario,
3956 &shared.name,
3957 true,
3958 in_root,
3959 )
3960 .ok()
3961 .flatten()
3962 && mutant.equals_expected == Some(false)
3963 && observe_witness(
3966 baseline,
3967 shared.original_exe.path.clone(),
3968 wrapper.as_deref(),
3969 scenario,
3970 &shared.name,
3971 true,
3972 in_root,
3973 )
3974 .ok()
3975 .flatten()
3976 .is_some_and(|rechecked| {
3977 rechecked.equals_expected == Some(true)
3978 && rechecked.value == shared.value
3979 })
3980 && let Some(verified) =
3981 scenario.verified(shared.value, mutant.value)
3982 {
3983 return Ok(Some(verified));
3984 }
3985 }
3988 let Some(original) = observe(scenario, baseline, &[], None, None)?
3989 else {
3990 return Ok(None);
3991 };
3992 let value = original.value;
3993 if witness::is_expected_literal(&value) {
3994 let Some(mutant) = observe(
3995 scenario,
3996 baseline,
3997 &survivor.candidate.edits,
3998 None,
3999 Some(&value),
4000 )?
4001 else {
4002 return Ok(None);
4003 };
4004 if mutant.equals_expected != Some(false)
4005 || value == mutant.value
4006 {
4007 return Ok(None);
4008 }
4009 let Some(checked) =
4010 observe(scenario, baseline, &[], None, Some(&value))?
4011 else {
4012 return Ok(None);
4013 };
4014 if checked.equals_expected != Some(true)
4015 || checked.value != value
4016 {
4017 return Ok(None);
4018 }
4019 return Ok(scenario.verified(value, mutant.value));
4020 }
4021 if witness::parse_debug_struct(&value).is_none() {
4024 return Ok(None);
4025 }
4026 let Some(raw_mutant) = observe(
4027 scenario,
4028 baseline,
4029 &survivor.candidate.edits,
4030 None,
4031 None,
4032 )?
4033 else {
4034 return Ok(None);
4035 };
4036 let Some((path, field_orig, _)) =
4037 witness::narrow_struct_field(&value, &raw_mutant.value)
4038 else {
4039 return Ok(None);
4040 };
4041 if !witness::is_expected_literal(&field_orig) {
4042 return Ok(None);
4043 }
4044 let field_path = path.join(".");
4045 let Some(mutant) = observe(
4046 scenario,
4047 baseline,
4048 &survivor.candidate.edits,
4049 Some(&field_path),
4050 Some(&field_orig),
4051 )?
4052 else {
4053 return Ok(None);
4054 };
4055 if mutant.equals_expected != Some(false)
4056 || mutant.value != raw_mutant.value
4057 || value == mutant.value
4058 {
4059 return Ok(None);
4060 }
4061 let Some(checked) = observe(
4062 scenario,
4063 baseline,
4064 &[],
4065 Some(&field_path),
4066 Some(&field_orig),
4067 )?
4068 else {
4069 return Ok(None);
4070 };
4071 if checked.equals_expected != Some(true) || checked.value != value {
4072 return Ok(None);
4073 }
4074 Ok(scenario.verified_field(
4075 value,
4076 mutant.value,
4077 field_path,
4078 field_orig,
4079 ))
4080 })();
4081 match distinction {
4082 Ok(Some(mut verified)) => {
4083 let edits = survivor.candidate.edits.len();
4084 verified.individually_killed = (edits > 1).then_some(edits);
4085 evidence = Some(verified);
4086 break;
4087 }
4088 Ok(None) => {}
4089 Err(err) => note(&format!(
4090 "could not check a distinguishing test for {}: {err:#}",
4091 scenario.expression,
4092 )),
4093 }
4094 }
4095 state.write(&file.path, &restore)?;
4096 progress.complete(Outcome::Pass.into());
4097 if let Some(index) = survivor.existing {
4098 if let Some(evidence) = evidence {
4099 report.findings[index].set_witness(evidence);
4100 if survivor.candidate.finding_at.is_some() {
4101 claimed.insert(index);
4102 }
4103 }
4104 } else {
4105 finding_run_survivors.push(1);
4106 report.findings.push(Finding::Survivor {
4107 at: survivor.at,
4108 survivors: vec![survivor.candidate.description.clone()],
4109 advice: survivor
4110 .candidate
4111 .advice
4112 .clone()
4113 .filter(|_| evidence.is_none()),
4114 witness: evidence,
4115 change_since: None,
4116 });
4117 }
4118 }
4119 Ok(())
4120 },
4121 )?;
4122 }
4123 Ok(())
4124 })();
4125 match witness_result {
4126 Ok(()) => {}
4127 Err(err)
4128 if crate::interrupt::is_interrupted() || crate::interrupt::is_interrupted_err(&err) =>
4129 {
4130 report.interrupted = true;
4131 }
4132 Err(err) => return Err(err),
4133 }
4134
4135 if crate::interrupt::is_interrupted() {
4136 report.interrupted = true;
4137 }
4138 report.record_evaluation();
4139 debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
4140 let mut paired_findings: Vec<(Finding, usize)> = report
4141 .findings
4142 .into_iter()
4143 .zip(finding_run_survivors)
4144 .collect();
4145 paired_findings.sort_by(|(a, _), (b, _)| {
4146 let (a, b) = (a.at(), b.at());
4147 (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
4148 });
4149 let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
4150 paired_findings.into_iter().unzip();
4151 report.findings = sorted_findings;
4152 let places: Vec<FilePlaces> = files
4153 .iter()
4154 .map(|file| FilePlaces {
4155 display: &file.display,
4156 source: &file.original,
4157 lines: &file.lines,
4158 places: &file.places,
4159 })
4160 .collect();
4161 name_findings(&mut report.findings, &places);
4162
4163 let partial_scope = is_partial_scope.then(|| crate::baseline::PartialScope {
4165 scope: scope.as_ref(),
4166 exclude_files: &options.exclude_files,
4167 preserve_all_existing: options.shard.is_some(),
4168 });
4169 let write_ctx = BaselineWriteContext {
4170 ws_package_prefix: &ws_package_prefix,
4171 partial_scope: partial_scope.as_ref(),
4172 single_package_run: batch.is_none(),
4173 note: ¬e,
4174 };
4175 apply_suppressions_and_finish(
4176 options,
4177 &files,
4178 &mut report,
4179 &finding_run_survivors,
4180 &killed_by_loc,
4181 checkpoint.as_ref(),
4182 &write_ctx,
4183 )?;
4184 report.wrapper_grace_outcomes = wrapper_grace_counter.as_ref().map(|c| c.snapshot());
4185 debug_assert!(
4186 report.counts_reconcile(),
4187 "report counts do not reconcile: {report:#?}"
4188 );
4189 Ok(report)
4190}
4191
4192fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
4193 if let Some(shard) = options.shard
4194 && (!options.source_only || shard.index >= shard.count)
4195 {
4196 bail!("shards require --source-only and a valid shard index");
4197 }
4198 let mut seen_errors = HashSet::new();
4199 let mut error_values = vec![];
4200 for expression in &options.error_values {
4201 let expression = expression.trim();
4202 if expression.chars().any(char::is_control) {
4205 bail!(
4206 "invalid --error expression {expression:?}: it has to be on one line, \
4207 without control characters"
4208 );
4209 }
4210 let parsed = syn::parse_str::<syn::Expr>(expression)
4211 .with_context(|| format!("invalid --error expression {expression:?}"))?;
4212 if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
4213 error_values.push(expression);
4214 }
4215 }
4216 let selection = &options.test_selection;
4217 if options.nextest.is_some() {
4218 if !cfg!(unix) {
4219 bail!("the nextest runner is available on Unix");
4220 }
4221 if !options.source_only || options.doc || selection.enabled() {
4222 bail!(
4223 "--test-tool nextest requires --source-only; select tests through the nextest profile"
4224 );
4225 }
4226 }
4227 if options.baseline_jobs > 1 && !selection.enabled() {
4228 bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
4229 }
4230 if options.doc && selection.enabled() {
4231 bail!("--doc cannot be combined with isolated test selection");
4232 }
4233 if options.source_only && options.jobs > 1 {
4234 eprintln!(
4235 "tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
4236 options.jobs
4237 );
4238 }
4239 Ok(error_values)
4240}
4241
4242struct PreparedWorkCopy {
4243 workspace: PathBuf,
4244 work: PathBuf,
4245 work_lock: Option<Arc<WorkLock>>,
4246 copy: PathBuf,
4247 state: WorkCopy,
4248 external_deps: BTreeSet<PathBuf>,
4249}
4250
4251fn prepare_work_copy(
4252 options: &Options,
4253 metadata: &Metadata,
4254 batch: Option<&WorkspaceBatch<'_>>,
4255 catalogue: Option<&CatalogueSnapshot>,
4256 note: &impl Fn(&str),
4257) -> Result<PreparedWorkCopy> {
4258 let workspace = metadata.workspace_root.canonicalize()?;
4259 let requested_work = catalogue
4260 .map(|catalogue| &catalogue.path)
4261 .or(options.work_dir.as_ref());
4262 let work = match requested_work {
4263 Some(dir) => {
4264 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
4265 dir.canonicalize()?
4266 }
4267 None => metadata.target_directory.join("tmt"),
4268 };
4269 if workspace.starts_with(&work) {
4272 bail!(
4273 "the work directory {} contains the workspace; choose a directory of its own",
4274 work.display()
4275 );
4276 }
4277 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
4278 let work = work.canonicalize()?;
4279 let work_lock = if catalogue.is_none() {
4280 Some(Arc::new(WorkLock::take(&work)?))
4281 } else {
4282 None
4283 };
4284 let stage_root = work.join("src");
4285 let copy_subdir = staged_copy_subdir(&workspace, &options.stage_external)?;
4286 let copy = if copy_subdir.as_os_str().is_empty() {
4287 stage_root.clone()
4288 } else {
4289 stage_root.join(©_subdir)
4290 };
4291 let marker = work.join(WORK_MARKER);
4292 if stage_root.exists() && !marker.exists() {
4293 bail!(
4294 "{} exists and was not created by tmt; refusing to delete it. \
4295 Choose another --work-dir or remove it yourself.",
4296 stage_root.display()
4297 );
4298 }
4299 fs::write(
4300 &marker,
4301 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
4302 )?;
4303 let target_dir = metadata.target_directory.clone();
4304 let forbidden = |path: &Path| {
4305 path == target_dir
4306 || path == work
4307 || batch.is_some_and(|batch| path == batch.work)
4308 || path.file_name().is_some_and(|n| n == ".git")
4309 || (path.parent() == Some(workspace.as_path())
4310 && path.file_name().is_some_and(|n| n == "target"))
4311 };
4312 let state = WorkCopy::open_with_copy_root(&work, &stage_root, ©);
4313 let fixtures = options
4314 .copy_fixtures
4315 .iter()
4316 .map(|path| fixture_relative(path))
4317 .collect::<Result<Vec<_>>>()?;
4318 let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
4319 let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
4320 let skip = |path: &Path| {
4321 fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
4322 };
4323 if options.progress && !options.list {
4324 for path in &excluded {
4325 note(&format!(
4326 "excluded fixture {}",
4327 path.strip_prefix(&workspace).unwrap_or(path).display()
4328 ));
4329 }
4330 }
4331 if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
4332 work_directory(&work, "src")?;
4333 real_dir(©, &state)?;
4334 if copy != stage_root {
4335 for ancestor in copy.ancestors() {
4336 if ancestor == stage_root || !ancestor.starts_with(&stage_root) {
4337 break;
4338 }
4339 state.kept.borrow_mut().insert(ancestor.to_path_buf());
4340 }
4341 }
4342 let visible = if options.all_files {
4343 None
4344 } else {
4345 git_visible_files(&workspace)?
4346 };
4347 match visible {
4348 Some(files) => {
4351 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
4352 note(&format!(
4353 "copied {copied} files (ignored files are left out)"
4354 ));
4355 }
4356 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
4357 }
4358 for relative in &fixtures {
4359 copy_fixture_entry(
4360 &workspace.join(relative),
4361 ©.join(relative),
4362 &workspace,
4363 &fixture_forbidden,
4364 &state,
4365 &mut BTreeSet::new(),
4366 )?;
4367 }
4368 let mut staged_destinations: Vec<PathBuf> = Vec::new();
4369 let mut folded_ancestors: BTreeMap<String, PathBuf> = BTreeMap::new();
4370 for entry in &options.stage_external {
4371 let (rel, _) = parse_external_rel(&entry.rel)?;
4372 let dst = normalize(©.join(&rel));
4373 let copy_rel_in_stage = copy.strip_prefix(&stage_root).unwrap_or(©);
4374 let dst_rel_in_stage = dst.strip_prefix(&stage_root).unwrap_or(&dst);
4375 if !dst.starts_with(&stage_root)
4376 || dst == stage_root
4377 || copy.starts_with(&dst)
4378 || dst.starts_with(©)
4379 || paths_overlap_case_insensitive(copy_rel_in_stage, dst_rel_in_stage)
4380 || staged_destinations.iter().any(|prev| {
4381 let prev_rel = prev.strip_prefix(&stage_root).unwrap_or(prev);
4382 paths_overlap_case_insensitive(prev_rel, dst_rel_in_stage)
4383 })
4384 {
4385 bail!(
4386 "--stage-external destination collides with the workspace copy or another staged path: {}",
4387 entry.rel.display()
4388 );
4389 }
4390 for ancestor in dst_rel_in_stage.ancestors() {
4391 if ancestor.as_os_str().is_empty() {
4392 continue;
4393 }
4394 let folded = ancestor.to_string_lossy().to_lowercase();
4395 if let Some(previous) = folded_ancestors.get(&folded)
4396 && previous != ancestor
4397 {
4398 bail!(
4399 "--stage-external destinations differ only by case: {} and {}",
4400 previous.display(),
4401 ancestor.display()
4402 );
4403 }
4404 folded_ancestors.insert(folded, ancestor.to_path_buf());
4405 }
4406 staged_destinations.push(dst.clone());
4407 let src = if entry.from.is_absolute() {
4408 entry.from.clone()
4409 } else {
4410 workspace.join(&entry.from)
4411 };
4412 copy_external_entry(
4413 &src,
4414 &dst,
4415 None,
4416 &work,
4417 &forbidden,
4418 &state,
4419 &mut BTreeSet::new(),
4420 )?;
4421 }
4422 prune(&stage_root, &state)?;
4423 if options.git_index {
4424 git_index::snapshot(&workspace, ©)?;
4425 }
4426 let mut external_deps = BTreeSet::new();
4427 if !options.list {
4428 let mut manifests: Vec<&Path> = metadata
4430 .packages
4431 .iter()
4432 .map(|p| p.manifest_path.as_path())
4433 .collect();
4434 let root_manifest = metadata.workspace_root.join("Cargo.toml");
4435 manifests.push(&root_manifest);
4436 for manifest in manifests {
4437 let Ok(canonical) = manifest.canonicalize() else {
4438 continue;
4439 };
4440 let (Some(manifest_dir), Ok(relative)) =
4441 (canonical.parent(), canonical.strip_prefix(&workspace))
4442 else {
4443 continue;
4444 };
4445 let text = fs::read_to_string(&canonical)?;
4446 let (rewritten, externals) = absolutize_path_dependencies_with_externals(
4447 &text,
4448 manifest_dir,
4449 &workspace,
4450 ©,
4451 )?;
4452 external_deps.extend(externals);
4453 if let Some(rewritten) = rewritten {
4454 state.write(©.join(relative), &rewritten)?;
4455 }
4456 }
4457 }
4458 if let Some(catalogue) = catalogue {
4459 state.settle(&workspace)?;
4460 catalogue.ready.set(true);
4461 }
4462 return Ok(PreparedWorkCopy {
4463 workspace,
4464 work,
4465 work_lock,
4466 copy,
4467 state,
4468 external_deps,
4469 });
4470 }
4471 Ok(PreparedWorkCopy {
4472 workspace,
4473 work,
4474 work_lock,
4475 copy,
4476 state,
4477 external_deps: BTreeSet::new(),
4478 })
4479}
4480
4481#[allow(clippy::too_many_arguments)]
4482fn run_audit_phase<'a>(
4483 session: &Session,
4484 files: &[SourceFile],
4485 jobs: &[Job],
4486 results: &mut [JobResult],
4487 timeout_rechecks: &mut report::TimeoutRechecks,
4488 scratch: &Path,
4489 wanted: usize,
4490 workers: usize,
4491 probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
4492) -> Result<report::Audit> {
4493 let survivors: Vec<usize> = (0..jobs.len())
4494 .filter(|job| results[*job].survived.is_some())
4495 .collect();
4496 let chosen: Vec<usize> = spread(survivors.len(), wanted)
4497 .into_iter()
4498 .map(|nth| survivors[nth])
4499 .collect();
4500 session.note(&format!(
4501 "audit: running {} of {} surviving mutants against all tests",
4502 chosen.len(),
4503 survivors.len()
4504 ));
4505 let against_all: Vec<Job> = chosen
4506 .iter()
4507 .map(|job| Job {
4508 site: jobs[*job].site,
4509 mutation: jobs[*job].mutation,
4510 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
4511 })
4512 .collect();
4513 let mut audit = report::Audit {
4514 sampled: chosen.len(),
4515 survivors: survivors.len(),
4516 ..report::Audit::default()
4517 };
4518 let audit_checkpoint = probe_phase("audit", &against_all)?;
4519 for (job, again) in chosen.iter().zip(session.run_jobs(
4520 &against_all,
4521 workers,
4522 "audit mutants",
4523 audit_checkpoint.as_ref(),
4524 )?) {
4525 timeout_rechecks.include(&again);
4526 if again.unable || again.unconfirmed_timeout {
4527 audit.not_audited += 1;
4528 } else if audit_all_tests_disagrees(&again) {
4529 results[*job] = again;
4531 let site = files
4532 .iter()
4533 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
4534 if let Some((file, site)) = site {
4535 audit
4536 .disagreements
4537 .push(report::location(&file.display, site));
4538 }
4539 }
4540 }
4541 session.note("audit: recording the tests once more");
4542 for (index, bin) in session.binaries.iter().enumerate() {
4543 let path = scratch.join(format!("trace-{index}-audit.tsv"));
4544 let _ = fs::remove_file(&path);
4545 let trace_env = path.to_string_lossy().into_owned();
4546 let limit = Duration::from_secs(3600);
4547 let outcome = run_binary(
4548 bin,
4549 None,
4550 &[("TMT_TRACE", &trace_env)],
4551 limit,
4552 RunOutput::Quiet,
4553 1,
4554 )?;
4555 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
4556 let _ = fs::remove_file(&path);
4557 let records = bin.trace.differences(&again);
4558 if outcome != Outcome::Pass || records > 0 {
4559 audit.trace_differences.push(report::TraceDifference {
4560 binary: bin.name.clone(),
4561 records,
4562 rerun_failed: outcome != Outcome::Pass,
4563 });
4564 }
4565 }
4566 Ok(audit)
4567}
4568
4569fn run_effects_phase(
4570 session: &Session,
4571 files: &[SourceFile],
4572 jobs: &[Job],
4573 effect_jobs: &[(usize, usize)],
4574 scratch: &Path,
4575 workers: usize,
4576 findings: &mut [Finding],
4577) -> Result<()> {
4578 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
4579 let sites: BTreeMap<u32, (&str, &Site)> = files
4580 .iter()
4581 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
4582 .collect();
4583 let traced = run_pool(effect_jobs.len(), workers, |index| {
4584 session.trace_job(
4585 &jobs[effect_jobs[index].1],
4586 scratch,
4587 workers.clamp(1, effect_jobs.len()),
4588 )
4589 })?;
4590 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
4591 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
4594 for found in changes.values_mut() {
4595 found.retain(|change| {
4596 sites.get(&change.site()).is_none_or(|(file, site)| {
4597 file != mutated_file
4598 || site.end <= mutated.start
4599 || mutated.end <= site.start
4600 })
4601 });
4602 }
4603 changes.retain(|_, found| !found.is_empty());
4604 }
4605 if let Finding::AssertionGap {
4606 effects,
4607 effects_of,
4608 ..
4609 } = &mut findings[*finding]
4610 {
4611 *effects = describe_effects(&changes, &sites);
4612 *effects_of = sites
4613 .get(&jobs[*job].site)
4614 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
4615 }
4616 }
4617 Ok(())
4618}
4619
4620struct BaselineWriteContext<'a> {
4621 ws_package_prefix: &'a str,
4622 partial_scope: Option<&'a crate::baseline::PartialScope<'a>>,
4623 single_package_run: bool,
4624 note: &'a dyn Fn(&str),
4625}
4626
4627fn apply_suppressions_and_finish(
4628 options: &Options,
4629 files: &[SourceFile],
4630 report: &mut Report,
4631 finding_run_survivors: &[usize],
4632 killed_by_loc: &BTreeMap<(String, usize, usize, &'static str), usize>,
4633 checkpoint: Option<&Checkpoint>,
4634 write_ctx: &BaselineWriteContext<'_>,
4635) -> Result<()> {
4636 if crate::interrupt::is_interrupted() {
4637 report.interrupted = true;
4638 report.record_evaluation();
4639 }
4640 let parsed_ignores: BTreeMap<&str, crate::baseline::ParsedLineIgnores> = files
4641 .iter()
4642 .map(|f| {
4643 (
4644 f.display.as_str(),
4645 crate::baseline::parse_line_ignores(&f.original),
4646 )
4647 })
4648 .collect();
4649 for (file, parsed) in &parsed_ignores {
4650 for warning in &parsed.warnings {
4651 match warning {
4652 crate::baseline::IgnoreWarning::EmptyScope { line } => {
4653 eprintln!(
4654 "tmt: warning: {}:{line}: empty `tmt:ignore[]` scope suppresses nothing (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
4655 crate::report::sanitize_inline(file),
4656 );
4657 }
4658 crate::baseline::IgnoreWarning::InvalidToken { line, token } => {
4659 eprintln!(
4660 "tmt: warning: {}:{line}: unknown `tmt:ignore` scope `{}` (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
4661 crate::report::sanitize_inline(file),
4662 crate::report::sanitize_inline(token),
4663 );
4664 }
4665 }
4666 }
4667 }
4668 let known = match &options.baseline {
4669 Some(path) => {
4670 let loaded = crate::baseline::load(path)?;
4671 loaded.validate_for_package(&report.package, path)?;
4672 Some(loaded)
4673 }
4674 None => None,
4675 };
4676 let before = report.findings.len();
4677 let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
4678 let mut matched_entries: BTreeMap<(&str, usize), BTreeSet<(usize, usize)>> = BTreeMap::new();
4679 for (finding, run_survivors) in report
4680 .findings
4681 .drain(..)
4682 .zip(finding_run_survivors.iter().copied())
4683 {
4684 let at = finding.at();
4685 if let Some((&file_key, parsed)) = parsed_ignores.get_key_value(at.file.as_str())
4686 && parsed
4687 .directives
4688 .get(&at.line)
4689 .is_some_and(|ignore| ignore.matches(finding.kind(), at.column))
4690 {
4691 for entry in &parsed.entries {
4692 if entry.matches(at.line, finding.kind(), at.column) {
4693 matched_entries
4694 .entry((file_key, entry.comment_line))
4695 .or_default()
4696 .insert((at.line, at.column));
4697 }
4698 }
4699 report.survivor_breakdown.suppressed += run_survivors;
4700 } else {
4701 after_inline.push((finding, run_survivors));
4702 }
4703 }
4704 if !report.interrupted && options.shard.is_none() && report.mutants_not_evaluated == 0 {
4709 let skipped_locs: BTreeSet<(&str, usize, usize)> = report
4710 .skipped
4711 .iter()
4712 .map(|s| (s.at.file.as_str(), s.at.line, s.at.column))
4713 .collect();
4714 let unreached_locs: BTreeSet<(&str, usize, usize)> = report
4715 .unreached
4716 .iter()
4717 .map(|u| (u.file.as_str(), u.line, u.column))
4718 .collect();
4719 for file in files {
4720 let Some(parsed) = parsed_ignores.get(file.display.as_str()) else {
4721 continue;
4722 };
4723 if parsed.entries.is_empty() {
4724 continue;
4725 }
4726 let evaluated_lines: BTreeSet<usize> = file
4727 .sites
4728 .iter()
4729 .chain(&file.rebuild_sites)
4730 .filter(|site| {
4731 let key = (file.display.as_str(), site.line, site.column);
4732 !skipped_locs.contains(&key) && !unreached_locs.contains(&key)
4733 })
4734 .map(|site| site.line)
4735 .collect();
4736 for entry in &parsed.entries {
4737 if !entry.is_active() {
4738 continue;
4739 }
4740 if let Some(matched_cols) =
4741 matched_entries.get(&(file.display.as_str(), entry.comment_line))
4742 {
4743 let other_killed: usize = killed_by_loc
4744 .iter()
4745 .filter(|((f, line, col, kind), _)| {
4746 f == &file.display
4747 && entry.matches(*line, kind, *col)
4748 && !matched_cols.contains(&(*line, *col))
4749 })
4750 .map(|(_, count)| *count)
4751 .sum();
4752 if other_killed > 0 {
4753 eprintln!(
4754 "tmt: warning: {}:{}: `tmt:ignore` also covers {other_killed} killed mutation(s) at other column(s) (narrow with `// tmt:ignore[kind@COL]` to avoid hiding regressions)",
4755 crate::report::sanitize_inline(&file.display),
4756 entry.comment_line,
4757 );
4758 }
4759 continue;
4760 }
4761 if entry
4762 .target_lines
4763 .iter()
4764 .any(|line| evaluated_lines.contains(line))
4765 {
4766 let covered_killed: usize = killed_by_loc
4767 .iter()
4768 .filter(|((f, line, col, kind), _)| {
4769 f == &file.display && entry.matches(*line, kind, *col)
4770 })
4771 .map(|(_, count)| *count)
4772 .sum();
4773 if covered_killed > 0 {
4774 eprintln!(
4775 "tmt: warning: {}:{}: `tmt:ignore` matched no findings on an evaluated line (covers {covered_killed} killed mutation(s); remove or narrow with `// tmt:ignore[kind@COL]`)",
4776 crate::report::sanitize_inline(&file.display),
4777 entry.comment_line,
4778 );
4779 } else {
4780 eprintln!(
4781 "tmt: warning: {}:{}: `tmt:ignore` matched no findings on an evaluated line (mutants may already be killed or selector/column may not match)",
4782 crate::report::sanitize_inline(&file.display),
4783 entry.comment_line,
4784 );
4785 }
4786 }
4787 }
4788 }
4789 }
4790 if crate::interrupt::is_interrupted() {
4791 report.interrupted = true;
4792 report.record_evaluation();
4793 }
4794 if !report.interrupted
4795 && let Some(path) = &options.write_baseline
4796 {
4797 let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
4798 let single_pkg = write_ctx
4799 .single_package_run
4800 .then_some(report.package.as_str());
4801 let summary = crate::baseline::write_scoped(
4802 path,
4803 &report.package,
4804 write_ctx.ws_package_prefix,
4805 &unignored,
4806 write_ctx.partial_scope,
4807 single_pkg,
4808 )?;
4809 if summary.preserved > 0 || summary.removed > 0 {
4810 (write_ctx.note)(&format!(
4811 "baseline {}: {} entries written ({} preserved out of scope, {} resolved removed)",
4812 path.display(),
4813 summary.written,
4814 summary.preserved,
4815 summary.removed
4816 ));
4817 }
4818 }
4819 for (finding, run_survivors) in after_inline {
4820 if known
4821 .as_ref()
4822 .is_some_and(|known| known.knows_in_package(&report.package, &finding))
4823 {
4824 report.survivor_breakdown.suppressed += run_survivors;
4825 } else {
4826 report.survivor_breakdown.reported += run_survivors;
4827 report.findings.push(finding);
4828 }
4829 }
4830 report.suppressed = before - report.findings.len();
4831 if crate::interrupt::is_interrupted() {
4832 report.interrupted = true;
4833 report.record_evaluation();
4834 }
4835 if !report.interrupted
4836 && let Some(checkpoint) = checkpoint
4837 {
4838 checkpoint.finish_if_complete()?;
4839 }
4840 Ok(())
4841}
4842
4843fn workspace_report_prefix(relative: &Path) -> String {
4844 let parts: Vec<_> = relative
4845 .components()
4846 .filter_map(|part| match part {
4847 std::path::Component::Normal(name) => Some(name.to_string_lossy()),
4848 _ => None,
4849 })
4850 .collect();
4851 if parts.is_empty() {
4852 String::new()
4853 } else {
4854 format!("{}/", parts.join("/"))
4855 }
4856}
4857
4858fn repository_prefix(dir: &Path) -> String {
4862 let shown = Command::new("git")
4863 .arg("-C")
4864 .arg(dir)
4865 .args(["rev-parse", "--show-prefix"])
4866 .stderr(Stdio::null())
4867 .output();
4868 match shown {
4869 Ok(output) if output.status.success() => {
4870 String::from_utf8_lossy(&output.stdout).trim().to_string()
4871 }
4872 _ => String::new(),
4873 }
4874}
4875
4876fn spread(count: usize, wanted: usize) -> Vec<usize> {
4879 let wanted = wanted.min(count);
4880 (0..wanted).map(|nth| nth * count / wanted).collect()
4881}
4882
4883struct FilePlaces<'a> {
4885 display: &'a str,
4886 source: &'a str,
4887 lines: &'a scope::LineIndex,
4888 places: &'a [(usize, usize, String)],
4890}
4891
4892fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
4897 let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
4898 for finding in findings {
4899 by_file
4900 .entry(finding.at().file.clone())
4901 .or_default()
4902 .push(finding);
4903 }
4904 for file in files {
4905 let Some(findings) = by_file.remove(file.display) else {
4906 continue;
4907 };
4908 let items = instrument::named_items(file.source);
4909 let index = instrument::ItemIndex::new(&items);
4910 let item_at = |line, column| {
4911 file.lines
4912 .offset_of(file.source, line, column)
4913 .map_or("", |offset| index.at(offset))
4914 };
4915 let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
4916 for (line, column, code) in file.places {
4917 positions
4918 .entry((item_at(*line, *column), code))
4919 .or_default()
4920 .push((*line, *column));
4921 }
4922 for places in positions.values_mut() {
4923 places.sort_unstable();
4924 places.dedup();
4925 }
4926 for finding in findings {
4927 let kind = finding.kind();
4928 let at = finding.at_mut();
4929 let item = item_at(at.line, at.column);
4930 let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
4931 places.partition_point(|&place| place < (at.line, at.column))
4932 });
4933 at.item = item.to_string();
4934 at.id = report::finding_id(kind, at, nth);
4935 }
4936 }
4937}
4938
4939fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
4941 match &site.kind {
4942 SiteKind::Cmp { .. } => plan::CmpOp::ALL
4943 .into_iter()
4944 .find(|op| op.symbol() == mutant.into)
4945 .map_or(Mutation::Negate, Mutation::Op),
4946 SiteKind::Arith { op, .. } => {
4947 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
4948 Mutation::ArithSwap
4949 } else {
4950 Mutation::ArithSwap2
4951 }
4952 }
4953 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
4954 SiteKind::Logic { .. } => Mutation::LogicSwap,
4955 SiteKind::Not { .. } => Mutation::DropNot,
4956 SiteKind::Range { .. } | SiteKind::RangeContains { .. } => Mutation::RangeEnd,
4957 SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
4958 SiteKind::StrAffix { .. } => Mutation::StrContains,
4959 SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
4960 SiteKind::Clamp { .. } => {
4961 if mutant.into.contains("lower") {
4962 Mutation::ClampDropLower
4963 } else {
4964 Mutation::ClampDropUpper
4965 }
4966 }
4967 SiteKind::Rounding { op, .. } => {
4968 if mutant.into == op.alt1().name() {
4969 Mutation::RoundAlt1
4970 } else {
4971 Mutation::RoundAlt2
4972 }
4973 }
4974 SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
4975 SiteKind::Position { .. } => Mutation::PositionSwap,
4976 SiteKind::SaturatingArith { .. } => Mutation::SaturatingSwap,
4977 SiteKind::StrTrim { op, .. } => {
4978 if mutant.into == op.alt1().name() {
4979 Mutation::TrimAlt1
4980 } else {
4981 Mutation::TrimAlt2
4982 }
4983 }
4984 SiteKind::StrCaseEq { .. } => Mutation::StrExactEq,
4985 SiteKind::Abs { .. } => Mutation::DropAbs,
4986 SiteKind::IterLimit { .. } => Mutation::IterLimitDrop,
4987 SiteKind::EndianSwap { .. } => Mutation::EndianSwap,
4988 SiteKind::BitCount { .. } => Mutation::BitCountSwap,
4989 SiteKind::LoopCtrl { .. } => Mutation::LoopCtrlSwap,
4990 SiteKind::LiteralSet { elements, .. } => {
4991 let idx = elements
4992 .iter()
4993 .position(|(elem, _, _)| elem == &mutant.into)
4994 .unwrap_or(0);
4995 Mutation::DropLiteralElem(idx as u8)
4996 }
4997 _ => Mutation::Delete,
5000 }
5001}
5002
5003fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
5012 let mut all = vec![mutation_of(site, mutant)];
5013 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
5014 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
5015 if into == op.negated() && (integers || !an_order_is_needed) {
5016 all.push(Mutation::Negate);
5017 }
5018 match (op, into) {
5019 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
5020 all.push(Mutation::Shift(1))
5021 }
5022 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
5023 all.push(Mutation::Shift(-1))
5024 }
5025 _ => {}
5026 }
5027 }
5028 all
5029}
5030
5031fn describe_effects(
5034 changes: &BTreeMap<String, BTreeSet<Change>>,
5035 sites: &BTreeMap<u32, (&str, &Site)>,
5036) -> Vec<String> {
5037 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
5038 for (test, found) in changes {
5039 for change in found {
5040 by_change.entry(change).or_default().push(test);
5041 }
5042 }
5043 if by_change.is_empty() {
5044 return vec![
5045 "with the mutant, these tests still reach the same code with the same outcomes, as far as that is recorded: they do not use its result, it is the same for their inputs, or what they assert holds for both".to_string(),
5046 ];
5047 }
5048 let mut out = vec![];
5049 for (change, tests) in by_change.iter().take(3) {
5050 let Some((file, site)) = sites.get(&change.site()) else {
5051 continue;
5052 };
5053 let code = report::location(file, site).code;
5054 let at = format!("{file}:{}", site.line);
5055 let who = if tests.is_empty() {
5056 continue;
5057 } else if let Some(first) = tests
5058 .iter()
5059 .copied()
5060 .find(|test| *test != crate::trace::UNKNOWN_TEST)
5061 {
5062 if tests.len() == 1 {
5063 format!("`{first}`")
5064 } else {
5065 format!("`{first}` (and {} more)", tests.len() - 1)
5066 }
5067 } else if tests.len() == 1 {
5068 "a test".to_string()
5069 } else {
5070 format!("a test (and {} more)", tests.len() - 1)
5071 };
5072 out.push(match change {
5073 Change::Returns { value, .. } => {
5074 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
5075 }
5076 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
5077 Change::NoLongerRuns { .. } => {
5078 format!("with the mutant, {who} no longer runs `{code}` ({at})")
5079 }
5080 Change::NewOutcome { .. } => {
5081 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
5082 }
5083 });
5084 }
5085 if by_change.len() > 3 {
5086 out.push(format!("(and {} more such changes)", by_change.len() - 3));
5087 }
5088 out
5089}
5090
5091#[cfg(test)]
5092mod tests;