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};
16use serde::{Deserialize, Serialize};
17
18use crate::checkpoint::{Checkpoint, Phase};
19use crate::instrument::{self, LiteralSide, RUNTIME_MOD, Rendered, Site, SiteKind};
20use crate::output_fixture::{self, Fixture};
21use crate::plan::{self, Mutation, Obs};
22use crate::propagation::{self, Change};
23use crate::report::{self, Finding, Report};
24use crate::scope::{self, Scope};
25use crate::trace::Trace;
26use crate::work_lock::WorkLock;
27use crate::{git_index, leftovers, progress, reverts, witness};
28
29#[derive(Clone)]
30pub struct Options {
31 pub dir: PathBuf,
33 pub package: Option<String>,
34 pub list: bool,
36 pub test_workspace: bool,
38 pub verify: bool,
40 pub work_dir: Option<PathBuf>,
42 pub progress: bool,
44 pub since: Option<String>,
46 pub lines: Vec<String>,
48 pub baseline: Option<PathBuf>,
50 pub write_baseline: Option<PathBuf>,
52 pub also_test: Vec<String>,
54 pub dependents: bool,
56 pub effects: bool,
58 pub rebuild: bool,
60 pub error_values: Vec<String>,
62 pub source_only: bool,
63 pub literal_operators: bool,
64 pub shard: Option<report::Shard>,
65 pub nextest: Option<report::Nextest>,
66 pub test_selection: TestSelection,
67 pub opt_level: Option<u8>,
69 pub timeout_seconds: Option<u64>,
71 pub baseline_jobs: usize,
72 pub serial_timeout_rechecks: bool,
73 pub wrapper_grace: Duration,
74 pub audit: Option<usize>,
76 pub cargo: CargoConfig,
78 pub jobs: usize,
80 pub all_files: bool,
82 pub git_index: bool,
83 pub copy_fixtures: Vec<PathBuf>,
84 pub copy_fixture_excludes: Vec<PathBuf>,
85 pub output_fixtures: Vec<Fixture>,
86 pub checkpoint: bool,
87 pub doc: bool,
89}
90
91#[derive(Clone, Default)]
92pub struct TestSelection {
93 pub isolate: bool,
94 pub targets: Vec<String>,
95 pub include: Vec<String>,
96 pub exclude: Vec<String>,
97 pub include_ignored: bool,
98 pub wrapper: Option<PathBuf>,
99}
100
101impl TestSelection {
102 fn enabled(&self) -> bool {
103 self.isolate
104 || !self.targets.is_empty()
105 || !self.include.is_empty()
106 || !self.exclude.is_empty()
107 || self.include_ignored
108 || self.wrapper.is_some()
109 }
110}
111
112pub use crate::report::CargoConfig;
113
114impl CargoConfig {
115 pub fn flags(&self) -> Vec<String> {
117 let mut flags = vec![];
118 if !self.features.is_empty() {
119 flags.extend(["--features".to_string(), self.features.join(",")]);
120 }
121 for (on, flag) in [
122 (self.all_features, "--all-features"),
123 (self.no_default_features, "--no-default-features"),
124 (self.locked, "--locked"),
125 ] {
126 if on {
127 flags.push(flag.to_string());
128 }
129 }
130 flags
131 }
132}
133
134const NEARBY_LINES: usize = 6;
137const WORK_MARKER: &str = ".tmt-work-dir";
139const STD_ALIAS: &str = "__tmt_std";
141const MAX_REPAIR_ROUNDS: usize = 40;
143const MAX_TEST_FILTERS: usize = 200;
145
146#[derive(Deserialize)]
147struct Metadata {
148 packages: Vec<Package>,
149 workspace_root: PathBuf,
150 target_directory: PathBuf,
151}
152
153#[derive(Deserialize)]
154struct Package {
155 name: String,
156 #[serde(default)]
157 dependencies: Vec<Dependency>,
158 features: BTreeMap<String, Vec<String>>,
159 manifest_path: PathBuf,
160 targets: Vec<Target>,
161}
162
163impl Package {
164 fn enabled_local_features(&self, workspace: &Path, cargo: &CargoConfig) -> BTreeSet<&str> {
166 if cargo.all_features {
167 return self.features.keys().map(String::as_str).collect();
168 }
169 let mut pending = Vec::new();
170 if !cargo.no_default_features {
171 pending.push("default");
172 }
173 let at_workspace_root = self.manifest_path.parent() == Some(workspace);
175 for feature in cargo
176 .features
177 .iter()
178 .flat_map(|features| features.split(|c: char| c == ',' || c.is_whitespace()))
179 {
180 match feature.split_once('/') {
181 Some((package, name)) if package == self.name => pending.push(name),
182 None if at_workspace_root => pending.push(feature),
183 _ => {}
184 }
185 }
186 let mut enabled = BTreeSet::new();
187 while let Some(feature) = pending.pop() {
188 if let Some((name, activates)) = self.features.get_key_value(feature)
189 && enabled.insert(name.as_str())
190 {
191 pending.extend(activates.iter().map(String::as_str));
192 }
193 }
194 enabled
195 }
196}
197
198#[derive(Deserialize)]
199struct Dependency {
200 name: String,
201}
202
203#[derive(Deserialize)]
204struct Target {
205 name: String,
206 kind: Vec<String>,
207 src_path: PathBuf,
208 test: bool,
209 #[serde(default)]
210 doctest: bool,
211 #[serde(default, rename = "required-features")]
212 required_features: Vec<String>,
213}
214
215impl Target {
216 fn is_production(&self) -> bool {
217 matches!(self.test_build_arg(), Some(("--lib" | "--bin", _)))
218 }
219
220 fn test_build_arg(&self) -> Option<(&'static str, Option<&str>)> {
222 match self.kind.first()?.as_str() {
223 "lib" | "rlib" | "cdylib" | "dylib" | "staticlib" | "proc-macro" => {
224 Some(("--lib", None))
225 }
226 "bin" => Some(("--bin", Some(&self.name))),
227 "example" => Some(("--example", Some(&self.name))),
228 "test" => Some(("--test", Some(&self.name))),
229 "bench" => Some(("--bench", Some(&self.name))),
230 _ => None,
231 }
232 }
233}
234
235fn test_build_flags(
237 packages: &[&Package],
238 names: &[String],
239 workspace: &Path,
240 cargo: &CargoConfig,
241) -> Option<Vec<String>> {
242 if names.is_empty() {
243 return None;
244 }
245 let selected = |target: &Target| target.test && names.contains(&target.name);
246 let mut selectors = BTreeSet::new();
247 for package in packages {
248 let enabled_features = package.enabled_local_features(workspace, cargo);
249 for target in package.targets.iter().filter(|t| selected(t)) {
250 let selector = target.test_build_arg()?;
251 if target
253 .required_features
254 .iter()
255 .any(|feature| !enabled_features.contains(feature.as_str()))
256 || selector
257 .1
258 .is_some_and(|name| name.contains(['*', '?', '[']))
259 {
260 return None;
261 }
262 selectors.insert(selector);
263 }
264 }
265 if selectors.is_empty()
267 || packages.iter().flat_map(|p| &p.targets).any(|target| {
268 !selected(target)
269 && target
270 .test_build_arg()
271 .is_some_and(|selector| selectors.contains(&selector))
272 })
273 {
274 return None;
275 }
276 Some(
277 selectors
278 .into_iter()
279 .map(|(flag, name)| match name {
280 Some(name) => format!("{flag}={name}"),
281 None => flag.to_owned(),
282 })
283 .collect(),
284 )
285}
286
287#[derive(Deserialize)]
289struct CargoMessage {
290 reason: String,
291 package_id: Option<String>,
292 target: Option<ArtifactTarget>,
293 profile: Option<Profile>,
294 executable: Option<PathBuf>,
295 #[serde(default)]
296 filenames: Vec<PathBuf>,
297 features: Option<Vec<String>>,
299 message: Option<Diagnostic>,
300}
301
302#[derive(Deserialize)]
303struct ArtifactTarget {
304 name: String,
305 kind: Vec<String>,
306 src_path: Option<PathBuf>,
307}
308
309#[derive(Deserialize)]
310struct Profile {
311 test: bool,
312}
313
314#[derive(Deserialize)]
315struct Diagnostic {
316 level: String,
317 rendered: Option<String>,
318 message: Option<String>,
319 #[serde(default)]
320 spans: Vec<DiagnosticSpan>,
321}
322
323#[derive(Deserialize)]
324struct DiagnosticSpan {
325 file_name: String,
326 byte_start: usize,
327 line_start: usize,
328 is_primary: bool,
329}
330
331#[derive(Debug, PartialEq, Clone)]
332struct ErrorSpan {
333 file: String,
334 byte_start: usize,
335 line: usize,
336}
337
338#[derive(Debug, PartialEq)]
341struct CompileError {
342 primary: Vec<ErrorSpan>,
343 secondary: Vec<ErrorSpan>,
344 rendered: String,
345}
346
347#[derive(Debug, Default, PartialEq)]
348struct BuildOutput {
349 test_binaries: Vec<(String, PathBuf, String, Vec<String>)>,
351 errors: Vec<CompileError>,
352 diagnostics: Vec<String>,
353 build_scripts: Vec<serde_json::Value>,
354 artifacts: Vec<(PathBuf, Vec<PathBuf>)>,
355 features: Vec<(PathBuf, Vec<String>)>,
357}
358
359#[derive(Debug, PartialEq)]
361enum SourceBuild {
362 Built,
363 Refused,
365 Failed(String),
369}
370
371fn source_build(output: &std::process::Output) -> SourceBuild {
372 if output.status.success() {
373 return SourceBuild::Built;
374 }
375 let refused = !parse_build_output(&String::from_utf8_lossy(&output.stdout), &[])
376 .diagnostics
377 .is_empty();
378 if refused {
379 return SourceBuild::Refused;
380 }
381 let said = String::from_utf8_lossy(&output.stderr);
382 let last: Vec<&str> = said.lines().rev().take(3).collect();
383 let last: Vec<&str> = last.into_iter().rev().collect();
384 SourceBuild::Failed(format!("{} ({})", last.join(" / "), output.status))
385}
386
387fn dependents_of(package: &str, packages: &[Package]) -> Vec<String> {
389 let mut reverse = BTreeMap::<&str, Vec<&str>>::new();
390 for other in packages {
391 for dependency in &other.dependencies {
392 reverse
393 .entry(&dependency.name)
394 .or_default()
395 .push(&other.name);
396 }
397 }
398 let mut found = BTreeSet::new();
399 let mut frontier = vec![package];
400 while let Some(current) = frontier.pop() {
401 if let Some(next) = reverse.get(current) {
402 for &other in next {
403 if other != package && found.insert(other) {
404 frontier.push(other);
405 }
406 }
407 }
408 }
409 found.into_iter().map(str::to_owned).collect()
410}
411
412fn is_package(id: &str, name: &str) -> bool {
415 let (path, fragment) = id.split_once('#').unwrap_or((id, ""));
416 fragment.split('@').next() == Some(name)
417 || path.rsplit('/').next() == Some(name)
418 || id.split(' ').next() == Some(name)
419}
420
421fn parse_build_output(stdout: &str, packages: &[&str]) -> BuildOutput {
422 let mut out = BuildOutput::default();
423 for line in stdout.lines() {
424 let Ok(msg) = serde_json::from_str::<CargoMessage>(line) else {
425 continue;
426 };
427 match msg.reason.as_str() {
428 "compiler-artifact" => {
429 let Some(target) = msg.target else { continue };
430 if let Some(path) = target.src_path {
431 let root = normalize(&path);
432 if let Some(features) = msg.features {
433 out.features.push((root.clone(), features));
434 }
435 out.artifacts.push((root, msg.filenames));
436 }
437 if let (Some(exe), Some(profile), Some(id)) =
438 (msg.executable, msg.profile, msg.package_id.as_deref())
439 && profile.test
440 && let Some(package) = packages.iter().find(|name| is_package(id, name))
441 {
442 out.test_binaries
443 .push((target.name, exe, package.to_string(), target.kind));
444 }
445 }
446 "build-script-executed" => {
447 if let Ok(script) = serde_json::from_str(line) {
448 out.build_scripts.push(script);
449 }
450 }
451 "compiler-message" => {
452 let Some(diag) = msg.message else { continue };
453 if diag.level != "error" {
454 continue;
455 }
456 let rendered = diag.rendered.or(diag.message).unwrap_or_default();
457 if !rendered.is_empty() && !out.diagnostics.contains(&rendered) {
458 out.diagnostics.push(rendered.clone());
459 }
460 let span = |s: &DiagnosticSpan| ErrorSpan {
461 file: s.file_name.clone(),
462 byte_start: s.byte_start,
463 line: s.line_start,
464 };
465 let error = CompileError {
466 primary: diag
467 .spans
468 .iter()
469 .filter(|s| s.is_primary)
470 .map(span)
471 .collect(),
472 secondary: diag
473 .spans
474 .iter()
475 .filter(|s| !s.is_primary)
476 .map(span)
477 .collect(),
478 rendered,
479 };
480 if !error.primary.is_empty() && !out.errors.contains(&error) {
483 out.errors.push(error);
484 }
485 }
486 _ => {}
487 }
488 }
489 out.test_binaries.sort_by(|left, right| {
490 (&left.2, &left.3, &left.0, &left.1).cmp(&(&right.2, &right.3, &right.0, &right.1))
491 });
492 out
493}
494
495fn dependency_file(artifact: &Path) -> Option<String> {
497 let stem = artifact.file_stem()?.to_str()?;
498 let unprefixed = match artifact.extension().and_then(|ext| ext.to_str()) {
499 Some("a" | "so" | "dylib" | "rlib" | "rmeta") => stem.strip_prefix("lib"),
500 _ => None,
501 };
502 unprefixed
503 .and_then(|stem| fs::read_to_string(artifact.with_file_name(format!("{stem}.d"))).ok())
504 .or_else(|| fs::read_to_string(artifact.with_extension("d")).ok())
505}
506
507fn dep_inputs(text: &str, copy: &Path) -> BTreeSet<PathBuf> {
508 text.lines()
511 .filter_map(|line| line.strip_suffix(':'))
512 .map(|name| name.replace("\\ ", " ").replace("\\#", "#"))
513 .map(|name| normalize(©.join(name)))
514 .collect()
515}
516
517fn directory_entries(path: &Path) -> impl Iterator<Item = PathBuf> + use<> {
518 fs::read_dir(path)
519 .into_iter()
520 .flatten()
521 .filter_map(|entry| entry.ok().map(|entry| entry.path()))
522}
523
524fn same_binary(a: &Path, b: &Path) -> Option<bool> {
525 let (a, b) = (fs::File::open(a).ok()?, fs::File::open(b).ok()?);
526 let (left, right) = (a.metadata().ok()?, b.metadata().ok()?);
527 if !left.is_file() || !right.is_file() || left.len() != right.len() {
528 return Some(false);
529 }
530 #[cfg(unix)]
531 {
532 use std::os::unix::fs::MetadataExt;
533 if left.ino() == right.ino() && left.dev() == right.dev() {
534 return Some(true);
535 }
536 }
537 compare_streams(a, b).ok()
538}
539
540fn compare_streams(a: impl std::io::Read, b: impl std::io::Read) -> std::io::Result<bool> {
541 use std::io::{BufRead, BufReader, ErrorKind};
542 const BUFFER_BYTES: usize = 64 * 1024;
543 let mut a = BufReader::with_capacity(BUFFER_BYTES, a);
544 let mut b = BufReader::with_capacity(BUFFER_BYTES, b);
545 loop {
546 let left = match a.fill_buf() {
547 Ok(bytes) => bytes,
548 Err(error) if error.kind() == ErrorKind::Interrupted => continue,
549 Err(error) => return Err(error),
550 };
551 let right = match b.fill_buf() {
552 Ok(bytes) => bytes,
553 Err(error) if error.kind() == ErrorKind::Interrupted => continue,
554 Err(error) => return Err(error),
555 };
556 let count = left.len().min(right.len());
557 if count == 0 {
558 return Ok(left.is_empty() && right.is_empty());
559 }
560 if left[..count] != right[..count] {
561 return Ok(false);
562 }
563 a.consume(count);
564 b.consume(count);
565 }
566}
567
568fn artifact_inputs(artifact: &Path, root: &Path, copy: &Path) -> BTreeSet<PathBuf> {
569 let read = |binary: &Path| {
570 dependency_file(binary)
571 .map(|text| dep_inputs(&text, copy))
572 .filter(|inputs| inputs.contains(root))
573 };
574 if let Some(inputs) = read(artifact) {
575 return inputs;
576 }
577 let Some((profile, stem)) = artifact
580 .parent()
581 .zip(artifact.file_stem().and_then(|s| s.to_str()))
582 else {
583 return BTreeSet::new();
584 };
585 let crate_stem = stem.replace('-', "_");
586 let hashed = format!("{crate_stem}-");
587 let old = directory_entries(&profile.join("deps")).filter(|path| {
588 path.extension() == artifact.extension()
589 && path
590 .file_stem()
591 .and_then(|s| s.to_str())
592 .is_some_and(|name| name.starts_with(&hashed))
593 });
594 let mut private_name = std::ffi::OsString::from(crate_stem);
595 if let Some(extension) = artifact.extension() {
596 private_name.push(".");
597 private_name.push(extension);
598 }
599 let new = directory_entries(&profile.join("build"))
600 .flat_map(|package| directory_entries(&package))
601 .map(|unit| unit.join("out").join(&private_name));
602 old.chain(new)
605 .filter_map(|path| {
606 let inputs = read(&path)?;
607 (same_binary(artifact, &path) == Some(true)).then_some(inputs)
608 })
609 .reduce(|left, right| left.intersection(&right).cloned().collect())
610 .unwrap_or_default()
611}
612
613#[derive(Default)]
614struct BuiltSources {
615 files: BTreeMap<PathBuf, BTreeSet<PathBuf>>,
616 features: BTreeMap<PathBuf, BTreeSet<String>>,
619}
620
621impl BuiltSources {
622 fn from_artifacts(
623 artifacts: &[(PathBuf, Vec<PathBuf>)],
624 features: &[(PathBuf, Vec<String>)],
625 copy: &Path,
626 ) -> Self {
627 let mut built = Self::default();
628 for (root, features) in features {
629 built
630 .features
631 .entry(root.clone())
632 .or_default()
633 .extend(features.iter().cloned());
634 }
635 for (root, artifacts) in artifacts {
636 if !root.starts_with(copy) {
637 continue;
638 }
639 let files = built.files.entry(root.clone()).or_default();
640 files.insert(root.clone());
641 if let Some(inputs) = artifacts
642 .iter()
643 .map(|file| artifact_inputs(file, root, copy))
644 .find(|inputs| !inputs.is_empty())
645 {
646 files.extend(inputs);
647 }
648 }
649 built
650 }
651
652 fn contains(&self, source: &SourceFile) -> bool {
653 source.owners.iter().any(|root| {
654 self.files
655 .get(root)
656 .is_some_and(|files| files.contains(&source.path))
657 })
658 }
659
660 fn left_out(&self, source: &SourceFile) -> Vec<(usize, usize)> {
664 let mut features = BTreeSet::new();
665 for root in &source.owners {
666 if !self
667 .files
668 .get(root)
669 .is_some_and(|files| files.contains(&source.path))
670 {
671 continue;
672 }
673 match self.features.get(root) {
674 Some(of_root) => features.extend(of_root.iter().cloned()),
675 None => return vec![],
676 }
677 }
678 instrument::parse_source(&source.original)
679 .map(|parsed| instrument::inactive_ranges(&source.original, &parsed, &features))
680 .unwrap_or_default()
681 }
682}
683
684struct SourceFile {
685 display: String,
687 path: PathBuf,
689 owners: BTreeSet<PathBuf>,
690 original: String,
691 lines: scope::LineIndex,
692 sites: Vec<Site>,
693 rebuild_sites: Vec<Site>,
695 places: Vec<(usize, usize, String)>,
698 rendered: Option<Rendered>,
699}
700
701fn write_rendered(
702 file: &mut SourceFile,
703 state: &WorkCopy,
704 suffix: &str,
705 disabled: &HashSet<u32>,
706 newly_disabled: &HashSet<u32>,
707) -> Result<()> {
708 if file.rendered.is_none()
709 || file
710 .sites
711 .iter()
712 .any(|site| newly_disabled.contains(&site.id))
713 {
714 file.rendered = Some(instrument::render(&file.original, &file.sites, &|id| {
715 !disabled.contains(&id)
716 }));
717 }
718 let rendered = file.rendered.as_ref().expect("rendered before writing");
719 if suffix.is_empty() {
720 state.write(&file.path, &rendered.text)
721 } else {
722 state.write(&file.path, &format!("{}{suffix}", rendered.text))
723 }
724}
725
726#[derive(Clone)]
728enum Runner {
729 Exe(PathBuf),
731 Isolated {
732 exe: PathBuf,
733 test: String,
734 ignored: bool,
735 wrapper: Option<PathBuf>,
736 },
737 Nextest {
738 copy: PathBuf,
739 target_dir: PathBuf,
740 profile: Option<String>,
741 opt_level: Option<u8>,
742 flags: Vec<String>,
743 },
744 Doc {
747 copy: PathBuf,
748 target_dir: PathBuf,
749 package: String,
750 opt_level: Option<u8>,
751 flags: Vec<String>,
752 },
753}
754
755impl Runner {
756 fn executable(&self) -> Option<&Path> {
757 match self {
758 Self::Exe(exe) | Self::Isolated { exe, .. } => Some(exe),
759 Self::Doc { .. } | Self::Nextest { .. } => None,
760 }
761 }
762}
763
764#[derive(Clone, Copy)]
765enum BaselineTiming {
766 Completed(Duration),
767 StillRunning(Duration),
768}
769
770fn explicit_timeout_conflict(
771 timeout: Option<Duration>,
772 baseline: Duration,
773 selected_count: Option<usize>,
774 test_count: usize,
775) -> Option<Duration> {
776 let entire_runner = selected_count.is_none_or(|count| count == test_count);
777 timeout.filter(|&limit| entire_runner && baseline >= limit)
778}
779
780struct TestBinary {
781 name: String,
782 cwd: PathBuf,
784 marks: PathBuf,
786 git_ceiling: PathBuf,
787 work_lock: Option<Arc<WorkLock>>,
788 tests: BTreeSet<String>,
790 runner: Runner,
791 baseline: Duration,
793 untraced_baseline: Option<BaselineTiming>,
795 timeout_diagnostic: std::sync::Once,
796 traced: Duration,
798 timeout: Option<Duration>,
799 wrapper_grace: Duration,
800 report_slow: bool,
801 filtered_timings:
802 std::sync::Mutex<BTreeMap<Vec<String>, std::sync::Arc<std::sync::OnceLock<Duration>>>>,
803 trace: Trace,
804 effects_baseline: std::sync::OnceLock<propagation::BaselineIndex>,
805}
806
807impl TestBinary {
808 fn mutant_limit(&self, baseline: Duration) -> Duration {
809 self.timeout.unwrap_or_else(|| mutant_timeout(baseline))
810 }
811
812 fn warn_timeout_conflict(&self, filter: Option<&[String]>) {
813 let Some(limit) = explicit_timeout_conflict(
815 self.timeout,
816 self.baseline,
817 filter.map(<[String]>::len),
818 self.tests.len(),
819 ) else {
820 return;
821 };
822 self.timeout_diagnostic.call_once(|| {
823 let timing = self.untraced_baseline.or_else(|| {
824 let started = Instant::now();
825 match run_binary(self, None, &[], self.traced, RunOutput::Quiet, 1) {
828 Ok(Outcome::Pass) => Some(BaselineTiming::Completed(started.elapsed())),
829 Ok(Outcome::Timeout) => Some(BaselineTiming::StillRunning(self.traced)),
830 _ => None,
831 }
832 });
833 let (elapsed, message) = match timing {
834 Some(BaselineTiming::Completed(elapsed)) => (elapsed, "took"),
835 Some(BaselineTiming::StillRunning(elapsed)) => (elapsed, "was still running after"),
836 None => return,
837 };
838 if elapsed >= limit {
839 eprintln!(
840 "tmt: warning: unmutated baseline for `{}` {message} {:.3}s, meeting or exceeding --timeout {}",
841 self.name, elapsed.as_secs_f64(), limit.as_secs()
842 );
843 }
844 });
845 }
846
847 fn filtered_limit(&self, filter: Option<&[String]>, traced: bool) -> Duration {
848 let baseline = if traced { self.traced } else { self.baseline };
849 let Some(filter) =
850 filter.filter(|names| !names.is_empty() && names.len() < self.tests.len())
851 else {
852 return self.mutant_limit(baseline);
853 };
854 if self.timeout.is_some() || baseline < SLOW_TRACE || !matches!(self.runner, Runner::Exe(_))
855 {
856 return self.mutant_limit(baseline);
857 }
858 let timed = {
859 let mut groups = self.filtered_timings.lock().unwrap();
860 groups.entry(filter.to_vec()).or_default().clone()
861 };
862 let timing = *timed.get_or_init(|| {
863 let untraced = self.baseline;
864 let started = Instant::now();
865 match run_binary(self, Some(filter), &[], untraced, RunOutput::Quiet, 1) {
868 Ok(Outcome::Pass) => started.elapsed(),
869 _ => untraced,
870 }
871 });
872 self.mutant_limit(if traced {
873 timing.max(
874 timing.mul_f64(self.traced.as_secs_f64() / self.baseline.as_secs_f64().max(0.001)),
875 )
876 } else {
877 timing
878 })
879 }
880}
881
882#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
883#[serde(rename_all = "snake_case")]
884enum Outcome {
885 Pass,
886 Fail,
887 Timeout,
888 Unable,
890}
891
892impl From<Outcome> for progress::Outcome {
893 fn from(outcome: Outcome) -> Self {
894 match outcome {
895 Outcome::Pass => Self::Survived,
896 Outcome::Fail => Self::Failed,
897 Outcome::Timeout => Self::TimedOut,
898 Outcome::Unable => Self::Unable,
899 }
900 }
901}
902
903fn isolate_copy_command(command: &mut Command, work: &Path) {
904 git_index::remove_git_overrides(command);
905 command.env("GIT_CEILING_DIRECTORIES", work);
906}
907
908const WRITTEN_LOG: &str = ".tmt-written";
910
911struct WorkCopy {
919 root: PathBuf,
920 log: PathBuf,
921 kept: RefCell<HashSet<PathBuf>>,
923 earlier: HashSet<PathBuf>,
925 visited: RefCell<HashSet<PathBuf>>,
927 written: RefCell<HashSet<PathBuf>>,
929 logged: RefCell<HashSet<PathBuf>>,
931}
932
933impl WorkCopy {
934 fn open(work: &Path, root: &Path) -> WorkCopy {
935 let log = work.join(WRITTEN_LOG);
936 for file in [log.clone(), log.with_extension("new")] {
938 if fs::symlink_metadata(&file).is_ok_and(|found| found.is_symlink()) {
939 let _ = fs::remove_file(&file);
940 }
941 }
942 let earlier: HashSet<PathBuf> = fs::read_to_string(&log)
943 .unwrap_or_default()
944 .lines()
945 .map(Path::new)
946 .filter(|relative| {
948 let mut parts = relative.components();
949 parts.clone().next().is_some()
950 && parts.all(|part| matches!(part, std::path::Component::Normal(_)))
951 })
952 .map(|relative| root.join(relative))
953 .collect();
954 WorkCopy {
955 root: root.to_path_buf(),
956 log,
957 kept: RefCell::default(),
958 logged: RefCell::new(earlier.clone()),
959 earlier,
960 visited: RefCell::default(),
961 written: RefCell::default(),
962 }
963 }
964
965 fn is_kept(&self, path: &Path) -> bool {
966 self.kept.borrow().contains(path) || self.earlier.contains(path)
967 }
968
969 fn original(&self, path: &Path, workspace: &Path) -> Result<Option<String>> {
972 let source = if !self.earlier.contains(path) {
973 path.to_path_buf() } else if !self.visited.borrow().contains(path) {
975 return Ok(None);
976 } else {
977 workspace.join(path.strip_prefix(&self.root).unwrap_or(path))
978 };
979 fs::read_to_string(&source)
980 .map(Some)
981 .with_context(|| format!("reading {}", source.display()))
982 }
983
984 fn write(&self, path: &Path, content: &str) -> Result<()> {
987 if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
988 fs::remove_file(path)?;
989 }
990 let parent = path.parent().and_then(|p| p.canonicalize().ok());
991 let inside = match (parent, self.root.canonicalize()) {
992 (Some(parent), Ok(root)) => parent.starts_with(root),
993 _ => false,
994 };
995 if !inside {
996 bail!(
997 "refusing to write outside the working copy: {}",
998 path.display()
999 );
1000 }
1001 self.record(path)?;
1002 if fs::read_to_string(path).is_ok_and(|existing| existing == content) {
1003 return Ok(()); }
1005 fs::write(path, content).with_context(|| format!("writing {}", path.display()))
1006 }
1007
1008 fn record(&self, path: &Path) -> Result<()> {
1009 self.written.borrow_mut().insert(path.to_path_buf());
1010 if self.logged.borrow().contains(path) {
1011 return Ok(());
1012 }
1013 let line = path
1014 .strip_prefix(&self.root)
1015 .ok()
1016 .and_then(Path::to_str)
1017 .filter(|text| !text.chars().any(char::is_control));
1018 let Some(line) = line else {
1019 bail!(
1020 "cannot instrument {}: its name cannot be written on a line of the log",
1021 path.display()
1022 );
1023 };
1024 use std::io::Write as _;
1025 let mut log = fs::OpenOptions::new()
1026 .create(true)
1027 .append(true)
1028 .open(&self.log)
1029 .with_context(|| format!("opening {}", self.log.display()))?;
1030 writeln!(log, "{line}").with_context(|| format!("writing {}", self.log.display()))?;
1031 self.logged.borrow_mut().insert(path.to_path_buf());
1032 Ok(())
1033 }
1034
1035 fn settle(&self, workspace: &Path) -> Result<()> {
1038 let written = self.written.borrow();
1039 for path in self.earlier.difference(&written) {
1040 if fs::symlink_metadata(path).is_ok() {
1041 fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
1042 }
1043 if self.visited.borrow().contains(path) {
1044 let source = workspace.join(path.strip_prefix(&self.root).unwrap_or(path));
1045 copy_as_new(&source, path)?;
1046 }
1047 }
1048 let mut lines: Vec<&str> = written
1049 .iter()
1050 .filter_map(|path| path.strip_prefix(&self.root).ok()?.to_str())
1051 .collect();
1052 lines.sort_unstable();
1053 let fresh = self.log.with_extension("new");
1054 fs::write(
1055 &fresh,
1056 lines
1057 .iter()
1058 .map(|line| format!("{line}\n"))
1059 .collect::<String>(),
1060 )?;
1061 fs::rename(&fresh, &self.log)?;
1062 *self.logged.borrow_mut() = written.clone();
1063 Ok(())
1064 }
1065}
1066
1067fn sync_file(src: &Path, dst: &Path, state: &WorkCopy) -> Result<()> {
1071 state.kept.borrow_mut().insert(dst.to_path_buf());
1072 if state.earlier.contains(dst) {
1073 state.visited.borrow_mut().insert(dst.to_path_buf());
1074 if fs::symlink_metadata(dst).is_ok_and(|m| m.is_file()) {
1075 return Ok(());
1077 }
1078 }
1079 let up_to_date = fs::symlink_metadata(dst).is_ok_and(|to| to.is_file()) && same_bytes(src, dst);
1083 if up_to_date {
1084 return Ok(());
1085 }
1086 if let Ok(existing) = fs::symlink_metadata(dst) {
1087 if existing.is_dir() {
1088 fs::remove_dir_all(dst)?;
1089 } else {
1090 fs::remove_file(dst)?;
1091 }
1092 }
1093 copy_as_new(src, dst)
1094}
1095
1096fn same_bytes(a: &Path, b: &Path) -> bool {
1098 let (Ok(a), Ok(b)) = (fs::File::open(a), fs::File::open(b)) else {
1099 return false;
1100 };
1101 compare_streams(a, b).unwrap_or(false)
1102}
1103
1104fn real_dir(dir: &Path, state: &WorkCopy) -> Result<()> {
1108 if let Ok(below) = dir.strip_prefix(&state.root) {
1109 let mut path = state.root.clone();
1110 for part in below.components() {
1111 path.push(part);
1112 match fs::symlink_metadata(&path) {
1113 Ok(found) if !found.is_dir() => fs::remove_file(&path)
1114 .with_context(|| format!("removing {}", path.display()))?,
1115 _ => {}
1116 }
1117 }
1118 }
1119 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))
1120}
1121
1122fn copy_as_new(src: &Path, dst: &Path) -> Result<()> {
1126 fs::copy(src, dst).with_context(|| format!("copying {}", src.display()))?;
1127 fs::File::open(dst)
1129 .and_then(|file| file.set_modified(std::time::SystemTime::now()))
1130 .with_context(|| format!("touching {}", dst.display()))
1131}
1132
1133fn prune(dir: &Path, state: &WorkCopy) -> Result<bool> {
1135 let mut empty = true;
1136 for entry in fs::read_dir(dir)? {
1137 let path = entry?.path();
1138 let is_dir = fs::symlink_metadata(&path)?.is_dir();
1139 if is_dir {
1140 if prune(&path, state)? && !state.is_kept(&path) {
1141 fs::remove_dir(&path)?;
1142 } else {
1143 empty = false;
1144 }
1145 } else if state.is_kept(&path) {
1146 empty = false;
1147 } else {
1148 fs::remove_file(&path)?;
1149 }
1150 }
1151 Ok(empty)
1152}
1153
1154fn copy_entry(
1161 src: &Path,
1162 dst: &Path,
1163 workspace: &Path,
1164 skip: &dyn Fn(&Path) -> bool,
1165 state: &WorkCopy,
1166) -> Result<()> {
1167 let kind = fs::symlink_metadata(src)?.file_type();
1168 if kind.is_symlink() {
1169 let Ok(target) = src.canonicalize() else {
1170 return Ok(()); };
1172 if target.is_dir() {
1173 let contains_link = src
1174 .parent()
1175 .is_some_and(|dir| dir.canonicalize().is_ok_and(|dir| dir.starts_with(&target)));
1176 if !target.starts_with(workspace) || contains_link || skip(&target) {
1177 return Ok(());
1178 }
1179 return copy_tree(&target, dst, workspace, skip, state);
1180 }
1181 sync_file(&target, dst, state)?;
1182 } else if kind.is_dir() {
1183 if !src.join("CACHEDIR.TAG").exists() {
1185 copy_tree(src, dst, workspace, skip, state)?;
1186 }
1187 } else {
1188 sync_file(src, dst, state)?;
1189 }
1190 Ok(())
1191}
1192
1193fn copy_tree(
1194 from: &Path,
1195 to: &Path,
1196 workspace: &Path,
1197 skip: &dyn Fn(&Path) -> bool,
1198 state: &WorkCopy,
1199) -> Result<()> {
1200 real_dir(to, state)?;
1201 for entry in fs::read_dir(from).with_context(|| format!("reading {}", from.display()))? {
1202 let src = entry?.path();
1203 if skip(&src) {
1204 continue;
1205 }
1206 let Some(name) = src.file_name() else {
1207 continue;
1208 };
1209 copy_entry(&src, &to.join(name), workspace, skip, state)?;
1210 }
1211 Ok(())
1212}
1213
1214fn fixture_relative(path: &Path) -> Result<PathBuf> {
1215 use std::path::Component;
1216 let relative = path
1217 .components()
1218 .filter(|part| *part != Component::CurDir)
1219 .collect::<PathBuf>();
1220 if relative.as_os_str().is_empty()
1221 || relative
1222 .components()
1223 .any(|part| !matches!(part, Component::Normal(_)))
1224 {
1225 bail!(
1226 "fixture path must be inside the workspace: {}",
1227 path.display()
1228 );
1229 }
1230 Ok(relative)
1231}
1232
1233fn fixture_exclusions(
1234 workspace: &Path,
1235 roots: &[PathBuf],
1236 excluded: &[PathBuf],
1237) -> Result<BTreeSet<PathBuf>> {
1238 excluded
1239 .iter()
1240 .map(|path| {
1241 let relative = fixture_relative(path)?;
1242 if !roots
1243 .iter()
1244 .any(|root| relative != *root && relative.starts_with(root))
1245 {
1246 bail!(
1247 "--copy-fixture-exclude must name an entry under a --copy-fixture: {}",
1248 path.display()
1249 );
1250 }
1251 let path = workspace.join(relative);
1252 fs::symlink_metadata(&path)
1253 .with_context(|| format!("excluding fixture {}", path.display()))?;
1254 confined_fixture_path(workspace, &path)?;
1255 Ok(path)
1256 })
1257 .collect()
1258}
1259
1260fn confined_fixture_path(workspace: &Path, path: &Path) -> Result<()> {
1261 use std::collections::VecDeque;
1262 use std::path::Component;
1263
1264 let parts = |relative: &Path| {
1265 relative
1266 .components()
1267 .map(|part| part.as_os_str().to_owned())
1268 .collect::<Vec<_>>()
1269 };
1270 let mut pending = VecDeque::from(parts(path.strip_prefix(workspace)?));
1271 let mut resolved = workspace.to_path_buf();
1272 let mut hops = 0;
1273 while let Some(part) = pending.pop_front() {
1274 match Path::new(&part).components().next() {
1275 Some(Component::ParentDir) if resolved != workspace => {
1276 resolved.pop();
1277 }
1278 Some(Component::CurDir) => {}
1279 Some(Component::Normal(_)) => {
1280 resolved.push(part);
1281 match fs::symlink_metadata(&resolved) {
1282 Ok(metadata) if metadata.is_symlink() => {
1283 hops += 1;
1284 if hops > 40 {
1285 bail!("fixture {} contains a symbolic link cycle", path.display());
1286 }
1287 let target = fs::read_link(&resolved)?;
1288 resolved.pop();
1289 let target = if target.is_absolute() {
1290 resolved = workspace.to_path_buf();
1291 target.strip_prefix(workspace).with_context(|| {
1292 format!("fixture {} points outside the workspace", path.display())
1293 })?
1294 } else {
1295 &target
1296 };
1297 for component in parts(target).into_iter().rev() {
1298 pending.push_front(component);
1299 }
1300 }
1301 Ok(_) => {}
1302 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
1303 Err(err) => {
1304 return Err(err)
1305 .with_context(|| format!("checking fixture {}", path.display()));
1306 }
1307 }
1308 }
1309 _ => bail!("fixture {} points outside the workspace", path.display()),
1310 }
1311 }
1312 Ok(())
1313}
1314
1315fn copy_fixture_entry(
1318 from: &Path,
1319 to: &Path,
1320 workspace: &Path,
1321 forbidden: &dyn Fn(&Path) -> bool,
1322 state: &WorkCopy,
1323 visiting: &mut BTreeSet<PathBuf>,
1324) -> Result<()> {
1325 let resolved = from
1326 .canonicalize()
1327 .with_context(|| format!("resolving fixture {}", from.display()))?;
1328 let allowed = |path: &Path| {
1329 path.starts_with(workspace)
1330 && path != workspace
1331 && !path
1332 .ancestors()
1333 .take_while(|part| *part != workspace)
1334 .any(forbidden)
1335 };
1336 if !allowed(from) || !allowed(&resolved) {
1337 bail!(
1338 "fixture {} resolves to an excluded path: {}",
1339 from.display(),
1340 resolved.display()
1341 );
1342 }
1343 let kind = fs::metadata(&resolved)?.file_type();
1344 real_dir(to.parent().expect("fixture has a parent"), state)?;
1345 if kind.is_file() {
1346 return sync_file(&resolved, to, state);
1347 }
1348 if !kind.is_dir() || !visiting.insert(resolved.clone()) {
1349 bail!(
1350 "fixture {} is a cycle or is not a regular file or directory",
1351 from.display()
1352 );
1353 }
1354 real_dir(to, state)?;
1355 state.kept.borrow_mut().insert(to.to_path_buf());
1356 for entry in fs::read_dir(&resolved)? {
1357 let entry = entry?;
1358 let path = entry.path();
1359 let destination = to.join(entry.file_name());
1360 let projected = workspace.join(
1361 destination
1362 .strip_prefix(&state.root)
1363 .expect("fixture under copy"),
1364 );
1365 if !forbidden(&path) && !forbidden(&projected) {
1366 copy_fixture_entry(&path, &destination, workspace, forbidden, state, visiting)?;
1367 }
1368 }
1369 visiting.remove(&resolved);
1370 Ok(())
1371}
1372
1373fn git_visible_files(dir: &Path) -> Result<Option<Vec<PathBuf>>> {
1377 let git = |args: &[&str]| {
1378 Command::new("git")
1379 .arg("-C")
1380 .arg(dir)
1381 .args(args)
1382 .stderr(Stdio::null())
1383 .output()
1384 };
1385 let Ok(inside) = git(&["rev-parse", "--is-inside-work-tree"]) else {
1387 return Ok(None);
1388 };
1389 if !inside.status.success() {
1390 return Ok(None);
1391 }
1392 if git(&["check-ignore", "-q", "."])?.status.success() {
1394 return Ok(None);
1395 }
1396 let listing = git(&[
1399 "ls-files",
1400 "--cached",
1401 "--others",
1402 "--exclude-standard",
1403 "-z",
1404 ])?;
1405 if !listing.status.success() {
1406 bail!(
1407 "git could not list the files of {}; pass --all-files to copy everything",
1408 dir.display()
1409 );
1410 }
1411 Ok(Some(
1412 listing
1413 .stdout
1414 .split(|b| *b == 0)
1415 .filter(|name| !name.is_empty())
1416 .filter_map(|name| std::str::from_utf8(name).ok())
1417 .map(PathBuf::from)
1418 .collect(),
1419 ))
1420}
1421
1422fn copy_git_visible(
1425 from: &Path,
1426 to: &Path,
1427 files: Vec<PathBuf>,
1428 workspace: &Path,
1429 skip: &dyn Fn(&Path) -> bool,
1430 state: &WorkCopy,
1431) -> Result<usize> {
1432 let mut copied = 0;
1433 for relative in files {
1434 let (src, dst) = (from.join(&relative), to.join(&relative));
1435 if skip(&src)
1436 || src
1437 .ancestors()
1438 .any(|a| a != from && a.starts_with(from) && skip(a))
1439 {
1440 continue;
1441 }
1442 let Ok(kind) = fs::symlink_metadata(&src).map(|m| m.file_type()) else {
1443 continue; };
1445 if let Some(parent) = dst.parent() {
1446 real_dir(parent, state)?;
1447 }
1448 if kind.is_dir() {
1449 match git_visible_files(&src)? {
1450 Some(inner) => {
1451 copied += copy_git_visible(&src, &dst, inner, workspace, skip, state)?
1452 }
1453 None => copy_tree(&src, &dst, workspace, skip, state)?,
1454 }
1455 } else {
1456 copy_entry(&src, &dst, workspace, skip, state)?;
1457 copied += 1;
1458 }
1459 }
1460 Ok(copied)
1461}
1462
1463#[derive(Default)]
1464struct ModuleOwners {
1465 production: BTreeSet<PathBuf>,
1466 consumers: BTreeSet<PathBuf>,
1467}
1468
1469fn source_graph(
1470 roots: impl IntoIterator<Item = (PathBuf, bool)>,
1471 copy: &Path,
1472 mut original: impl FnMut(&Path) -> Result<Option<String>>,
1473) -> Result<BTreeMap<PathBuf, ModuleOwners>> {
1474 use std::collections::{VecDeque, btree_map::Entry};
1475 let mut files: BTreeMap<PathBuf, ModuleOwners> = BTreeMap::new();
1476 let mut edges = BTreeMap::new();
1477 for (root, production) in roots {
1478 let directory = root.parent().expect("Cargo target directory").to_path_buf();
1479 let mut pending = VecDeque::from([(root.clone(), directory, production)]);
1480 let mut seen = HashSet::new();
1481 while let Some((path, directory, active)) = pending.pop_front() {
1482 if !seen.insert((path.clone(), directory.clone(), active)) {
1483 continue;
1484 }
1485 let children = match edges.entry((path.clone(), directory.clone())) {
1488 Entry::Occupied(entry) => entry.into_mut(),
1489 Entry::Vacant(entry) => {
1490 let children = original(&path)?.map(|source| {
1491 crate::modules::external(&source, &path, &directory)
1492 .into_iter()
1493 .filter_map(|module| {
1494 let file = module
1495 .paths
1496 .iter()
1497 .map(|path| normalize(path))
1498 .find(|path| path.starts_with(copy) && path.is_file())?;
1499 Some((file, normalize(&module.directory), module.production))
1500 })
1501 .collect::<Vec<_>>()
1502 });
1503 entry.insert(children)
1504 }
1505 };
1506 let Some(children) = children else {
1507 continue;
1508 };
1509 let record = files.entry(path).or_default();
1510 record.consumers.insert(root.clone());
1511 if active {
1512 record.production.insert(root.clone());
1513 }
1514 pending.extend(children.iter().map(|(child, directory, production)| {
1515 (child.clone(), directory.clone(), active && *production)
1516 }));
1517 }
1518 }
1519 files.retain(|_, owners| !owners.production.is_empty());
1520 Ok(files)
1521}
1522
1523fn normalize(path: &Path) -> PathBuf {
1525 let mut out = PathBuf::new();
1526 for component in path.components() {
1527 match component {
1528 std::path::Component::CurDir => {}
1529 std::path::Component::ParentDir => {
1530 out.pop();
1531 }
1532 other => out.push(other),
1533 }
1534 }
1535 out
1536}
1537
1538fn relative_source(path: &Path, package: &Path) -> PathBuf {
1539 for (depth, ancestor) in package.ancestors().enumerate() {
1540 if let Ok(local) = path.strip_prefix(ancestor) {
1541 let mut relative: PathBuf = std::iter::repeat_n("..", depth).collect();
1542 relative.push(local);
1543 return relative;
1544 }
1545 }
1546 path.to_path_buf()
1547}
1548
1549fn absolutize_path_dependencies(
1552 manifest: &str,
1553 manifest_dir: &Path,
1554 workspace: &Path,
1555 copy: &Path,
1556) -> Result<Option<String>> {
1557 use toml_edit::{DocumentMut, Item, TableLike, value};
1558
1559 fn fix(deps: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
1560 let (manifest_dir, workspace, copy) = dirs;
1561 for (_, dep) in deps.iter_mut() {
1562 let Some(dep) = dep.as_table_like_mut() else {
1563 continue;
1564 };
1565 let Some(path) = dep.get("path").and_then(Item::as_str) else {
1566 continue;
1567 };
1568 let absolute = Path::new(path).is_absolute();
1569 let target = normalize(&manifest_dir.join(path));
1570 let rewritten = match target.strip_prefix(workspace) {
1571 Err(_) => target,
1573 Ok(inside) if absolute => copy.join(inside),
1576 Ok(_) => continue,
1577 };
1578 dep.insert("path", value(rewritten.to_string_lossy().into_owned()));
1579 *changed = true;
1580 }
1581 }
1582 const SECTIONS: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];
1583 fn fix_sections(table: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
1584 for section in SECTIONS {
1585 if let Some(deps) = table.get_mut(section).and_then(Item::as_table_like_mut) {
1586 fix(deps, dirs, changed);
1587 }
1588 }
1589 }
1590
1591 let mut doc: DocumentMut = manifest.parse().context("parsing Cargo.toml")?;
1592 let mut changed = false;
1593 let dirs = (manifest_dir, workspace, copy);
1594 fix_sections(doc.as_table_mut(), dirs, &mut changed);
1595 if let Some(ws) = doc.get_mut("workspace").and_then(Item::as_table_like_mut) {
1596 fix_sections(ws, dirs, &mut changed);
1597 }
1598 for per_key in ["target", "patch"] {
1599 let Some(outer) = doc.get_mut(per_key).and_then(Item::as_table_like_mut) else {
1600 continue;
1601 };
1602 for (_, inner) in outer.iter_mut() {
1603 let Some(inner) = inner.as_table_like_mut() else {
1604 continue;
1605 };
1606 if per_key == "target" {
1607 fix_sections(inner, dirs, &mut changed);
1608 } else {
1609 fix(inner, dirs, &mut changed);
1610 }
1611 }
1612 }
1613 Ok(changed.then(|| doc.to_string()))
1614}
1615
1616fn test_filter(tests: &BTreeSet<String>, known: &BTreeSet<String>) -> Option<Vec<String>> {
1622 if tests.len() > MAX_TEST_FILTERS || !tests.iter().all(|t| known.contains(t)) {
1623 None
1624 } else {
1625 Some(tests.iter().cloned().collect())
1626 }
1627}
1628
1629fn parse_test_list(stdout: &str) -> BTreeSet<String> {
1631 stdout
1632 .lines()
1633 .filter_map(|line| line.strip_suffix(": test"))
1634 .map(str::to_string)
1635 .collect()
1636}
1637
1638fn list_tests(
1640 exe: &Path,
1641 cwd: &Path,
1642 work: &Path,
1643 ignored: bool,
1644 strict: bool,
1645 lock: Option<&WorkLock>,
1646) -> Result<BTreeSet<String>> {
1647 let mut command = Command::new(exe);
1648 isolate_copy_command(&mut command, work);
1649 if let Some(lock) = lock {
1650 lock.retain_for(&mut command);
1651 }
1652 command.args(["--list", "--format", "terse"]);
1653 if ignored {
1654 command.arg("--ignored");
1655 }
1656 let listing = command
1657 .current_dir(cwd)
1658 .stdin(Stdio::null())
1659 .output()
1660 .with_context(|| format!("listing tests of {}", exe.display()))?;
1661 if !listing.status.success() {
1662 if !strict {
1663 return Ok(BTreeSet::new());
1664 }
1665 bail!(
1666 "listing tests of {} failed: {}",
1667 exe.display(),
1668 String::from_utf8_lossy(&listing.stderr)
1669 );
1670 }
1671 Ok(parse_test_list(&String::from_utf8_lossy(&listing.stdout)))
1672}
1673
1674fn profile_env(opt_level: Option<u8>) -> Vec<(&'static str, String)> {
1676 opt_level.map_or(vec![], |level| {
1677 vec![
1678 ("CARGO_PROFILE_DEV_OPT_LEVEL", level.to_string()),
1679 ("CARGO_PROFILE_TEST_OPT_LEVEL", level.to_string()),
1680 ]
1681 })
1682}
1683
1684const SLOW_TRACE: Duration = Duration::from_secs(2);
1686
1687fn mutant_timeout(baseline: Duration) -> Duration {
1688 Duration::from_secs(5) + baseline * 5
1689}
1690
1691const TEST_POLL_INITIAL: Duration = Duration::from_micros(250);
1692const TEST_POLL_CAP: Duration = Duration::from_millis(5);
1693
1694fn next_test_poll(delay: &mut Duration, remaining: Duration) -> Duration {
1697 let wait = (*delay).min(remaining);
1698 *delay = (*delay * 2).min(TEST_POLL_CAP);
1699 wait
1700}
1701
1702fn test_threads(cores: usize, sharing: usize) -> usize {
1706 (cores / sharing.max(1)).max(2)
1707}
1708
1709enum RunOutput<'a> {
1710 Quiet,
1711 FirstFailure,
1712 Capture(&'a fs::File),
1713}
1714
1715fn nextest_outcome(code: Option<i32>) -> Result<Outcome> {
1716 match code {
1717 Some(0) => Ok(Outcome::Pass),
1718 Some(100) => Ok(Outcome::Fail),
1720 _ => bail!("cargo nextest failed outside a test (exit code {code:?})"),
1721 }
1722}
1723
1724fn run_binary(
1725 bin: &TestBinary,
1726 tests: Option<&[String]>,
1727 env: &[(&str, &str)],
1728 timeout: Duration,
1729 output: RunOutput<'_>,
1730 sharing: usize,
1731) -> Result<Outcome> {
1732 let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
1733 let threads = test_threads(cores, sharing);
1734 static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1735 let unable_mark = reserve_file(&bin.marks, "unable", &RUNS)?;
1736
1737 let mut cmd = match &bin.runner {
1738 Runner::Exe(exe) => {
1739 let mut cmd = Command::new(exe);
1740 cmd.arg(format!("--test-threads={threads}"));
1743 if let Some(tests) = tests {
1744 cmd.arg("--exact").args(tests);
1745 }
1746 cmd.current_dir(&bin.cwd)
1747 .env("CARGO_MANIFEST_DIR", &bin.cwd);
1748 cmd
1749 }
1750 Runner::Isolated {
1751 exe,
1752 test,
1753 ignored,
1754 wrapper,
1755 } => {
1756 let mut cmd = if let Some(wrapper) = wrapper {
1757 let mut cmd = Command::new(wrapper);
1758 cmd.arg(exe);
1759 cmd
1760 } else {
1761 Command::new(exe)
1762 };
1763 cmd.args(["--exact", "--test-threads=1", test]);
1764 if *ignored {
1765 cmd.arg("--ignored");
1766 }
1767 cmd.current_dir(&bin.cwd)
1768 .env("CARGO_MANIFEST_DIR", &bin.cwd);
1769 cmd
1770 }
1771 Runner::Nextest {
1772 copy,
1773 target_dir,
1774 profile,
1775 opt_level,
1776 flags,
1777 } => {
1778 let mut cmd = Command::new("cargo");
1779 cmd.args(["nextest", "run", "--no-tests=fail"]);
1780 if let Some(profile) = profile {
1781 cmd.args(["--profile", profile]);
1782 }
1783 cmd.args(flags)
1784 .current_dir(copy)
1785 .env("CARGO_TARGET_DIR", target_dir)
1786 .env("CARGO_BUILD_BUILD_DIR", target_dir)
1787 .envs(profile_env(*opt_level));
1788 cmd
1789 }
1790 Runner::Doc {
1791 copy,
1792 target_dir,
1793 package,
1794 opt_level,
1795 flags,
1796 } => {
1797 let mut cmd = Command::new("cargo");
1798 cmd.args(["test", "--doc", "-p", package])
1799 .args(flags)
1800 .current_dir(copy)
1801 .env("CARGO_TARGET_DIR", target_dir)
1802 .env("CARGO_BUILD_BUILD_DIR", target_dir)
1803 .envs(profile_env(*opt_level));
1804 cmd
1805 }
1806 };
1807 isolate_copy_command(&mut cmd, &bin.git_ceiling);
1808 if let Some(lock) = &bin.work_lock {
1809 lock.retain_for(&mut cmd);
1810 }
1811 cmd.env_remove("TMT_TRACE")
1812 .env_remove("TMT_MUTANT")
1813 .env_remove("TMT_TEST")
1814 .env_remove(witness::OUTPUT_ENV)
1815 .env("TMT_UNABLE", &unable_mark)
1816 .envs(env.iter().copied())
1817 .stdin(Stdio::null());
1818 if let Runner::Isolated { test, .. } = &bin.runner {
1819 cmd.env("TMT_TEST", test);
1820 }
1821 let nextest = matches!(bin.runner, Runner::Nextest { .. });
1822 let mut output_to_watch = None;
1823 match output {
1824 RunOutput::Capture(file) => {
1825 cmd.stdout(file.try_clone()?).stderr(file.try_clone()?);
1826 }
1827 RunOutput::FirstFailure if !nextest && !matches!(bin.runner, Runner::Isolated { .. }) => {
1828 let writer = fs::OpenOptions::new().append(true).open(&unable_mark)?;
1831 output_to_watch = Some(FailureOutput::new(fs::File::open(&unable_mark)?));
1832 cmd.stdout(writer).stderr(Stdio::null());
1833 }
1834 RunOutput::Quiet | RunOutput::FirstFailure => {
1835 cmd.stdout(Stdio::null()).stderr(Stdio::null());
1836 }
1837 }
1838 #[cfg(unix)]
1840 std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
1841 let mut watch = leftovers::Watch::new(reserve_file(&bin.marks, "held", &RUNS)?);
1843 let mut child = match watch.spawn(&mut cmd) {
1844 Ok(child) => child,
1845 Err(error) => {
1846 watch.finish(true);
1847 let _ = release_mark(&unable_mark);
1848 return Err(error).with_context(|| format!("starting the tests of `{}`", bin.name));
1849 }
1850 };
1851 let group = child.id();
1852 let kill = |child: &mut std::process::Child| {
1853 if nextest {
1854 stop_nextest(child, Duration::from_secs(12));
1857 return;
1858 }
1859 kill_test_group(group);
1860 let _ = child.kill();
1861 let _ = child.wait();
1862 };
1863 let started = Instant::now();
1864 let mut delay = TEST_POLL_INITIAL;
1865 let mut waiting_reported = false;
1866 let running_mutant = env.iter().any(|(key, _)| *key == "TMT_MUTANT")
1867 || matches!(output, RunOutput::FirstFailure);
1868 let result: Result<Outcome> = (|| loop {
1869 if let Some(status) = child.try_wait()? {
1870 if matches!(bin.runner, Runner::Isolated { .. }) || output_to_watch.is_some() {
1871 kill_test_group(group);
1872 }
1873 if nextest {
1874 return nextest_outcome(status.code());
1875 }
1876 return Ok(if status.success() {
1877 Outcome::Pass
1878 } else {
1879 Outcome::Fail
1880 });
1881 }
1882 if output_to_watch
1883 .as_mut()
1884 .map(FailureOutput::failed)
1885 .transpose()?
1886 .unwrap_or(false)
1887 {
1888 kill(&mut child);
1889 return Ok(Outcome::Fail);
1890 }
1891 let elapsed = started.elapsed();
1892 if bin.report_slow
1893 && running_mutant
1894 && !waiting_reported
1895 && elapsed >= Duration::from_secs(5).min(timeout / 2)
1896 {
1897 let selected = tests
1898 .filter(|names| !names.is_empty())
1899 .map(|names| names.join(", "))
1900 .unwrap_or_else(|| bin.name.clone());
1901 eprintln!(
1902 "tmt: waiting for mutant tests `{selected}` (limit {:.2}s)",
1903 timeout.as_secs_f64()
1904 );
1905 waiting_reported = true;
1906 }
1907 if elapsed >= timeout {
1909 if cfg!(unix)
1910 && !bin.wrapper_grace.is_zero()
1911 && matches!(
1912 &bin.runner,
1913 Runner::Isolated {
1914 wrapper: Some(_),
1915 ..
1916 }
1917 )
1918 {
1919 signal_test_group(group, 15);
1920 let began = Instant::now();
1921 while began.elapsed() < bin.wrapper_grace && child.try_wait().ok() == Some(None) {
1922 std::thread::sleep(
1923 Duration::from_millis(10)
1924 .min(bin.wrapper_grace.saturating_sub(began.elapsed())),
1925 );
1926 }
1927 }
1928 kill(&mut child);
1929 return Ok(Outcome::Timeout);
1930 }
1931 std::thread::sleep(next_test_poll(&mut delay, timeout - elapsed));
1933 })();
1934 drop(output_to_watch);
1936 leftovers::count(&watch.finish(leftovers::leave()));
1938 if result.is_err() {
1939 kill(&mut child);
1940 let _ = release_mark(&unable_mark);
1941 }
1942 let outcome = result?;
1943
1944 if release_mark(&unable_mark)? {
1948 return Ok(Outcome::Unable);
1949 }
1950 Ok(outcome)
1951}
1952
1953struct FailureOutput {
1954 file: fs::File,
1955 line: Vec<u8>,
1956 discarded: bool,
1957}
1958
1959impl FailureOutput {
1960 fn new(file: fs::File) -> Self {
1961 Self {
1962 file,
1963 line: Vec::new(),
1964 discarded: false,
1965 }
1966 }
1967
1968 fn failed(&mut self) -> std::io::Result<bool> {
1969 use std::io::Read as _;
1970 const MAX_LINE: usize = 8 * 1024;
1971 let mut chunk = [0; MAX_LINE];
1972 let read = self.file.read(&mut chunk)?;
1973 for part in chunk[..read].split_inclusive(|byte| *byte == b'\n') {
1974 self.discarded |= self.line.len() + part.len() > MAX_LINE;
1975 if !self.discarded {
1976 self.line.extend_from_slice(part);
1977 }
1978 if part.ends_with(b"\n") {
1979 if !self.discarded
1980 && is_failure_line(String::from_utf8_lossy(&self.line).trim_end())
1981 {
1982 return Ok(true);
1983 }
1984 self.discarded = false;
1985 self.line.clear();
1986 }
1987 }
1988 Ok(false)
1989 }
1990}
1991
1992fn stop_nextest(child: &mut std::process::Child, grace: Duration) {
1993 let wait = |child: &mut std::process::Child, limit: Duration| {
1994 let started = Instant::now();
1995 loop {
1996 match child.try_wait() {
1997 Ok(Some(_)) => return true,
1999 Ok(None) if started.elapsed() < limit => {
2001 std::thread::sleep(Duration::from_millis(10));
2003 }
2004 _ => return false,
2005 }
2006 }
2007 };
2008 if wait(child, Duration::ZERO) {
2009 return;
2010 }
2011 let group = child.id();
2012 #[cfg(unix)]
2015 let mut owned = owned_test_processes(group);
2016 signal_test_group(group, 15);
2017 let mut reaped = wait(child, grace);
2018 if !reaped {
2019 signal_test_group(group, 15);
2021 reaped = wait(child, grace.min(Duration::from_secs(1)));
2022 }
2023 #[cfg(unix)]
2024 {
2025 if !reaped {
2027 owned.extend(owned_test_processes(group));
2029 }
2030 for surviving in surviving_groups(&owned, &test_processes()) {
2031 kill_test_group(surviving);
2032 }
2033 }
2034 if !reaped {
2035 kill_test_group(group);
2037 let _ = child.kill();
2038 let _ = child.wait();
2039 }
2040}
2041
2042#[cfg(unix)]
2043#[derive(Debug, PartialEq)]
2044struct TestProcess {
2045 pid: u32,
2046 parent: u32,
2047 group: u32,
2048 started: String,
2049}
2050
2051#[cfg(unix)]
2052fn test_processes() -> Vec<TestProcess> {
2053 let Ok(processes) = Command::new("ps")
2054 .args([
2055 "-e", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "lstart=",
2056 ])
2057 .output()
2058 else {
2059 return vec![];
2060 };
2061 String::from_utf8_lossy(&processes.stdout)
2062 .lines()
2063 .filter_map(|line| {
2064 let mut fields = line.split_whitespace();
2065 Some(TestProcess {
2066 pid: fields.next()?.parse().ok()?,
2067 parent: fields.next()?.parse().ok()?,
2068 group: fields.next()?.parse().ok()?,
2069 started: fields.collect::<Vec<_>>().join(" "),
2070 })
2071 })
2072 .collect()
2073}
2074
2075#[cfg(unix)]
2079fn surviving_groups(owned: &[TestProcess], current: &[TestProcess]) -> BTreeSet<u32> {
2080 current
2081 .iter()
2082 .filter(|process| {
2083 owned.iter().any(|before| {
2084 process.pid == before.pid
2085 && process.group == before.group
2086 && process.started == before.started
2087 })
2088 })
2089 .map(|process| process.group)
2090 .collect()
2091}
2092
2093#[cfg(unix)]
2094fn owned_test_processes(root: u32) -> Vec<TestProcess> {
2095 owned_among(test_processes(), root)
2096}
2097
2098#[cfg(unix)]
2101fn owned_among(data: Vec<TestProcess>, root: u32) -> Vec<TestProcess> {
2102 let mut owned = HashSet::from([root]);
2103 loop {
2104 let before = owned.len();
2105 for process in &data {
2106 if owned.contains(&process.parent) {
2107 owned.insert(process.pid);
2108 }
2109 }
2110 if owned.len() == before {
2111 break;
2112 }
2113 }
2114 let groups: HashSet<_> = data
2117 .iter()
2118 .filter(|process| process.pid == process.group && owned.contains(&process.pid))
2119 .map(|process| process.group)
2120 .collect();
2121 data.into_iter()
2122 .filter(|process| owned.contains(&process.pid) && groups.contains(&process.group))
2123 .collect()
2124}
2125
2126fn kill_test_group(id: u32) {
2127 signal_test_group(id, 9);
2128}
2129
2130fn signal_test_group(id: u32, signal: i32) {
2131 #[cfg(any(target_os = "linux", target_os = "macos"))]
2132 {
2133 unsafe extern "C" {
2134 fn killpg(group: std::ffi::c_int, signal: std::ffi::c_int) -> std::ffi::c_int;
2135 }
2136 if let Ok(group) = std::ffi::c_int::try_from(id) {
2137 unsafe { killpg(group, signal) };
2139 }
2140 }
2141 #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
2142 let _ = Command::new("kill")
2143 .args([format!("-{signal}"), "--".to_owned(), format!("-{id}")])
2144 .stdout(Stdio::null())
2145 .stderr(Stdio::null())
2146 .status();
2147 #[cfg(not(unix))]
2148 let _ = (id, signal);
2149}
2150
2151fn run_baseline(
2153 bin: &TestBinary,
2154 env: &[(&str, &str)],
2155 timeout: Duration,
2156 path: &Path,
2157 timing_only: bool,
2158) -> Result<bool> {
2159 use std::io::{Read, Seek, SeekFrom};
2160
2161 let mut suffix = 0;
2162 let (path, mut log) = loop {
2163 let candidate = if suffix == 0 {
2164 path.to_path_buf()
2165 } else {
2166 path.with_extension(format!("{suffix}.log"))
2167 };
2168 match fs::OpenOptions::new()
2169 .create_new(true)
2170 .read(true)
2171 .write(true)
2172 .open(&candidate)
2173 {
2174 Ok(log) => break (candidate, log),
2175 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => suffix += 1,
2176 Err(err) => {
2177 return Err(err)
2178 .with_context(|| format!("creating baseline log {}", candidate.display()));
2179 }
2180 }
2181 };
2182 let result =
2183 run_binary(bin, None, env, timeout, RunOutput::Capture(&log), 1).with_context(|| {
2184 format!(
2185 "running baseline for `{}`; output: {}",
2186 bin.name,
2187 path.display()
2188 )
2189 })?;
2190 if result == Outcome::Pass || (timing_only && result == Outcome::Timeout) {
2191 drop(log);
2192 fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
2193 return Ok(result == Outcome::Pass);
2194 }
2195 let reason = match result {
2196 Outcome::Pass => unreachable!("pass handled above"),
2197 Outcome::Fail => "do not pass on the unmutated code",
2198 Outcome::Timeout => "timed out on the unmutated code",
2199 Outcome::Unable => "could not be evaluated on the unmutated code",
2200 };
2201 const LIMIT: u64 = 16 * 1024;
2202 log.seek(SeekFrom::Start(log.metadata()?.len().saturating_sub(LIMIT)))?;
2203 let mut tail = Vec::new();
2204 log.take(LIMIT).read_to_end(&mut tail)?;
2205 bail!(
2206 "the tests in `{}` {reason}; full output: {}\n{}",
2207 bin.name,
2208 path.display(),
2209 String::from_utf8_lossy(&tail).trim_end()
2210 );
2211}
2212
2213fn marks_dir(work: &Path) -> Result<PathBuf> {
2217 work_directory(work, "marks")
2218}
2219
2220fn work_directory(work: &Path, name: &str) -> Result<PathBuf> {
2221 let path = work.join(name);
2222 match fs::symlink_metadata(&path) {
2223 Ok(found) if found.is_dir() => {}
2224 Ok(_) => bail!(
2225 "{} is in the way: the working directory needs a directory of that name, and \
2226 this is not one. Move it, or choose another --work-dir",
2227 path.display()
2228 ),
2229 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
2230 fs::create_dir(&path).with_context(|| format!("creating {}", path.display()))?
2231 }
2232 Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
2233 }
2234 Ok(path)
2235}
2236
2237fn reserve_file(dir: &Path, label: &str, runs: &std::sync::atomic::AtomicUsize) -> Result<PathBuf> {
2246 let dir = std::path::absolute(dir).unwrap_or(dir.to_path_buf());
2249 loop {
2250 let mark = dir.join(format!(
2251 "tmt-{label}-{}-{}",
2252 std::process::id(),
2253 runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
2254 ));
2255 match fs::OpenOptions::new()
2256 .write(true)
2257 .create_new(true)
2258 .open(&mark)
2259 {
2260 Ok(_) => return Ok(mark),
2261 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
2262 Err(err) => {
2264 return Err(err).with_context(|| format!("creating {}", mark.display()));
2265 }
2266 }
2267 }
2268}
2269
2270fn run_source_tests(binaries: &[&TestBinary]) -> Result<Outcome> {
2271 for bin in binaries {
2272 bin.warn_timeout_conflict(None);
2273 let outcome = run_binary(
2274 bin,
2275 None,
2276 &[],
2277 bin.mutant_limit(bin.baseline),
2278 RunOutput::FirstFailure,
2279 1,
2280 )?;
2281 if outcome != Outcome::Pass {
2282 return Ok(outcome);
2283 }
2284 }
2285 Ok(Outcome::Pass)
2286}
2287
2288fn observe_witness(
2289 baseline: &TestBinary,
2290 exe: PathBuf,
2291 wrapper: Option<&Path>,
2292 scenario: &witness::Scenario,
2293 name: &str,
2294 compares: bool,
2295 in_root: bool,
2296) -> Result<Option<witness::Observation>> {
2297 use std::io::Read as _;
2298 let test_name = scenario.test_name(name);
2299 let test_name = if in_root {
2302 test_name
2303 } else {
2304 let inner = format!("::{test_name}");
2305 let listed = list_tests(
2306 &exe,
2307 &baseline.cwd,
2308 &baseline.git_ceiling,
2309 false,
2310 false,
2311 baseline.work_lock.as_deref(),
2312 )?;
2313 let mut named = listed.into_iter().filter(|test| test.ends_with(&inner));
2314 match (named.next(), named.next()) {
2315 (Some(only), None) => only,
2316 _ => return Ok(None),
2317 }
2318 };
2319 let test = TestBinary {
2320 name: test_name.clone(),
2321 cwd: baseline.cwd.clone(),
2322 marks: baseline.marks.clone(),
2323 git_ceiling: baseline.git_ceiling.clone(),
2324 work_lock: baseline.work_lock.clone(),
2325 tests: BTreeSet::new(),
2326 runner: Runner::Isolated {
2327 exe,
2328 test: test_name,
2329 ignored: false,
2330 wrapper: wrapper.map(Path::to_path_buf),
2331 },
2332 baseline: baseline.baseline,
2333 untraced_baseline: None,
2334 timeout_diagnostic: std::sync::Once::new(),
2335 traced: Duration::ZERO,
2336 timeout: baseline.timeout,
2337 wrapper_grace: baseline.wrapper_grace,
2338 report_slow: false,
2339 filtered_timings: Default::default(),
2340 trace: Trace::default(),
2341 effects_baseline: std::sync::OnceLock::new(),
2342 };
2343 static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2344 let path = reserve_file(&test.marks, "witness", &RUNS)?;
2345 let result = (|| {
2346 let Some(output) = path.to_str() else {
2347 return Ok(None);
2348 };
2349 if run_binary(
2350 &test,
2351 None,
2352 &[(witness::OUTPUT_ENV, output)],
2353 test.mutant_limit(test.baseline),
2354 RunOutput::Quiet,
2355 1,
2356 )? != Outcome::Pass
2357 {
2358 return Ok(None);
2359 }
2360 let mut text = String::new();
2361 const MAX_OBSERVATION: u64 = 2048;
2362 fs::File::open(&path)?
2363 .take(MAX_OBSERVATION + 1)
2364 .read_to_string(&mut text)?;
2365 Ok((text.len() <= MAX_OBSERVATION as usize)
2366 .then(|| scenario.observation(&text, compares))
2367 .flatten())
2368 })();
2369 release_mark(&path)?;
2370 result
2371}
2372
2373fn candidate_edit(
2374 file: &SourceFile,
2375 start: usize,
2376 end: usize,
2377 replacement: String,
2378) -> report::CandidateEdit {
2379 let (line, column) = file.lines.position(&file.original, start);
2380 report::CandidateEdit {
2381 file: file.display.clone(),
2382 line,
2383 column,
2384 start,
2385 end,
2386 before: file.original[start..end].to_string(),
2387 replacement,
2388 }
2389}
2390
2391fn witness_location(source: &SourceFile, candidate: &witness::Candidate) -> report::Location {
2392 let span = &candidate.edits[0].span;
2393 let (line, column) = source.lines.position(&source.original, span.start);
2394 report::Location {
2395 file: source.display.clone(),
2396 line,
2397 column,
2398 code: report::one_line(&source.original[span.clone()]),
2399 ..Default::default()
2400 }
2401}
2402
2403#[derive(Serialize, Deserialize)]
2404#[serde(rename_all = "snake_case")]
2405enum WitnessTrial {
2406 Inapplicable,
2407 Unviable,
2408 Evaluated(Outcome),
2409}
2410
2411struct WitnessSurvivor<'a> {
2412 candidate: &'a witness::Candidate,
2413 at: report::Location,
2414 existing: Option<usize>,
2415 scenarios: Vec<(&'a witness::Scenario, &'a TestBinary)>,
2416}
2417
2418struct SharedWitness {
2419 value: String,
2420 name: String,
2421 tests: std::rc::Rc<[witness::Edit]>,
2422}
2423
2424fn shared_witnesses(
2425 source: &str,
2426 survivors: &[WitnessSurvivor<'_>],
2427 wrapper: Option<&Path>,
2428 in_root: bool,
2429 compile: impl Fn(&[witness::Edit]) -> Result<Option<PathBuf>>,
2430 note: impl Fn(&str),
2431) -> Result<Vec<Option<SharedWitness>>> {
2432 let mut originals: Vec<_> = (0..survivors.len()).map(|_| None).collect();
2433 if wrapper.is_some() {
2435 return Ok(originals);
2436 }
2437 let inputs: Vec<_> = survivors
2440 .iter()
2441 .enumerate()
2442 .filter_map(|(index, survivor)| {
2443 let (scenario, runner) = *survivor.scenarios.first()?;
2444 Some((
2445 index,
2446 scenario,
2447 runner,
2448 format!("{}_{index}", witness::TEST_NAME),
2449 ))
2450 })
2451 .collect();
2452 for batch in inputs.chunks(32).filter(|batch| batch.len() > 1) {
2453 note(&format!(
2454 "sharing a build for {} original witness inputs",
2455 batch.len()
2456 ));
2457 let tests: Vec<_> = batch
2458 .iter()
2459 .map(|(_, scenario, _, name)| scenario.test_edit(source, name, None))
2460 .collect();
2461 let Some(exe) = compile(&tests)? else {
2462 note("shared witness build failed, trying inputs individually");
2463 continue;
2464 };
2465 let observed: Vec<_> = batch
2466 .iter()
2467 .filter_map(|(index, scenario, runner, name)| {
2468 let value =
2469 observe_witness(runner, exe.clone(), wrapper, scenario, name, false, in_root)
2470 .ok()??
2471 .value;
2472 witness::is_expected_literal(&value)
2473 .then_some((*index, *scenario, *runner, name, value))
2474 })
2475 .collect();
2476 if observed.is_empty() {
2477 continue;
2478 }
2479 let tests: std::rc::Rc<[_]> = observed
2480 .iter()
2481 .map(|(_, scenario, _, name, value)| scenario.test_edit(source, name, Some(value)))
2482 .collect();
2483 let Some(exe) = compile(&tests)? else {
2484 note("shared witness build failed, trying inputs individually");
2485 continue;
2486 };
2487 for (index, scenario, runner, name, value) in observed {
2488 let checked =
2489 observe_witness(runner, exe.clone(), wrapper, scenario, name, true, in_root);
2490 if checked.is_ok_and(|value_read| {
2491 value_read
2492 .is_some_and(|read| read.equals_expected == Some(true) && read.value == value)
2493 }) {
2494 originals[index] = Some(SharedWitness {
2495 value,
2496 name: name.clone(),
2497 tests: tests.clone(),
2498 });
2499 }
2500 }
2501 }
2502 Ok(originals)
2503}
2504
2505fn release_mark(mark: &Path) -> Result<bool> {
2509 match fs::remove_file(mark) {
2510 Ok(()) => Ok(false),
2511 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(true),
2512 Err(err) => Err(err).with_context(|| {
2513 format!(
2514 "removing {}: cannot tell whether the tests ran the mutant to the end",
2515 mark.display()
2516 )
2517 }),
2518 }
2519}
2520
2521fn is_failure_line(line: &str) -> bool {
2523 line.starts_with("test ") && line.ends_with(" ... FAILED")
2524}
2525
2526fn requested_scope(
2529 options: &Options,
2530 workspace: &Path,
2531 package_dir: &Path,
2532 copy: &Path,
2533) -> Result<Option<Scope>> {
2534 if options.since.is_none() && options.lines.is_empty() {
2535 return Ok(None);
2536 }
2537 let prefix = package_dir.strip_prefix(copy).unwrap_or(Path::new(""));
2539 let lines: Vec<String> = options
2540 .lines
2541 .iter()
2542 .map(|spec| normalize(&prefix.join(spec)).to_string_lossy().into_owned())
2543 .collect();
2544 let mut scope = Scope::parse_lines(&lines)?;
2545 if let Some(revision) = &options.since {
2546 scope.merge(Scope::from_diff(&since_diff(workspace, revision)?));
2547 for file in git_output(
2549 workspace,
2550 &["ls-files", "--others", "--exclude-standard", "-z"],
2551 )?
2552 .split('\0')
2553 .filter(|file| !file.is_empty())
2554 {
2555 scope.add_whole_file(file);
2556 }
2557 }
2558 Ok(Some(scope))
2559}
2560
2561fn git_output(workspace: &Path, args: &[&str]) -> Result<String> {
2562 let output = Command::new("git")
2563 .arg("-C")
2564 .arg(workspace)
2565 .args(args)
2566 .output()
2567 .context("running git")?;
2568 if !output.status.success() {
2569 bail!(
2570 "git {} failed: {}",
2571 args.join(" "),
2572 String::from_utf8_lossy(&output.stderr).trim()
2573 );
2574 }
2575 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
2576}
2577
2578fn since_diff(workspace: &Path, revision: &str) -> Result<String> {
2580 git_output(
2582 workspace,
2583 &[
2584 "diff",
2585 "-U0",
2586 "--no-color",
2587 "--no-ext-diff",
2588 "--relative",
2589 "--src-prefix=a/",
2590 "--dst-prefix=b/",
2591 revision,
2592 "--",
2593 ],
2594 )
2595}
2596
2597fn blame_error(
2601 error: &CompileError,
2602 files: &[SourceFile],
2603 copy: &Path,
2604 disabled: &HashSet<u32>,
2605) -> Vec<u32> {
2606 let enabled = |id: u32| !disabled.contains(&id);
2607 let file_of = |span: &ErrorSpan| {
2608 let path = copy.join(&span.file);
2609 files.iter().find(|f| f.path == path)
2610 };
2611 let innermost = |spans: &[ErrorSpan]| -> Vec<u32> {
2612 let mut ids = vec![];
2613 for span in spans {
2614 if let Some(file) = file_of(span) {
2615 let rendered = file.rendered.as_ref().expect("rendered before building");
2616 match rendered
2618 .inserted_by(span.byte_start)
2619 .filter(|id| enabled(*id))
2620 {
2621 Some(id) => ids.push(id),
2622 None => ids.extend(instrument::blame(
2623 &file.sites,
2624 &enabled,
2625 rendered.to_original(span.byte_start),
2626 )),
2627 }
2628 }
2629 }
2630 ids
2631 };
2632 let widen = |lines: usize| -> Vec<u32> {
2633 let mut ids = vec![];
2634 for span in &error.primary {
2635 if let Some(file) = file_of(span) {
2636 ids.extend(
2637 file.sites
2638 .iter()
2639 .filter(|s| enabled(s.id) && s.line.abs_diff(span.line) <= lines)
2640 .map(|s| s.id),
2641 );
2642 }
2643 }
2644 ids
2645 };
2646 [&error.primary, &error.secondary]
2647 .into_iter()
2648 .map(|spans| innermost(spans))
2649 .chain([0, NEARBY_LINES, usize::MAX].into_iter().map(widen))
2650 .find(|ids| !ids.is_empty())
2651 .unwrap_or_default()
2652}
2653
2654fn domain_of(
2656 literal: LiteralSide,
2657 bounds: Option<&crate::trace::TypeBounds>,
2658) -> Option<(i128, i128)> {
2659 let bounds = bounds?;
2660 match literal {
2661 LiteralSide::Rhs(k) => Some((bounds.lhs.0.checked_sub(k)?, bounds.lhs.1.checked_sub(k)?)),
2662 LiteralSide::Lhs(k) => Some((k.checked_sub(bounds.rhs.1)?, k.checked_sub(bounds.rhs.0)?)),
2663 LiteralSide::None => None,
2664 }
2665}
2666
2667struct Session {
2668 progress: bool,
2669 serial_timeout_rechecks: bool,
2670 package_dir: PathBuf,
2671 binaries: Vec<TestBinary>,
2672}
2673
2674struct Job {
2676 site: u32,
2677 mutation: Mutation,
2678 tests: Vec<(usize, Option<Vec<String>>)>,
2680}
2681
2682fn jobs_for_site(jobs: &[Job], site: u32) -> std::ops::Range<usize> {
2684 let first = jobs.partition_point(|job| job.site < site);
2685 let count = jobs[first..].partition_point(|job| job.site == site);
2686 first..first + count
2687}
2688
2689#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2690struct JobResult {
2691 first_pass_timeout: bool,
2692 unconfirmed_timeout: bool,
2693 survived: Option<Vec<String>>,
2695 timed_out: bool,
2696 unable: bool,
2698}
2699
2700#[derive(Debug, PartialEq)]
2702enum Prediction {
2703 Confirmed,
2705 Refuted,
2707 Unknown,
2710}
2711
2712impl Prediction {
2713 fn of<'a>(runs: impl Iterator<Item = &'a JobResult>) -> Prediction {
2714 let mut verdict = Prediction::Confirmed;
2715 for run in runs {
2716 if run.unable || run.unconfirmed_timeout {
2717 verdict = Prediction::Unknown;
2718 } else if run.survived.is_none() {
2719 return Prediction::Refuted;
2720 }
2721 }
2722 verdict
2723 }
2724}
2725
2726impl report::TimeoutRechecks {
2727 fn include(&mut self, result: &JobResult) {
2728 if result.first_pass_timeout {
2729 self.first_pass += 1;
2730 if result.unconfirmed_timeout || result.unable {
2731 self.unconfirmed += 1;
2732 } else if result.timed_out {
2733 self.confirmed += 1;
2734 } else {
2735 self.recovered += 1;
2736 }
2737 }
2738 }
2739}
2740
2741impl JobResult {
2742 fn progress_outcome(&self) -> progress::Outcome {
2743 if self.unable {
2744 progress::Outcome::Unable
2745 } else if self.timed_out {
2746 progress::Outcome::TimedOut
2747 } else if self.survived.is_some() {
2748 progress::Outcome::Survived
2749 } else {
2750 progress::Outcome::Failed
2751 }
2752 }
2753}
2754
2755fn tests_where<T>(
2757 per_test: Option<&BTreeMap<String, T>>,
2758 pick: impl Fn(&T) -> bool,
2759) -> BTreeSet<String> {
2760 per_test
2761 .into_iter()
2762 .flatten()
2763 .filter(|(_, obs)| pick(obs))
2764 .map(|(test, _)| test.clone())
2765 .collect()
2766}
2767
2768type InfectedTests<'a> = Box<dyn Fn(&TestBinary, Mutation) -> BTreeSet<String> + 'a>;
2769type ReachingTests<'a> = Box<dyn Fn(&TestBinary) -> BTreeSet<String> + 'a>;
2770
2771struct PlannedGap {
2773 finding: Finding,
2774 survivors: Vec<Mutation>,
2776 constant_expr: Option<(usize, usize)>,
2780}
2781
2782fn core_range(start: usize, text: &str) -> (usize, usize) {
2784 let (mut from, mut to) = (0, text.len());
2785 loop {
2786 let inner = &text[from..to];
2787 let trimmed = inner.trim();
2788 from += inner.len() - inner.trim_start().len();
2789 to = from + trimmed.len();
2790 let wrapped = trimmed.starts_with('(') && trimmed.ends_with(')') && {
2791 let mut depth = 0usize;
2793 trimmed.char_indices().all(|(i, c)| {
2794 match c {
2795 '(' => depth += 1,
2796 ')' => depth -= 1,
2797 _ => {}
2798 }
2799 depth > 0 || i == trimmed.len() - 1
2800 })
2801 };
2802 if !wrapped {
2803 return (start + from, start + to);
2804 }
2805 from += 1;
2806 to -= 1;
2807 }
2808}
2809
2810struct SitePlan<'a> {
2812 gaps: Vec<PlannedGap>,
2814 cannot_differ: bool,
2817 constant: bool,
2819 run: Vec<Mutation>,
2821 infected: InfectedTests<'a>,
2823 reaching: ReachingTests<'a>,
2825}
2826
2827enum Planned<'a> {
2828 Unreached,
2829 NotEvaluated,
2831 Nothing,
2833 Plan(SitePlan<'a>),
2834}
2835
2836type ConfirmedGap = (Finding, Vec<usize>, Option<(usize, usize)>);
2838
2839struct SiteWork<'a> {
2841 file: &'a str,
2842 site: &'a Site,
2843 gaps: Vec<ConfirmedGap>,
2844 constant: bool,
2845 cannot_differ: bool,
2846 runs: Vec<(Mutation, usize)>,
2847}
2848
2849impl Session {
2850 fn note(&self, text: &str) {
2851 if self.progress {
2852 eprintln!("tmt: {text}");
2853 }
2854 }
2855
2856 fn merged<T: Default + Copy>(
2857 &self,
2858 select: impl Fn(&Trace) -> Option<&BTreeMap<String, T>>,
2859 merge: impl Fn(&mut T, &T),
2860 ) -> T {
2861 let mut all = T::default();
2862 for obs in self
2863 .binaries
2864 .iter()
2865 .filter_map(|b| select(&b.trace))
2866 .flat_map(|t| t.values())
2867 {
2868 merge(&mut all, obs);
2869 }
2870 all
2871 }
2872
2873 fn plan<'a>(
2876 &'a self,
2877 file: &str,
2878 site: &'a Site,
2879 verify: bool,
2880 primitive: &dyn Fn(usize, usize) -> bool,
2881 ) -> Planned<'a> {
2882 let id = site.id;
2883 let reach_plan = |mutation: Mutation| SitePlan {
2884 gaps: vec![],
2885 constant: false,
2886 cannot_differ: false,
2887 run: vec![mutation],
2888 infected: Box::new(move |bin, _| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
2889 reaching: Box::new(move |bin| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
2890 };
2891 let reached = || {
2892 self.binaries
2893 .iter()
2894 .any(|b| b.trace.reach.contains_key(&id))
2895 };
2896 Planned::Plan(match &site.kind {
2897 SiteKind::Stmt
2898 | SiteKind::Neg { .. }
2899 | SiteKind::Field { .. }
2900 | SiteKind::Body { .. }
2901 if reached() =>
2902 {
2903 reach_plan(Mutation::Delete)
2904 }
2905 SiteKind::Stmt
2906 | SiteKind::Neg { .. }
2907 | SiteKind::Field { .. }
2908 | SiteKind::Body { .. } => return Planned::Unreached,
2909 SiteKind::Guard { can_be_false } => {
2910 let can_be_false = *can_be_false;
2911 let allowed = move |m: &Mutation| can_be_false || *m != Mutation::Const(false);
2912 let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
2913 let guard_plan = plan::plan_return(&merged);
2914 if guard_plan.unreached {
2915 return Planned::Unreached;
2916 }
2917 let gaps = guard_plan
2918 .always
2919 .filter(|always| allowed(&Mutation::Const(*always)))
2920 .map(|always| PlannedGap {
2921 finding: report::guard_gap_finding(file, site, always, verify),
2922 survivors: vec![Mutation::Const(always)],
2923 constant_expr: Some((site.start, site.end)),
2925 })
2926 .into_iter()
2927 .collect();
2928 SitePlan {
2929 constant: false,
2930 cannot_differ: false,
2931 gaps,
2932 run: guard_plan.run.into_iter().filter(allowed).collect(),
2933 infected: Box::new(move |bin, m| {
2934 tests_where(bin.trace.returns.get(&id), |obs| match m {
2935 Mutation::Const(value) => obs.infected_by_const(value),
2936 _ => obs.reached(),
2937 })
2938 }),
2939 reaching: Box::new(move |bin| {
2940 tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
2941 }),
2942 }
2943 }
2944 SiteKind::Arm { .. } if reached() => reach_plan(Mutation::Delete),
2945 SiteKind::Arm { .. } => return Planned::Unreached,
2946 SiteKind::Not { .. } if reached() => reach_plan(Mutation::DropNot),
2947 SiteKind::Range { .. } if reached() => {
2950 if self
2951 .binaries
2952 .iter()
2953 .any(|b| b.trace.ranges_at_top.contains(&id))
2954 {
2955 return Planned::NotEvaluated;
2956 }
2957 reach_plan(Mutation::RangeEnd)
2958 }
2959 SiteKind::Not { .. } | SiteKind::Range { .. } => {
2962 if self
2963 .merged(|t| t.arith.get(&id), plan::ArithObs::merge)
2964 .opaque
2965 {
2966 return Planned::Nothing;
2967 }
2968 return Planned::Unreached;
2969 }
2970 SiteKind::Cmp {
2971 op,
2972 literal,
2973 lhs,
2974 rhs,
2975 gap: operator,
2976 } => {
2977 let op = *op;
2978 let mut merged = Obs::default();
2979 for bin in &self.binaries {
2980 merged.merge(&bin.trace.merged(id));
2981 }
2982 let bounds = self.binaries.iter().find_map(|b| b.trace.bounds.get(&id));
2983 let against = match literal {
2989 LiteralSide::Rhs(number) => {
2990 Some((lhs, (site.start, operator.0), *number, true))
2991 }
2992 LiteralSide::Lhs(number) => Some((rhs, (operator.1, site.end), *number, false)),
2993 LiteralSide::None => None,
2994 }
2995 .and_then(|(expr, (from, to), number, is_rhs)| {
2996 let reach = instrument::reach(expr)?;
2997 primitive(from, to).then_some((reach, number, is_rhs))
2998 });
2999 let mut domain = domain_of(*literal, bounds);
3000 if let Some((reach, number, is_rhs)) = against
3001 && let Some((low, high)) = reach.interval()
3002 && let (Some(a), Some(b)) = if is_rhs {
3003 (low.checked_sub(number), high.checked_sub(number))
3004 } else {
3005 (number.checked_sub(high), number.checked_sub(low))
3006 }
3007 {
3008 domain = Some(match domain {
3009 Some((lo, hi)) => (lo.max(a), hi.min(b)),
3010 None => (a, b),
3011 });
3012 }
3013 let mut cmp_plan = plan::plan_cmp(op, &merged, domain);
3014 if let Some((reach, number, is_rhs)) = against
3015 && let Some(gap) = cmp_plan.gap.take()
3016 {
3017 cmp_plan.gap = plan::within_reach(gap, op, &merged, reach, number, is_rhs);
3018 }
3019 let mut gaps = vec![];
3020 let mut constant = false;
3021 match &cmp_plan.gap {
3022 Some(plan::InputGap::Unreached) => return Planned::Unreached,
3023 Some(gap) => {
3024 constant = matches!(gap, plan::InputGap::OneSided { .. });
3025 if let Some(finding) =
3026 report::input_gap_finding(file, site, gap, &merged, verify)
3027 {
3028 gaps.push(PlannedGap {
3029 finding,
3030 survivors: gap.survivors(),
3031 constant_expr: None,
3032 });
3033 }
3034 }
3035 None => {}
3036 }
3037 SitePlan {
3038 gaps,
3039 constant,
3040 cannot_differ: cmp_plan.cannot_differ,
3041 run: cmp_plan.run,
3042 infected: Box::new(move |bin, m| {
3043 tests_where(bin.trace.cmp.get(&id), |obs| plan::infects(op, m, obs))
3044 }),
3045 reaching: Box::new(move |bin| {
3046 tests_where(bin.trace.cmp.get(&id), Obs::reached)
3047 }),
3048 }
3049 }
3050 SiteKind::Logic {
3051 and,
3052 lhs,
3053 rhs,
3054 gap: op_gap,
3055 } => {
3056 let and = *and;
3057 let lhs_range = core_range(site.start, lhs);
3058 let rhs_range = core_range(op_gap.1, rhs);
3059 let merged = self.merged(|t| t.logic.get(&id), plan::LogicObs::merge);
3060 let logic_plan = plan::plan_logic(and, &merged);
3061 if logic_plan.gaps.contains(&plan::LogicGap::Unreached) {
3062 return Planned::Unreached;
3063 }
3064 let gaps: Vec<_> = logic_plan
3065 .gaps
3066 .iter()
3067 .filter_map(|gap| {
3068 let (mutation, operand) = match gap {
3071 plan::LogicGap::RhsNeverDecides => (Mutation::LogicDropRhs, rhs_range),
3072 _ => (Mutation::LogicDropLhs, lhs_range),
3073 };
3074 Some(PlannedGap {
3075 finding: report::logic_gap_finding(file, site, *gap, verify)?,
3076 survivors: vec![mutation],
3077 constant_expr: Some(operand),
3078 })
3079 })
3080 .collect();
3081 SitePlan {
3082 constant: merged.constant_value(and).is_some(),
3083 cannot_differ: false,
3084 gaps,
3085 run: logic_plan.run,
3086 infected: Box::new(move |bin, m| {
3087 tests_where(bin.trace.logic.get(&id), |obs| {
3088 plan::logic_infects(and, m, obs)
3089 })
3090 }),
3091 reaching: Box::new(move |bin| {
3092 tests_where(bin.trace.logic.get(&id), plan::LogicObs::reached)
3093 }),
3094 }
3095 }
3096 SiteKind::Arith { .. } | SiteKind::MinMax { .. } => {
3097 let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
3100 let mutations: Vec<(Mutation, plan::ArithObs)> = match &site.kind {
3101 SiteKind::MinMax { .. } => vec![(Mutation::MinMax, merged)],
3102 SiteKind::Arith { op, assign, .. } if op.second(*assign).is_some() => vec![
3103 (Mutation::ArithSwap, merged),
3104 (Mutation::ArithSwap2, merged.second()),
3105 ],
3106 _ => vec![(Mutation::ArithSwap, merged)],
3107 };
3108 let (mut gaps, mut run) = (vec![], vec![]);
3109 for (mutation, seen) in mutations {
3110 match plan::plan_arith(&seen) {
3111 plan::ArithPlan::Unreached => return Planned::Unreached,
3112 plan::ArithPlan::Opaque => return Planned::Nothing,
3114 plan::ArithPlan::NeverDiffers => {
3115 let finding = if mutation == Mutation::MinMax {
3116 report::min_max_gap_finding(file, site, verify)
3117 } else {
3118 report::arith_gap_finding(file, site, mutation, verify)
3119 };
3120 gaps.extend(finding.map(|finding| PlannedGap {
3121 finding,
3122 survivors: vec![mutation],
3123 constant_expr: None,
3124 }));
3125 }
3126 plan::ArithPlan::Run => run.push(mutation),
3127 }
3128 }
3129 SitePlan {
3130 gaps,
3131 constant: false,
3132 cannot_differ: false,
3133 run,
3134 infected: Box::new(move |bin, m| {
3135 tests_where(bin.trace.arith.get(&id), |obs| obs.infected_by(m))
3136 }),
3137 reaching: Box::new(move |bin| {
3138 tests_where(bin.trace.arith.get(&id), |obs| obs.same || obs.differs)
3139 }),
3140 }
3141 }
3142 SiteKind::Return {
3143 sole_expr, option, ..
3144 } => {
3145 let sole_expr = *sole_expr;
3146 let is_option = option.is_some();
3147 let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
3148 let return_plan = if is_option {
3149 plan::plan_option_return(&merged)
3150 } else {
3151 plan::plan_return(&merged)
3152 };
3153 if return_plan.unreached {
3154 return Planned::Unreached;
3155 }
3156 let gaps: Vec<_> = return_plan
3157 .always
3158 .and_then(|always| {
3159 Some(PlannedGap {
3160 finding: report::return_gap_finding(file, site, always, verify)?,
3161 survivors: vec![Mutation::Const(always)],
3162 constant_expr: sole_expr,
3164 })
3165 })
3166 .into_iter()
3167 .collect();
3168 SitePlan {
3169 constant: false,
3170 cannot_differ: false,
3171 gaps,
3172 run: return_plan.run,
3173 infected: Box::new(move |bin, m| {
3174 tests_where(bin.trace.returns.get(&id), |obs| match m {
3175 Mutation::Const(value) => obs.infected_by_const(value),
3176 _ => obs.reached(),
3177 })
3178 }),
3179 reaching: Box::new(move |bin| {
3180 tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
3181 }),
3182 }
3183 }
3184 })
3185 }
3186
3187 fn job(
3188 &self,
3189 site: u32,
3190 mutation: Mutation,
3191 tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>,
3192 ) -> Job {
3193 let tests = self
3194 .binaries
3195 .iter()
3196 .enumerate()
3197 .filter_map(|(index, bin)| {
3198 let tests = tests_of(bin);
3199 if tests.is_empty() {
3200 return None;
3201 }
3202 let filter = match bin.runner {
3203 Runner::Exe(_) => test_filter(&tests, &bin.tests),
3204 Runner::Doc { .. } | Runner::Isolated { .. } | Runner::Nextest { .. } => None,
3205 };
3206 Some((index, filter))
3207 })
3208 .collect();
3209 Job {
3210 site,
3211 mutation,
3212 tests,
3213 }
3214 }
3215
3216 fn run_job(&self, job: &Job, sharing: usize) -> Result<JobResult> {
3219 let spec = format!("{}:{}", job.site, job.mutation.encode());
3220 let mut passed = vec![];
3221 let mut tests: Vec<&(usize, Option<Vec<String>>)> = job.tests.iter().collect();
3223 tests.sort_by_key(|(index, _)| self.binaries[*index].baseline);
3224 for (index, filter) in tests {
3225 let bin = &self.binaries[*index];
3226 let outcome = run_binary(
3227 bin,
3228 filter.as_deref(),
3229 &[("TMT_MUTANT", &spec)],
3230 bin.filtered_limit(filter.as_deref(), false),
3231 RunOutput::FirstFailure,
3232 sharing,
3233 )?;
3234 if outcome != Outcome::Pass {
3235 return Ok(JobResult {
3236 first_pass_timeout: false,
3237 unconfirmed_timeout: false,
3238 survived: None,
3239 timed_out: outcome == Outcome::Timeout,
3240 unable: outcome == Outcome::Unable,
3241 });
3242 }
3243 match filter {
3244 Some(names) => passed.extend(names.iter().cloned()),
3245 None if matches!(bin.runner, Runner::Isolated { .. }) => {
3246 passed.push(bin.name.clone())
3247 }
3248 None => passed.push(format!("all tests of `{}`", bin.name)),
3249 }
3250 }
3251 Ok(JobResult {
3252 first_pass_timeout: false,
3253 unconfirmed_timeout: false,
3254 survived: Some(passed),
3255 timed_out: false,
3256 unable: false,
3257 })
3258 }
3259
3260 fn trace_job(
3263 &self,
3264 job: &Job,
3265 scratch: &Path,
3266 sharing: usize,
3267 ) -> Result<BTreeMap<String, BTreeSet<Change>>> {
3268 let spec = format!("{}:{}", job.site, job.mutation.encode());
3269 let mut all: BTreeMap<String, BTreeSet<Change>> = BTreeMap::new();
3270 for (index, filter) in &job.tests {
3271 let bin = &self.binaries[*index];
3272 let path = scratch.join(format!("effects-{}-{index}.tsv", job.site));
3273 let _ = fs::remove_file(&path);
3274 let trace_env = path.to_string_lossy().into_owned();
3275 let outcome = run_binary(
3276 bin,
3277 filter.as_deref(),
3278 &[("TMT_MUTANT", &spec), ("TMT_TRACE", &trace_env)],
3279 bin.filtered_limit(filter.as_deref(), true),
3280 RunOutput::Quiet,
3281 sharing,
3282 )?;
3283 let text = fs::read_to_string(&path).unwrap_or_default();
3284 let _ = fs::remove_file(&path);
3285 if outcome != Outcome::Pass {
3286 continue; }
3288 let mutated = Trace::parse(&text);
3289 let ran: Option<BTreeSet<String>> =
3290 filter.as_ref().map(|names| names.iter().cloned().collect());
3291 let baseline = bin
3292 .effects_baseline
3293 .get_or_init(|| propagation::BaselineIndex::new(&bin.trace));
3294 for (test, found) in baseline.changes(&mutated, ran.as_ref(), job.site) {
3295 all.entry(test).or_default().extend(found);
3296 }
3297 }
3298 Ok(all)
3299 }
3300
3301 fn run_jobs(
3307 &self,
3308 jobs: &[Job],
3309 workers: usize,
3310 label: &str,
3311 checkpoint: Option<&Phase<'_>>,
3312 ) -> Result<Vec<JobResult>> {
3313 if self
3314 .binaries
3315 .first()
3316 .is_some_and(|bin| bin.timeout.is_some())
3317 {
3318 for (index, filter) in jobs.iter().flat_map(|job| &job.tests) {
3319 self.binaries[*index].warn_timeout_conflict(filter.as_deref());
3320 }
3321 }
3322 let run = |index: usize, sharing| self.run_job(&jobs[index], sharing);
3323 evaluate_jobs(
3324 jobs.len(),
3325 workers,
3326 self.serial_timeout_rechecks,
3327 self.progress,
3328 label,
3329 checkpoint,
3330 &run,
3331 )
3332 }
3333}
3334
3335fn evaluate_jobs(
3336 count: usize,
3337 workers: usize,
3338 serial_rechecks: bool,
3339 progress_enabled: bool,
3340 label: &str,
3341 checkpoint: Option<&Phase<'_>>,
3342 run: &(impl Fn(usize, usize) -> Result<JobResult> + Sync),
3343) -> Result<Vec<JobResult>> {
3344 let sharing = workers.clamp(1, count.max(1));
3345 let mut results = progress::track(progress_enabled, label, count, |progress| {
3346 run_pool(count, workers, |index| {
3347 if let Some(cached) = checkpoint
3348 .map(|phase| phase.get::<JobResult>(index))
3349 .transpose()?
3350 .flatten()
3351 {
3352 progress.complete(cached.progress_outcome());
3353 return Ok((cached, false));
3354 }
3355 let mut result = run(index, sharing)?;
3356 if sharing > 1 && result.timed_out {
3357 result.first_pass_timeout = true;
3358 result.unconfirmed_timeout = true;
3359 }
3360 let pending = result.unconfirmed_timeout && serial_rechecks;
3361 if !pending {
3362 if let Some(phase) = checkpoint {
3363 phase.record(index, &result)?;
3364 }
3365 progress.complete(result.progress_outcome());
3366 }
3367 Ok((result, pending))
3368 })
3369 })?;
3370 let pending: Vec<_> = results
3371 .iter()
3372 .enumerate()
3373 .filter_map(|(index, (_, pending))| pending.then_some(index))
3374 .collect();
3375 if !pending.is_empty() && progress_enabled {
3376 eprintln!(
3377 "tmt: {label}: {} first-pass timeouts, {} pending serial rechecks",
3378 pending.len(),
3379 if serial_rechecks { pending.len() } else { 0 }
3380 );
3381 }
3382 if serial_rechecks {
3383 progress::track_timeout_rechecks(progress_enabled, pending.len(), |progress| {
3384 for index in pending {
3385 let mut confirmed = run(index, 1)?;
3386 confirmed.first_pass_timeout = true;
3387 let outcome = if confirmed.timed_out {
3388 progress::Outcome::TimedOut
3389 } else if confirmed.unable {
3390 progress::Outcome::Unable
3391 } else {
3392 progress::Outcome::Survived
3393 };
3394 if let Some(phase) = checkpoint {
3395 phase.record(index, &confirmed)?;
3396 }
3397 results[index] = (confirmed, false);
3398 progress.complete(outcome);
3399 }
3400 Ok::<_, anyhow::Error>(())
3401 })?;
3402 }
3403 if let Some(phase) = checkpoint {
3404 phase.finish()?;
3405 }
3406 Ok(results.into_iter().map(|(result, _)| result).collect())
3407}
3408
3409fn run_pool<T: Send>(
3412 count: usize,
3413 workers: usize,
3414 work: impl Fn(usize) -> Result<T> + Sync,
3415) -> Result<Vec<T>> {
3416 if count == 0 {
3417 return Ok(vec![]);
3418 }
3419 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
3420 let next = AtomicUsize::new(0);
3421 let stop = AtomicBool::new(false);
3422 let done: Vec<Vec<(usize, Result<T>)>> = std::thread::scope(|scope| {
3423 let handles: Vec<_> = (0..workers.clamp(1, count))
3424 .map(|_| {
3425 scope.spawn(|| {
3426 let mut mine = vec![];
3427 while !stop.load(Ordering::Acquire) {
3428 let index = next.fetch_add(1, Ordering::Relaxed);
3429 if index >= count {
3430 break;
3431 }
3432 let result = work(index);
3433 if result.is_err() {
3434 stop.store(true, Ordering::Release);
3435 }
3436 mine.push((index, result));
3437 }
3438 mine
3439 })
3440 })
3441 .collect();
3442 handles
3443 .into_iter()
3444 .map(|handle| handle.join().expect("worker panicked"))
3445 .collect()
3446 });
3447 let mut ordered: Vec<Option<Result<T>>> = (0..count).map(|_| None).collect();
3448 for (index, result) in done.into_iter().flatten() {
3449 ordered[index] = Some(result);
3450 }
3451 ordered.into_iter().flatten().collect()
3452}
3453
3454impl std::str::FromStr for report::Shard {
3455 type Err = anyhow::Error;
3456
3457 fn from_str(text: &str) -> Result<Self> {
3458 let (index, count) = text.split_once('/').context("expected a shard index K/N")?;
3459 let index: usize = index.parse().context("invalid shard index")?;
3460 let count: usize = count.parse().context("invalid shard count")?;
3461 if index >= count {
3462 bail!("shard index must be less than the shard count");
3463 }
3464 Ok(Self {
3465 index,
3466 count,
3467 round_robin: false,
3468 })
3469 }
3470}
3471
3472impl report::Shard {
3473 fn contains(self, candidate: usize, candidates: usize) -> bool {
3474 candidate < candidates
3475 && (if self.round_robin {
3476 candidate % self.count
3477 } else {
3478 candidate / candidates.div_ceil(self.count)
3479 }) == self.index
3480 }
3481}
3482
3483fn cargo_metadata(dir: &Path, cargo: &CargoConfig) -> Result<Metadata> {
3484 let output = Command::new("cargo")
3485 .args(["metadata", "--no-deps", "--format-version", "1"])
3486 .args(cargo.flags())
3487 .current_dir(dir)
3488 .output()
3489 .context("running cargo metadata")?;
3490 if !output.status.success() {
3491 bail!(
3492 "cargo metadata failed:\n{}",
3493 String::from_utf8_lossy(&output.stderr)
3494 );
3495 }
3496 serde_json::from_slice(&output.stdout).context("parsing cargo metadata")
3497}
3498
3499#[derive(Clone, Copy)]
3500struct WorkspaceShard {
3501 offset: usize,
3502 total: usize,
3503 member_total: usize,
3504}
3505
3506struct CatalogueSnapshot {
3507 path: PathBuf,
3508 ready: std::cell::Cell<bool>,
3509 _lock: WorkLock,
3510}
3511
3512struct WorkspaceBatch<'a> {
3513 metadata: &'a Metadata,
3514 work: &'a Path,
3515 catalogue: Option<CatalogueSnapshot>,
3516}
3517
3518pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
3520 let mut reports = vec![];
3521 run_packages_each(options, names, |name, result| {
3522 reports.push((name, result));
3523 Ok(())
3524 })?;
3525 Ok(reports)
3526}
3527
3528pub fn run_packages_each(
3530 options: &Options,
3531 names: &[String],
3532 mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
3533) -> Result<()> {
3534 if options.baseline.is_some() || options.write_baseline.is_some() {
3535 bail!("baseline files require a single package");
3536 }
3537 let metadata = cargo_metadata(&options.dir, &options.cargo)?;
3538 let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
3539 let selected = if names.is_empty() {
3540 all.clone()
3541 } else {
3542 names.iter().cloned().collect()
3543 };
3544 if let Some(unknown) = selected.difference(&all).next() {
3545 bail!("no package `{unknown}` in the workspace");
3546 }
3547 let base = options
3548 .work_dir
3549 .clone()
3550 .unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
3551 fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
3552 let base = base.canonicalize()?;
3553 if metadata.workspace_root.canonicalize()?.starts_with(&base) {
3554 bail!(
3555 "the work directory {} contains the workspace",
3556 base.display()
3557 );
3558 }
3559 let catalogue = if options.list || options.shard.is_some() {
3560 let path = work_directory(&base, ".catalogue")?;
3561 Some(CatalogueSnapshot {
3562 _lock: WorkLock::take(&path)?,
3563 path,
3564 ready: std::cell::Cell::new(false),
3565 })
3566 } else {
3567 None
3568 };
3569 let batch = WorkspaceBatch {
3570 metadata: &metadata,
3571 work: &base,
3572 catalogue,
3573 };
3574 let member_options = selected.into_iter().map(|name| {
3575 let mut member = options.clone();
3576 member.package = Some(name.clone());
3577 member.work_dir = Some(base.join(&name));
3578 (name, member)
3579 });
3580 let Some(shard) = options.shard else {
3581 for (name, member) in member_options {
3582 let result = run_package(&member, Some(&batch), None);
3583 completed(name, result)?;
3584 }
3585 return Ok(());
3586 };
3587 if !options.source_only || shard.index >= shard.count {
3588 bail!("shards require --source-only and a valid shard index");
3589 }
3590 let catalogues: Vec<_> = member_options
3593 .map(|(name, member)| {
3594 let mut preview = member.clone();
3595 preview.list = true;
3596 preview.shard = None;
3597 preview.progress = false;
3598 let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
3599 let count = report.mutants.as_ref().map_or(0, Vec::len);
3600 if !member.list {
3601 report.mutants = None;
3602 }
3603 (count, report)
3604 });
3605 (name, member, catalogue)
3606 })
3607 .collect();
3608 let total = catalogues
3609 .iter()
3610 .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
3611 .map(|(count, _)| count)
3612 .sum();
3613 let mut offset = 0;
3614 for (name, member, catalogue) in catalogues {
3615 let result = catalogue.and_then(|(member_total, mut report)| {
3616 let range = WorkspaceShard {
3617 offset,
3618 total,
3619 member_total,
3620 };
3621 offset += member_total;
3622 if member.list {
3623 report.analysis.shard = Some(shard);
3624 let mut index = range.offset;
3625 report
3626 .mutants
3627 .as_mut()
3628 .expect("source catalogue")
3629 .retain(|_| {
3630 let keep = shard.contains(index, total);
3631 index += 1;
3632 keep
3633 });
3634 Ok(report)
3635 } else {
3636 run_package(&member, Some(&batch), Some(range))
3637 }
3638 });
3639 completed(name, result)?;
3640 }
3641 Ok(())
3642}
3643
3644struct LeftoverNote(bool);
3646
3647impl Drop for LeftoverNote {
3648 fn drop(&mut self) {
3649 use std::sync::atomic::Ordering;
3650 let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
3651 let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
3652 if let Some(text) = leftover_note(stopped, not_stopped)
3653 && self.0
3654 {
3655 eprintln!("tmt: {text}");
3656 }
3657 }
3658}
3659
3660fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
3661 let stopped = (stopped > 0).then(|| {
3662 format!("stopped {stopped} processes that the tests had left running after their run")
3663 });
3664 let not_stopped = (not_stopped > 0).then(|| {
3665 format!(
3666 "after {not_stopped} runs something the tests started may still be running \
3667 (it could not be found or stopped)"
3668 )
3669 });
3670 match (stopped, not_stopped) {
3671 (None, None) => None,
3672 (Some(one), None) | (None, Some(one)) => Some(one),
3673 (Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
3674 }
3675}
3676
3677pub fn run(options: &Options) -> Result<Report> {
3678 run_package(options, None, None)
3679}
3680
3681fn run_package(
3682 options: &Options,
3683 batch: Option<&WorkspaceBatch<'_>>,
3684 workspace_shard: Option<WorkspaceShard>,
3685) -> Result<Report> {
3686 let _leftovers = LeftoverNote(options.progress);
3687 if let Some(shard) = options.shard
3688 && (!options.source_only || shard.index >= shard.count)
3689 {
3690 bail!("shards require --source-only and a valid shard index");
3691 }
3692 let mut seen_errors = HashSet::new();
3693 let mut error_values = vec![];
3694 for expression in &options.error_values {
3695 let expression = expression.trim();
3696 if expression.chars().any(char::is_control) {
3699 bail!(
3700 "invalid --error expression {expression:?}: it has to be on one line, \
3701 without control characters"
3702 );
3703 }
3704 let parsed = syn::parse_str::<syn::Expr>(expression)
3705 .with_context(|| format!("invalid --error expression {expression:?}"))?;
3706 if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3707 error_values.push(expression);
3708 }
3709 }
3710 let selection = &options.test_selection;
3711 if options.nextest.is_some() {
3712 if !cfg!(unix) {
3713 bail!("the nextest runner is available on Unix");
3714 }
3715 if !options.source_only || options.doc || selection.enabled() {
3716 bail!(
3717 "--test-tool nextest requires --source-only; select tests through the nextest profile"
3718 );
3719 }
3720 }
3721 if options.baseline_jobs > 1 && !selection.enabled() {
3722 bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3723 }
3724 if options.doc && selection.enabled() {
3725 bail!("--doc cannot be combined with isolated test selection");
3726 }
3727 let note = |text: &str| {
3728 if options.progress {
3729 eprintln!("tmt: {text}");
3730 }
3731 };
3732 let dir = options
3733 .dir
3734 .canonicalize()
3735 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
3736
3737 let local_metadata;
3738 let metadata = if let Some(batch) = batch {
3739 batch.metadata
3740 } else {
3741 local_metadata = cargo_metadata(&dir, &options.cargo)?;
3742 &local_metadata
3743 };
3744 let catalogue = batch
3745 .and_then(|batch| batch.catalogue.as_ref())
3746 .filter(|_| options.list);
3747 let package = match &options.package {
3748 Some(name) => metadata.packages.iter().find(|p| &p.name == name),
3749 None => metadata
3750 .packages
3751 .iter()
3752 .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
3753 .or(match &metadata.packages[..] {
3754 [only] => Some(only),
3755 _ => None,
3756 }),
3757 }
3758 .ok_or_else(|| anyhow!("cannot tell which package to analyse; pass --package <name>"))?;
3759 let mut test_packages: Vec<&Package> = vec![package];
3762 for name in &options.also_test {
3763 let other = metadata
3764 .packages
3765 .iter()
3766 .find(|p| &p.name == name)
3767 .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
3768 if !test_packages.iter().any(|p| p.name == other.name) {
3769 test_packages.push(other);
3770 }
3771 }
3772 if options.test_workspace {
3773 test_packages.extend(
3774 metadata
3775 .packages
3776 .iter()
3777 .filter(|other| {
3778 !test_packages
3779 .iter()
3780 .any(|selected| selected.name == other.name)
3781 })
3782 .collect::<Vec<_>>(),
3783 );
3784 }
3785 if options.dependents {
3786 for name in dependents_of(&package.name, &metadata.packages) {
3787 if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
3788 && !test_packages.iter().any(|p| p.name == other.name)
3789 {
3790 test_packages.push(other);
3791 }
3792 }
3793 }
3794 let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
3795 let root_target = package
3796 .targets
3797 .iter()
3798 .find(|t| {
3799 is_kind(
3800 t,
3801 &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
3802 )
3803 })
3804 .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
3805 .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
3806
3807 let workspace = metadata.workspace_root.canonicalize()?;
3809 let requested_work = catalogue
3810 .map(|catalogue| &catalogue.path)
3811 .or(options.work_dir.as_ref());
3812 let work = match requested_work {
3813 Some(dir) => {
3814 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3815 dir.canonicalize()?
3816 }
3817 None => metadata.target_directory.join("tmt"),
3818 };
3819 if workspace.starts_with(&work) {
3822 bail!(
3823 "the work directory {} contains the workspace; choose a directory of its own",
3824 work.display()
3825 );
3826 }
3827 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
3828 let work = work.canonicalize()?;
3829 let work_lock = if catalogue.is_none() {
3830 Some(Arc::new(WorkLock::take(&work)?))
3831 } else {
3832 None
3833 };
3834 let copy = work.join("src");
3835 let marker = work.join(WORK_MARKER);
3836 if copy.exists() && !marker.exists() {
3837 bail!(
3838 "{} exists and was not created by tmt; refusing to delete it. \
3839 Choose another --work-dir or remove it yourself.",
3840 copy.display()
3841 );
3842 }
3843 fs::write(
3844 &marker,
3845 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
3846 )?;
3847 let target_dir = metadata.target_directory.clone();
3848 let forbidden = |path: &Path| {
3849 path == target_dir
3850 || path == work
3851 || batch.is_some_and(|batch| path == batch.work)
3852 || path.file_name().is_some_and(|n| n == ".git")
3853 || (path.parent() == Some(workspace.as_path())
3854 && path.file_name().is_some_and(|n| n == "target"))
3855 };
3856 let state = WorkCopy::open(&work, ©);
3857 let fixtures = options
3858 .copy_fixtures
3859 .iter()
3860 .map(|path| fixture_relative(path))
3861 .collect::<Result<Vec<_>>>()?;
3862 let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
3863 let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
3864 let skip = |path: &Path| {
3865 fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
3866 };
3867 if options.progress && !options.list {
3868 for path in &excluded {
3869 note(&format!(
3870 "excluded fixture {}",
3871 path.strip_prefix(&workspace).unwrap_or(path).display()
3872 ));
3873 }
3874 }
3875 if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
3876 work_directory(&work, "src")?;
3877 let visible = if options.all_files {
3878 None
3879 } else {
3880 git_visible_files(&workspace)?
3881 };
3882 match visible {
3883 Some(files) => {
3886 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
3887 note(&format!(
3888 "copied {copied} files (ignored files are left out)"
3889 ));
3890 }
3891 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
3892 }
3893 for relative in &fixtures {
3894 copy_fixture_entry(
3895 &workspace.join(relative),
3896 ©.join(relative),
3897 &workspace,
3898 &fixture_forbidden,
3899 &state,
3900 &mut BTreeSet::new(),
3901 )?;
3902 }
3903 prune(©, &state)?;
3904 if options.git_index {
3905 git_index::snapshot(&workspace, ©)?;
3906 }
3907 if !options.list {
3908 let mut manifests: Vec<&Path> = metadata
3910 .packages
3911 .iter()
3912 .map(|p| p.manifest_path.as_path())
3913 .collect();
3914 let root_manifest = metadata.workspace_root.join("Cargo.toml");
3915 manifests.push(&root_manifest);
3916 for manifest in manifests {
3917 let Ok(canonical) = manifest.canonicalize() else {
3918 continue;
3919 };
3920 let (Some(manifest_dir), Ok(relative)) =
3921 (canonical.parent(), canonical.strip_prefix(&workspace))
3922 else {
3923 continue;
3924 };
3925 let text = fs::read_to_string(&canonical)?;
3926 if let Some(rewritten) =
3927 absolutize_path_dependencies(&text, manifest_dir, &workspace, ©)?
3928 {
3929 state.write(©.join(relative), &rewritten)?;
3930 }
3931 }
3932 }
3933 if let Some(catalogue) = catalogue {
3934 state.settle(&workspace)?;
3935 catalogue.ready.set(true);
3936 }
3937 }
3938
3939 let in_copy = |path: &Path| -> Result<PathBuf> {
3940 let canonical = path.canonicalize()?;
3941 let relative = canonical
3942 .strip_prefix(&workspace)
3943 .with_context(|| format!("{} is outside the workspace", path.display()))?;
3944 Ok(copy.join(relative))
3945 };
3946 let package_dir = in_copy(
3947 package
3948 .manifest_path
3949 .parent()
3950 .expect("manifest has a parent"),
3951 )?;
3952 let root_file = in_copy(&root_target.src_path)?;
3953 let source_dir = root_file
3954 .parent()
3955 .expect("source file has a parent")
3956 .to_path_buf();
3957
3958 let mut roots = BTreeMap::new();
3961 for owner in &metadata.packages {
3962 for target in &owner.targets {
3963 let production = owner.name == package.name && target.is_production();
3964 if let Ok(path) = in_copy(&target.src_path)
3965 && path.is_file()
3966 {
3967 let selected = roots.entry(path).or_insert(false);
3968 *selected |= production;
3969 }
3970 }
3971 }
3972 let paths = source_graph(roots, ©, |path| state.original(path, &workspace))?;
3973 let scope = requested_scope(options, &workspace, &package_dir, ©)?;
3974 let mut skipped = vec![];
3975 let mut files = vec![];
3976 let mut next_id = 0u32;
3977 let want_witnesses = (options.list || options.rebuild || options.source_only)
3978 && root_target.test_build_arg() == Some(("--lib", None));
3979 let mut witness_candidates = vec![];
3980 for (path, owners) in paths {
3981 let Some(original) = state.original(&path, &workspace)? else {
3982 continue; };
3984 let selected_file = scope.as_ref().is_none_or(|scope| {
3985 let relative = path.strip_prefix(©).unwrap_or(&path).to_string_lossy();
3986 scope.touches(&relative, 1, usize::MAX)
3987 });
3988 if !selected_file && path != root_file {
3989 continue;
3990 }
3991 let display = relative_source(&path, &package_dir).display().to_string();
3992 match instrument::parse_source(&original) {
3993 Ok(parsed) => {
3994 let mut found =
3995 instrument::discover_parsed(&original, &parsed, next_id, &error_values);
3996 if want_witnesses
3998 && selected_file
3999 && owners.consumers.len() == 1
4000 && owners.consumers.contains(&root_file)
4001 {
4002 witness_candidates.extend(
4003 witness::discover_parsed(&original, &parsed, !options.list)
4004 .into_iter()
4005 .map(|mut candidate| {
4006 candidate.file = path.clone();
4007 candidate
4008 }),
4009 );
4010 }
4011 next_id += found.sites.len() as u32;
4012 if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
4013 found.rebuild_sites.append(&mut found.sites);
4014 }
4015 let places = if options.list {
4016 vec![]
4017 } else {
4018 found
4019 .sites
4020 .iter()
4021 .chain(&found.rebuild_sites)
4022 .map(|site| (site.line, site.column, report::one_line(&site.text)))
4023 .collect()
4024 };
4025 files.push(SourceFile {
4026 display,
4027 path,
4028 owners: owners.production,
4029 lines: scope::LineIndex::new(&original),
4030 original,
4031 places,
4032 sites: found.sites,
4033 rebuild_sites: found.rebuild_sites,
4034 rendered: None,
4035 });
4036 }
4037 Err(err) => {
4038 if selected_file {
4039 let diagnostic = format!("{err:#}");
4040 note(&format!("skipping {display}: {diagnostic}"));
4041 let end_line = scope::line_of(&original, original.len());
4042 let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
4043 skipped.push(report::SkippedSite::new(
4044 report::Location {
4045 file: display,
4046 line: 1,
4047 column: 1,
4048 ..Default::default()
4049 },
4050 (end_line, end_column),
4051 report::SkipReason::UnparseableSource,
4052 Some(diagnostic),
4053 ));
4054 }
4055 }
4056 }
4057 }
4058
4059 let since_hunks = match options.since.as_deref() {
4062 Some(revision) if !options.list && options.shard.is_none() => {
4063 scope::hunks(&since_diff(&workspace, revision)?)
4064 }
4065 _ => vec![],
4066 };
4067 let mut tests_changed: Vec<(PathBuf, Vec<scope::Hunk>)> = vec![];
4068 let mut undo_paths: HashSet<PathBuf> = HashSet::new();
4070 let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
4071 if let Some(scope) = &scope {
4073 for file in &mut files {
4074 let relative = file
4075 .path
4076 .strip_prefix(©)
4077 .unwrap_or(&file.path)
4078 .to_string_lossy()
4079 .into_owned();
4080 let in_scope = |site: &Site| {
4081 scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
4082 || scope.touches(&relative, site.line, site.line)
4084 };
4085 let of_file: Vec<scope::Hunk> = since_hunks
4086 .iter()
4087 .filter(|hunk| hunk.file == relative)
4088 .cloned()
4089 .collect();
4090 if (options.rebuild || options.source_only)
4091 && (!reverts::changes(&file.original, &of_file).is_empty()
4092 || reverts::mixed(&file.original, &of_file) > 0)
4093 {
4094 undo_paths.insert(file.path.clone());
4095 }
4096 let of_tests = reverts::test_hunks(&file.original, &of_file);
4097 if of_tests.is_empty() {
4098 file.sites.retain(in_scope);
4099 } else {
4100 beyond_places.extend(
4101 file.sites
4102 .iter()
4103 .filter(|site| !in_scope(site))
4104 .map(|site| (file.path.clone(), site.start, site.end)),
4105 );
4106 tests_changed.push((file.path.clone(), of_tests));
4107 }
4108 file.rebuild_sites.retain(in_scope);
4109 }
4110 files.retain(|f| {
4111 !f.sites.is_empty()
4112 || !f.rebuild_sites.is_empty()
4113 || f.path == root_file
4114 || witness_candidates.iter().any(|c| c.file == f.path)
4115 || undo_paths.contains(&f.path)
4116 });
4117 }
4118 if !options.list {
4119 for candidate in witness_candidates.iter().filter(|c| !c.existing) {
4120 if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
4121 let at = witness_location(file, candidate);
4122 file.places.push((at.line, at.column, at.code));
4123 }
4124 }
4125 }
4126 witness_candidates.retain(|candidate| {
4127 let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
4128 return false;
4129 };
4130 let relative = file
4131 .path
4132 .strip_prefix(©)
4133 .unwrap_or(&file.path)
4134 .to_string_lossy();
4135 scope.as_ref().is_none_or(|scope| {
4136 let site_in_scope = if candidate.edits.len() == 1 {
4137 scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
4138 } else {
4139 candidate.edits.iter().any(|edit| {
4140 scope.touches(
4141 &relative,
4142 file.lines.line_of(edit.span.start),
4143 file.lines.line_of(edit.span.end),
4144 )
4145 })
4146 };
4147 site_in_scope
4148 || candidate
4149 .signature_lines
4150 .iter()
4151 .any(|&line| scope.touches(&relative, line, line))
4152 })
4153 });
4154 let total_sites: usize = files
4155 .iter()
4156 .map(|f| f.sites.len() + f.rebuild_sites.len())
4157 .sum::<usize>()
4158 + witness_candidates
4159 .iter()
4160 .filter(|candidate| !candidate.existing)
4161 .count();
4162 note(&format!("{} sites in {} files", total_sites, files.len()));
4163 if options.source_only {
4164 for file in &mut files {
4165 file.rebuild_sites.append(&mut file.sites);
4166 }
4167 }
4168
4169 let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
4170 let mut mutants = instrument::source_mutants(site);
4171 if include_boundary {
4172 mutants.extend(instrument::source_boundary_mutant(site));
4173 }
4174 if options.literal_operators {
4175 instrument::literal_operator_mutants(&file.original, site, &mut mutants);
4176 }
4177 mutants
4178 };
4179 let counts = options.shard.map(|_| {
4180 let regular: usize = files
4181 .iter()
4182 .map(|file| {
4183 file.rebuild_sites
4184 .iter()
4185 .map(|site| source_mutants(file, site, true).len())
4186 .sum::<usize>()
4187 })
4188 .sum();
4189 let total = regular
4190 + witness_candidates
4191 .iter()
4192 .filter(|candidate| !candidate.existing)
4193 .count();
4194 (regular, total)
4195 });
4196 if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
4197 && range.member_total != local_total
4198 {
4199 bail!("package catalogue changed while preparing its workspace shard");
4200 }
4201 let in_shard = |index| match (options.shard, counts, workspace_shard) {
4202 (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
4203 (Some(shard), Some((_, total)), _) => shard.contains(index, total),
4204 _ => true,
4205 };
4206 if let Some((mut index, _)) = counts {
4207 witness_candidates.retain(|candidate| {
4208 if candidate.existing {
4209 return true;
4210 }
4211 let selected = in_shard(index);
4212 index += 1;
4213 selected
4214 });
4215 }
4216 let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
4217
4218 let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
4219 let mut report_path = repository_prefix(package_path);
4220 if report_path.is_empty()
4221 && batch.is_some()
4222 && let Ok(relative) = package_path.strip_prefix(&workspace)
4223 && !relative.as_os_str().is_empty()
4224 {
4225 report_path = format!("{}/", relative.to_string_lossy().replace('\\', "/"));
4226 }
4227 let mut report = Report {
4228 package: package.name.clone(),
4229 sites: if empty_shard { 0 } else { total_sites },
4230 analysis: report::Analysis {
4231 package_path: report_path,
4232 since: options.since.clone(),
4233 lines: options.lines.clone(),
4234 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
4235 cargo: options.cargo.clone(),
4236 opt_level: options.opt_level,
4237 timeout_seconds: options.timeout_seconds,
4238 baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
4239 timeout_recheck: if options.serial_timeout_rechecks {
4240 "serial"
4241 } else {
4242 "none"
4243 },
4244 wrapper_grace_seconds: selection
4245 .wrapper
4246 .as_ref()
4247 .map(|_| options.wrapper_grace.as_secs()),
4248 rebuild: options.rebuild || options.source_only,
4249 verified: options.verify && !options.source_only,
4250 doc_tests: options.doc,
4251 source_only: options.source_only,
4252 literal_operators: options.literal_operators,
4253 shard: options.shard,
4254 nextest: options.nextest.clone(),
4255 error_values: error_values
4256 .iter()
4257 .map(|value| (*value).to_owned())
4258 .collect(),
4259 test_selection: None,
4260 git_index: options.git_index,
4261 copy_fixtures: options.copy_fixtures.clone(),
4262 copy_fixture_excludes: options.copy_fixture_excludes.clone(),
4263 output_fixtures: options.output_fixtures.clone(),
4264 checkpoint: (options.checkpoint && !options.list)
4265 .then(|| work.join("checkpoint.jsonl")),
4266 },
4267 skipped,
4268 ..Report::default()
4269 };
4270 if options.list {
4271 if catalogue.is_none() {
4272 state.settle(&workspace)?;
4273 }
4274 let mut candidates = vec![];
4275 let mut index = 0;
4276 for file in &files {
4277 let sites = file
4278 .sites
4279 .iter()
4280 .map(|site| (site, false))
4281 .chain(file.rebuild_sites.iter().map(|site| (site, true)));
4282 for (site, requires_rebuild) in sites {
4283 for mutant in source_mutants(file, site, true) {
4284 if in_shard(index) {
4285 candidates.push(report::Candidate {
4286 what: mutant.what,
4287 into: mutant.into,
4288 requires_rebuild,
4289 edits: vec![candidate_edit(
4290 file,
4291 mutant.start,
4292 mutant.end,
4293 mutant.replacement,
4294 )],
4295 });
4296 }
4297 index += 1;
4298 }
4299 }
4300 }
4301 candidates.extend(
4302 witness_candidates
4303 .iter()
4304 .filter(|candidate| !candidate.existing)
4305 .filter_map(|candidate| {
4306 let file = files.iter().find(|file| file.path == candidate.file)?;
4307 Some(report::Candidate {
4308 what: "witness".into(),
4309 into: candidate.description.clone(),
4310 requires_rebuild: true,
4311 edits: candidate
4312 .edits
4313 .iter()
4314 .map(|edit| {
4315 candidate_edit(
4316 file,
4317 edit.span.start,
4318 edit.span.end,
4319 edit.replacement.clone(),
4320 )
4321 })
4322 .collect(),
4323 })
4324 }),
4325 );
4326 report.mutants = Some(candidates);
4327 return Ok(report);
4328 }
4329 if empty_shard || (scope.is_some() && total_sites == 0 && undo_paths.is_empty()) {
4330 state.settle(&workspace)?;
4332 if let Some(path) = &options.baseline {
4333 crate::baseline::load(path)?;
4334 }
4335 if let Some(path) = &options.write_baseline {
4336 crate::baseline::write(path, &[])?;
4337 }
4338 report.record_evaluation();
4339 if let Some(path) = report.analysis.checkpoint.as_deref() {
4340 let checkpoint = Checkpoint::open(path)?;
4341 let settings =
4342 serde_json::json!({"analysis": &report.analysis, "package": &package.name});
4343 let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
4344 checkpoint.start(&identity, settings)?;
4345 checkpoint.finish()?;
4346 }
4347 return Ok(report);
4348 }
4349
4350 for (id, site) in files
4353 .iter_mut()
4354 .flat_map(|file| &mut file.sites)
4355 .enumerate()
4356 {
4357 site.id = id as u32;
4358 }
4359 let beyond: HashSet<u32> = files
4361 .iter()
4362 .flat_map(|file| {
4363 file.sites
4364 .iter()
4365 .filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
4366 .map(|site| site.id)
4367 })
4368 .collect();
4369
4370 let root_source = state
4371 .original(&root_file, &workspace)?
4372 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
4373 let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
4374 String::new()
4375 } else {
4376 state.write(
4377 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
4378 crate::RUNTIME_SOURCE,
4379 )?;
4380 let std_alias = format!("extern crate std as {STD_ALIAS};");
4381 if root_source.contains(&std_alias) {
4382 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
4383 } else {
4384 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
4385 }
4386 };
4387
4388 let mut disabled: HashSet<u32> = HashSet::new();
4390 let mut repairs = BTreeMap::new();
4391 let build_target = work_directory(&work, "target")?;
4392 let target_flags = test_build_flags(
4393 &test_packages,
4394 &selection.targets,
4395 &workspace,
4396 &options.cargo,
4397 );
4398 let build_scope = if target_flags.is_some() {
4399 report::TestBuildScope::SelectedTargets
4400 } else {
4401 report::TestBuildScope::PackageWide
4402 };
4403 let build_note = if !selection.targets.is_empty() && target_flags.is_none() {
4404 "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
4405 } else {
4406 ""
4407 };
4408 if !build_note.is_empty() {
4409 note(build_note.trim_end());
4410 }
4411 let can_build_only_observer = !options.doc
4414 && target_flags.is_none()
4415 && test_packages.len() == 1
4416 && package.targets.len() == 1
4417 && root_target.test
4418 && root_target.test_build_arg() == Some(("--lib", None));
4419 let build_test_binaries = |observer: bool| {
4420 let mut command = Command::new("cargo");
4421 isolate_copy_command(&mut command, &work);
4422 if let Some(lock) = &work_lock {
4423 lock.retain_for(&mut command);
4424 }
4425 command
4426 .args(["test", "--no-run", "--message-format=json"])
4427 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
4428 .args(target_flags.as_deref().unwrap_or_default())
4429 .args((observer && can_build_only_observer).then_some("--lib"))
4430 .args(options.cargo.flags())
4431 .current_dir(©)
4432 .env("CARGO_TARGET_DIR", &build_target)
4433 .env("CARGO_BUILD_BUILD_DIR", &build_target)
4434 .envs(profile_env(options.opt_level))
4435 .stderr(Stdio::piped())
4436 .output()
4437 .context("running cargo test --no-run")
4438 };
4439 let cargo_build = || build_test_binaries(false);
4440 let mut rounds = 0;
4441 let mut newly_disabled = HashSet::new();
4442 let build = loop {
4443 for file in &mut files {
4444 let suffix = if file.path == root_file {
4445 root_suffix.as_str()
4446 } else {
4447 ""
4448 };
4449 write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
4450 }
4451 if !files.iter().any(|f| f.path == root_file) {
4452 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
4453 }
4454 if rounds == 0 {
4455 state.settle(&workspace)?;
4456 }
4457 note(if rounds == 0 {
4458 "building the instrumented crate"
4459 } else {
4460 "rebuilding without the sites that failed to compile"
4461 });
4462 let output = cargo_build()?;
4463 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
4464 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
4465 if output.status.success() {
4466 break build;
4467 }
4468 let diagnostics = || {
4469 [
4470 build.diagnostics.join("\n"),
4471 String::from_utf8_lossy(&output.stderr).into_owned(),
4472 ]
4473 .into_iter()
4474 .filter(|part| !part.trim().is_empty())
4475 .collect::<Vec<_>>()
4476 .join("\n")
4477 };
4478 if build.errors.is_empty() {
4479 bail!("the build failed:\n{build_note}{}", diagnostics());
4480 }
4481 rounds += 1;
4482 let before = disabled.len();
4483 let mut blamed_now: HashSet<u32> = HashSet::new();
4484 for error in &build.errors {
4485 let blamed = blame_error(error, &files, ©, &disabled);
4486 if std::env::var_os("TMT_DEBUG").is_some() {
4487 eprintln!("tmt: debug: blaming {blamed:?} for\n{}", error.rendered);
4488 }
4489 for id in blamed {
4490 repairs
4491 .entry(id)
4492 .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
4493 blamed_now.insert(id);
4494 }
4495 }
4496 disabled.extend(blamed_now.iter().copied());
4497 newly_disabled = blamed_now;
4498 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
4499 bail!(
4500 "the crate does not build after instrumentation.\n\
4501 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
4502 diagnostics()
4503 );
4504 }
4505 };
4506 let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
4507 BuiltSources::from_artifacts(&build.artifacts, &build.features, ©)
4508 } else {
4509 BuiltSources::default()
4510 };
4511 output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
4512 let checkpoint_path = report.analysis.checkpoint.as_deref();
4513 let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
4514 let doc_packages = test_packages
4515 .iter()
4516 .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
4517 if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
4518 bail!("{build_note}`{}` has no test binaries", package.name);
4519 }
4520
4521 let mut session = Session {
4523 progress: options.progress,
4524 serial_timeout_rechecks: options.serial_timeout_rechecks,
4525 package_dir,
4526 binaries: vec![],
4527 };
4528 let wrapper = selection
4529 .wrapper
4530 .as_ref()
4531 .map(|path| {
4532 if path.is_absolute()
4533 || path
4534 .components()
4535 .any(|c| matches!(c, std::path::Component::ParentDir))
4536 {
4537 bail!(
4538 "--test-wrapper must be a path inside the workspace: {}",
4539 path.display()
4540 );
4541 }
4542 let copied = copy.join(path);
4543 if !copied.is_file() {
4544 bail!(
4545 "test wrapper is missing from the work copy: {}",
4546 copied.display()
4547 );
4548 }
4549 Ok(copied)
4550 })
4551 .transpose()?;
4552 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
4553 let root_test_exe = |built: &BuildOutput| {
4554 built
4555 .test_binaries
4556 .iter()
4557 .find(|(name, _, owner, kind)| {
4558 *name == root_target.name && *owner == package.name && *kind == root_target.kind
4559 })
4560 .map(|(_, exe, _, _)| exe.clone())
4561 };
4562 let root_exe = (!witness_candidates.is_empty())
4563 .then(|| root_test_exe(&build))
4564 .flatten();
4565 if let Some(nextest) = &options.nextest {
4566 let mut flags: Vec<_> = test_packages
4567 .iter()
4568 .flat_map(|p| ["-p".to_owned(), p.name.clone()])
4569 .collect();
4570 flags.extend(options.cargo.flags());
4571 runners.push((
4572 "nextest".to_owned(),
4573 Runner::Nextest {
4574 copy: copy.clone(),
4575 target_dir: build_target.clone(),
4576 profile: nextest.profile.clone(),
4577 opt_level: options.opt_level,
4578 flags,
4579 },
4580 session.package_dir.clone(),
4581 ));
4582 } else {
4583 for (name, exe, owner, kind) in build.test_binaries {
4584 if !selection.targets.is_empty() && !selection.targets.contains(&name) {
4585 continue;
4586 }
4587 let owner_package = test_packages
4588 .iter()
4589 .find(|p| p.name == owner)
4590 .expect("binaries are filtered by these packages");
4591 let cwd = in_copy(
4592 owner_package
4593 .manifest_path
4594 .parent()
4595 .expect("manifest has a parent"),
4596 )?;
4597 if selection.enabled() {
4598 let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
4599 let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
4600 for test in all {
4601 let was_ignored = ignored.contains(&test);
4602 if (was_ignored && !selection.include_ignored)
4603 || (!selection.include.is_empty() && !selection.include.contains(&test))
4604 || selection.exclude.contains(&test)
4605 {
4606 continue;
4607 }
4608 runners.push((
4609 format!("{owner}::{}::{name}::{test}", kind.join("+")),
4610 Runner::Isolated {
4611 exe: exe.clone(),
4612 test,
4613 ignored: was_ignored,
4614 wrapper: wrapper.clone(),
4615 },
4616 cwd.clone(),
4617 ));
4618 }
4619 continue;
4620 }
4621 let name = if owner == package.name {
4623 name
4624 } else {
4625 format!("{owner}::{name}")
4626 };
4627 runners.push((name, Runner::Exe(exe), cwd));
4628 }
4629 }
4630 if selection.enabled() && runners.is_empty() {
4631 bail!("{build_note}no tests matched the requested selection");
4632 }
4633 let selected_tests = selection.enabled().then(|| report::TestSelection {
4634 build_scope,
4635 wrapper: selection
4636 .wrapper
4637 .as_ref()
4638 .map(|path| path.display().to_string()),
4639 tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
4640 });
4641 for owner in doc_packages {
4642 let doc = Runner::Doc {
4643 copy: copy.clone(),
4644 target_dir: build_target.clone(),
4645 package: owner.name.clone(),
4646 opt_level: options.opt_level,
4647 flags: options.cargo.flags(),
4648 };
4649 let name = if owner.name == package.name {
4650 "doc tests".to_owned()
4651 } else {
4652 format!("{}::doc tests", owner.name)
4653 };
4654 let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
4655 runners.push((name, doc, cwd));
4656 }
4657 report.analysis.test_selection = selected_tests;
4658 let identity = if checkpoint.is_some() {
4659 let mut build_inputs: Vec<_> = build
4660 .build_scripts
4661 .iter()
4662 .map(serde_json::Value::to_string)
4663 .collect();
4664 build_inputs.sort();
4665 let settings = serde_json::json!({
4668 "build_scripts": build_inputs,
4669 "analysis": &report.analysis, "package": &package.name, "jobs": options.jobs,
4670 "verify": options.verify, "audit": options.audit, "effects": options.effects,
4671 "all_files": options.all_files, "build_scope": build_scope,
4672 "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
4673 });
4674 let mut inputs = BTreeSet::new();
4675 for (root, artifacts) in &build.artifacts {
4676 inputs.insert(root.clone());
4677 if let Some(dependencies) = artifacts
4678 .iter()
4679 .map(|artifact| artifact_inputs(artifact, root, ©))
4680 .find(|deps| !deps.is_empty())
4681 {
4682 inputs.extend(dependencies);
4683 } else {
4684 inputs.extend(artifacts.iter().cloned());
4687 }
4688 }
4689 inputs.extend(
4690 build
4691 .build_scripts
4692 .iter()
4693 .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
4694 );
4695 inputs.retain(|path| !path.starts_with(©));
4698 inputs.extend(
4699 options
4700 .output_fixtures
4701 .iter()
4702 .map(|fixture| build_target.join(&fixture.to)),
4703 );
4704 Some(crate::campaign_identity::compute(
4705 ©,
4706 &settings,
4707 inputs,
4708 options.nextest.is_some(),
4709 )?)
4710 } else {
4711 None
4712 };
4713 let marks = marks_dir(&work)?;
4718 let baseline_jobs = if selection.enabled() {
4719 options.baseline_jobs
4720 } else {
4721 1
4722 };
4723 if options.progress {
4724 eprintln!(
4725 "tmt: baselines: 0/{} completed ({} workers)",
4726 runners.len(),
4727 baseline_jobs
4728 );
4729 }
4730
4731 session.binaries = progress::track_baselines(options.progress, runners.len(), |progress| {
4732 run_pool(runners.len(), baseline_jobs, |slot| {
4733 let index = slot;
4734 let (name, runner, cwd) = runners[index].clone();
4735 let result = (|| {
4736 let trace_path = work.join(format!("trace-{index}.tsv"));
4737 let _ = fs::remove_file(&trace_path);
4738 let mut bin = TestBinary {
4739 name,
4740 cwd,
4741 marks: marks.clone(),
4742 git_ceiling: work.clone(),
4743 work_lock: work_lock.clone(),
4744 tests: BTreeSet::new(),
4745 runner,
4746 baseline: Duration::ZERO,
4747 untraced_baseline: None,
4748 timeout_diagnostic: std::sync::Once::new(),
4749 traced: Duration::ZERO,
4750 timeout: options.timeout_seconds.map(Duration::from_secs),
4751 wrapper_grace: options.wrapper_grace,
4752 report_slow: options.progress,
4753 filtered_timings: Default::default(),
4754 trace: Trace::default(),
4755 effects_baseline: std::sync::OnceLock::new(),
4756 };
4757 session.note(&format!("tracing `{}`", bin.name));
4758 let started = Instant::now();
4759 let trace_env = trace_path.to_string_lossy().into_owned();
4760 let trace = [("TMT_TRACE", trace_env.as_str())];
4761 run_baseline(
4762 &bin,
4763 if options.source_only { &[] } else { &trace },
4764 Duration::from_secs(3600),
4765 &work.join(format!("baseline-{index}.log")),
4766 false,
4767 )?;
4768 bin.traced = started.elapsed();
4769 bin.baseline = bin.traced;
4770 if options.source_only {
4771 bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
4772 }
4773 if !options.source_only && bin.traced > SLOW_TRACE {
4776 let started = Instant::now();
4777 let passed = run_baseline(
4778 &bin,
4779 &[],
4780 bin.traced,
4781 &work.join(format!("baseline-{index}-untraced.log")),
4782 true,
4783 )?;
4784 let elapsed = started.elapsed();
4785 if passed {
4786 bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
4787 bin.baseline = elapsed;
4788 } else {
4789 bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
4790 }
4791 }
4792 let text = match fs::read_to_string(&trace_path) {
4795 Ok(text) => text,
4796 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
4797 Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
4798 };
4799 bin.trace = Trace::parse(&text);
4800 if bin.trace.malformed_lines > 0 {
4801 bail!(
4802 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
4803 bin.name,
4804 bin.trace.malformed_lines
4805 );
4806 }
4807 if let Runner::Exe(exe) = &bin.runner {
4808 bin.tests =
4809 list_tests(exe, &bin.cwd, &work, false, false, work_lock.as_deref())?;
4810 }
4811 Ok(bin)
4812 })();
4813 progress.complete(if result.is_ok() {
4814 progress::Outcome::Survived
4815 } else {
4816 progress::Outcome::Failed
4817 });
4818 result
4819 })
4820 })?;
4821
4822 for file in &files {
4824 for site in &file.sites {
4825 if disabled.contains(&site.id) {
4826 let fallback = options.rebuild
4827 && !matches!(site.kind, SiteKind::Body { .. })
4828 && !instrument::source_mutants(site).is_empty();
4829 match site.kind {
4830 SiteKind::Body { .. } => report.unviable_mutants += 1,
4831 _ if fallback => {}
4832 _ => report.skipped_sites += 1,
4833 }
4834 report.skipped.push(report::SkippedSite::new(
4835 report::location(&file.display, site),
4836 file.lines.position(&file.original, site.end),
4837 if fallback {
4838 report::SkipReason::ProbeReplacedBySourceRebuild
4839 } else {
4840 report::SkipReason::ProbeCompileError
4841 },
4842 repairs.get(&site.id).cloned(),
4843 ));
4844 }
4845 }
4846 if !options.rebuild && !options.source_only {
4847 report.skipped.extend(file.rebuild_sites.iter().map(|site| {
4848 report::SkippedSite::new(
4849 report::location(&file.display, site),
4850 file.lines.position(&file.original, site.end),
4851 report::SkipReason::RequiresSourceRebuild,
4852 None,
4853 )
4854 }));
4855 }
4856 }
4857 if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
4858 checkpoint.start(
4859 identity,
4860 serde_json::json!({
4861 "package": &package.name, "analysis": &report.analysis,
4862 "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
4863 "jobs": options.jobs, "tool_version": env!("CARGO_PKG_VERSION")
4864 }),
4865 )?;
4866 }
4867 let phase = |name: &str, keys: Vec<String>| {
4868 checkpoint
4869 .as_ref()
4870 .zip(identity.as_deref())
4871 .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
4872 .transpose()
4873 };
4874 let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
4875 if checkpoint.is_none() {
4876 return Ok(None);
4877 }
4878 let locations: BTreeMap<_, _> = files
4879 .iter()
4880 .flat_map(|file| {
4881 file.sites
4882 .iter()
4883 .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
4884 })
4885 .collect();
4886 let keys = jobs
4887 .iter()
4888 .map(|job| {
4889 let tests = job
4890 .tests
4891 .iter()
4892 .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
4893 .collect::<Vec<_>>();
4894 serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
4895 })
4896 .collect::<std::result::Result<Vec<_>, _>>()?;
4897 phase(name, keys)
4898 };
4899 let scratch = work.clone();
4900 let mut jobs: Vec<Job> = vec![];
4901 let mut not_evaluated: HashSet<u32> = HashSet::new();
4904 let mut work: Vec<SiteWork> = vec![];
4905 let mut effect_jobs: Vec<(usize, usize)> = vec![];
4907 for file in &files {
4908 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
4909 let primitive = |from: usize, to: usize| {
4912 let Some(mut text) = file.original.get(from..to) else {
4913 return false;
4914 };
4915 let mut start = from;
4916 loop {
4917 let trimmed = text.trim_start();
4918 start += text.len() - trimmed.len();
4919 text = trimmed.trim_end();
4920 match text
4921 .strip_prefix('(')
4922 .and_then(|inner| inner.strip_suffix(')'))
4923 {
4924 Some(inner) => {
4925 start += 1;
4926 text = inner;
4927 }
4928 None => break,
4929 }
4930 }
4931 file.sites.iter().any(|other| {
4932 matches!(other.kind, SiteKind::Arith { .. })
4933 && other.start == start
4934 && other.end == start + text.len()
4935 && !disabled.contains(&other.id)
4936 && {
4937 let seen =
4938 session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
4939 !seen.opaque
4940 && (seen.same || seen.differs || seen.same2 || seen.differs2)
4941 }
4942 })
4943 };
4944 let plan = match session.plan(&file.display, site, options.verify, &primitive) {
4945 Planned::Unreached if beyond.contains(&site.id) => continue,
4948 Planned::Unreached => {
4949 let at = report::location(&file.display, site);
4951 if report.unreached.last() != Some(&at) {
4952 report.unreached.push(at);
4953 }
4954 continue;
4955 }
4956 Planned::Nothing => continue,
4957 Planned::NotEvaluated => {
4958 not_evaluated.insert(site.id);
4959 continue;
4960 }
4961 Planned::Plan(plan) => plan,
4962 };
4963 let mut add =
4964 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
4965 jobs.push(session.job(site.id, mutation, tests_of));
4966 jobs.len() - 1
4967 };
4968 let gaps = plan
4969 .gaps
4970 .into_iter()
4971 .map(
4972 |PlannedGap {
4973 finding,
4974 survivors,
4975 constant_expr,
4976 }| {
4977 let confirm = if options.verify {
4980 survivors
4981 .into_iter()
4982 .map(|m| add(m, &*plan.reaching))
4983 .collect()
4984 } else {
4985 vec![]
4986 };
4987 (finding, confirm, constant_expr)
4988 },
4989 )
4990 .collect();
4991 let infected = &plan.infected;
4992 let runs = plan
4993 .run
4994 .iter()
4995 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
4996 .collect();
4997 work.push(SiteWork {
4998 file: &file.display,
4999 site,
5000 gaps,
5001 constant: plan.constant,
5002 cannot_differ: plan.cannot_differ,
5003 runs,
5004 });
5005 }
5006 }
5007 session.note(&format!(
5008 "running {} mutants on {} thread(s)",
5009 jobs.len(),
5010 options.jobs.max(1)
5011 ));
5012 let probe_checkpoint = probe_phase("probe", &jobs)?;
5013 let mut results =
5014 session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
5015 for result in &results {
5016 report.timeout_rechecks.include(result);
5017 }
5018
5019 if let Some(wanted) = options.audit {
5022 let survivors: Vec<usize> = (0..jobs.len())
5023 .filter(|job| results[*job].survived.is_some())
5024 .collect();
5025 let chosen: Vec<usize> = spread(survivors.len(), wanted)
5026 .into_iter()
5027 .map(|nth| survivors[nth])
5028 .collect();
5029 session.note(&format!(
5030 "audit: running {} of {} surviving mutants against all tests",
5031 chosen.len(),
5032 survivors.len()
5033 ));
5034 let against_all: Vec<Job> = chosen
5035 .iter()
5036 .map(|job| Job {
5037 site: jobs[*job].site,
5038 mutation: jobs[*job].mutation,
5039 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
5040 })
5041 .collect();
5042 let mut audit = report::Audit {
5043 sampled: chosen.len(),
5044 survivors: survivors.len(),
5045 ..report::Audit::default()
5046 };
5047 let audit_checkpoint = probe_phase("audit", &against_all)?;
5048 for (job, again) in chosen.iter().zip(session.run_jobs(
5049 &against_all,
5050 options.jobs,
5051 "audit mutants",
5052 audit_checkpoint.as_ref(),
5053 )?) {
5054 report.timeout_rechecks.include(&again);
5055 if again.survived.is_none() {
5056 results[*job] = again;
5058 let site = files
5059 .iter()
5060 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
5061 if let Some((file, site)) = site {
5062 audit
5063 .disagreements
5064 .push(report::location(&file.display, site));
5065 }
5066 }
5067 }
5068 session.note("audit: recording the tests once more");
5069 for (index, bin) in session.binaries.iter().enumerate() {
5070 let path = scratch.join(format!("trace-{index}-audit.tsv"));
5071 let _ = fs::remove_file(&path);
5072 let trace_env = path.to_string_lossy().into_owned();
5073 let limit = Duration::from_secs(3600);
5074 let outcome = run_binary(
5075 bin,
5076 None,
5077 &[("TMT_TRACE", &trace_env)],
5078 limit,
5079 RunOutput::Quiet,
5080 1,
5081 )?;
5082 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
5083 let _ = fs::remove_file(&path);
5084 let records = bin.trace.differences(&again);
5085 if outcome != Outcome::Pass || records > 0 {
5086 audit.trace_differences.push(report::TraceDifference {
5087 binary: bin.name.clone(),
5088 records,
5089 });
5090 }
5091 }
5092 report.audit = Some(audit);
5093 }
5094 let mut found_out_before: HashSet<usize> = HashSet::new();
5098 let asked: Vec<usize> = work
5099 .iter()
5100 .filter(|item| beyond.contains(&item.site.id))
5101 .flat_map(|item| {
5102 item.gaps
5103 .iter()
5104 .flat_map(|(_, confirm, _)| confirm.iter().copied())
5105 .chain(item.runs.iter().map(|(_, job)| *job))
5106 })
5107 .filter(|job| results[*job].survived.is_some())
5108 .collect();
5109 if !asked.is_empty() {
5110 let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
5111 session.note(&format!(
5112 "running {} surviving mutants against the tests as they were at {revision}",
5113 asked.len()
5114 ));
5115 let suffix = |file: &SourceFile| {
5116 if file.path == root_file {
5117 root_suffix.as_str()
5118 } else {
5119 ""
5120 }
5121 };
5122 let earlier: Vec<(&SourceFile, String)> = tests_changed
5124 .iter()
5125 .filter_map(|(path, hunks)| {
5126 let file = files.iter().find(|file| file.path == *path)?;
5127 let rendered = file.rendered.as_ref()?;
5128 let mut places = hunks
5129 .iter()
5130 .map(|hunk| {
5131 let (from, to) = scope::range_of(&file.original, hunk);
5132 Some((rendered.copied(from, to)?, hunk.old.as_str()))
5133 })
5134 .collect::<Option<Vec<_>>>()?;
5135 places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
5136 let mut text = rendered.text.clone();
5137 for ((from, to), old) in places {
5138 text.replace_range(from..to, old);
5139 }
5140 Some((file, text))
5141 })
5142 .collect();
5143 let attempted = (|| -> Result<Option<Vec<JobResult>>> {
5144 for (file, text) in &earlier {
5145 state.write(&file.path, &format!("{text}{}", suffix(file)))?;
5146 }
5147 if !cargo_build()?.status.success() {
5148 session.note(
5149 "the tests as they were do not build with the code as it is: what they found out is not known",
5150 );
5151 return Ok(None);
5152 }
5153 let all: Vec<&TestBinary> = session.binaries.iter().collect();
5155 if run_source_tests(&all)? != Outcome::Pass {
5156 session.note(
5157 "the tests as they were fail on the code as it is: what they found out is not known",
5158 );
5159 return Ok(None);
5160 }
5161 let against_all: Vec<Job> = asked
5162 .iter()
5163 .map(|job| Job {
5164 site: jobs[*job].site,
5165 mutation: jobs[*job].mutation,
5166 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
5167 })
5168 .collect();
5169 session
5170 .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
5171 .map(Some)
5172 })();
5173 for (file, _) in &earlier {
5175 let rendered = file.rendered.as_ref().expect("rendered before building");
5176 state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
5177 }
5178 if !cargo_build()?.status.success() {
5179 bail!("the crate does not build once its tests are put back as they are");
5180 }
5181 if let Some(again) = attempted? {
5182 for (job, result) in asked.iter().zip(again) {
5183 if result.survived.is_none() && !result.unable && !result.unconfirmed_timeout {
5184 found_out_before.insert(*job);
5185 }
5186 }
5187 }
5188 }
5189 let unable = results
5190 .iter()
5191 .filter(|r| r.unable || r.unconfirmed_timeout)
5192 .count();
5193 not_evaluated.extend(
5194 jobs.iter()
5195 .zip(&results)
5196 .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
5197 .map(|(job, _)| job.site),
5198 );
5199 if !options.rebuild {
5200 report.mutants_not_evaluated = not_evaluated.len();
5201 }
5202 report.mutants_run = results.len() - unable;
5203 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
5204 report.mutants_timed_out = results
5205 .iter()
5206 .filter(|r| r.timed_out && !r.unconfirmed_timeout)
5207 .count();
5208
5209 let confirmed = |w: &SiteWork| {
5212 w.gaps
5213 .iter()
5214 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
5215 };
5216 let constants: BTreeSet<(&str, usize, usize)> = work
5217 .iter()
5218 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
5219 .map(|w| (w.file, w.site.start, w.site.end))
5220 .collect();
5221 for item in &work {
5222 let at = report::location(item.file, item.site);
5223 for (finding, confirm, constant_expr) in &item.gaps {
5224 let repeats = constant_expr
5227 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
5228 if beyond.contains(&item.site.id) {
5229 let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
5231 if confirmed && !repeats && confirm.iter().any(|j| found_out_before.contains(j)) {
5232 report.weakened.push(finding.at().clone());
5233 report.findings.push(finding.clone());
5234 }
5235 continue;
5236 }
5237 match Prediction::of(confirm.iter().map(|j| &results[*j])) {
5238 Prediction::Refuted => report.unstable.push(at.clone()),
5239 Prediction::Confirmed if !repeats => report.findings.push(finding.clone()),
5240 Prediction::Confirmed | Prediction::Unknown => {}
5242 }
5243 }
5244 if let SiteKind::Body {
5247 sole_expr: Some((start, end)),
5248 ..
5249 } = item.site.kind
5250 && constants.contains(&(item.file, start, end))
5251 {
5252 continue;
5253 }
5254 let mut survivors = vec![];
5255 let mut passing_tests = BTreeSet::new();
5256 for (mutation, job) in &item.runs {
5257 if beyond.contains(&item.site.id) && !found_out_before.contains(job) {
5258 continue;
5259 }
5260 if let Some(tests) = &results[*job].survived {
5261 survivors.push(report::describe(item.site, *mutation));
5262 passing_tests.extend(tests.iter().cloned());
5263 }
5264 }
5265 if !survivors.is_empty() {
5266 let first = item.runs.iter().find(|(_, job)| {
5268 results[*job].survived.is_some()
5269 && (!beyond.contains(&item.site.id) || found_out_before.contains(job))
5270 });
5271 if beyond.contains(&item.site.id) {
5272 report.weakened.push(at.clone());
5273 }
5274 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
5275 report.findings.push(Finding::AssertionGap {
5276 at,
5277 survivors,
5278 tests: passing_tests.into_iter().collect(),
5279 effects: vec![],
5280 effects_of: None,
5281 witness: None,
5282 });
5283 }
5284 }
5285
5286 if options.effects && !effect_jobs.is_empty() {
5288 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
5289 let sites: BTreeMap<u32, (&str, &Site)> = files
5290 .iter()
5291 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
5292 .collect();
5293 let traced = run_pool(effect_jobs.len(), options.jobs, |index| {
5294 session.trace_job(
5295 &jobs[effect_jobs[index].1],
5296 &scratch,
5297 options.jobs.clamp(1, effect_jobs.len()),
5298 )
5299 })?;
5300 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
5301 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
5304 for found in changes.values_mut() {
5305 found.retain(|change| {
5306 sites.get(&change.site()).is_none_or(|(file, site)| {
5307 file != mutated_file
5308 || site.end <= mutated.start
5309 || mutated.end <= site.start
5310 })
5311 });
5312 }
5313 changes.retain(|_, found| !found.is_empty());
5314 }
5315 if let Finding::AssertionGap {
5316 effects,
5317 effects_of,
5318 ..
5319 } = &mut report.findings[*finding]
5320 {
5321 *effects = describe_effects(&changes, &sites);
5322 *effects_of = sites
5323 .get(&jobs[*job].site)
5324 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
5325 }
5326 }
5327 }
5328
5329 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
5333 let build_regular_mutants = options.rebuild || options.source_only;
5334 let mut index = 0;
5335 for file in &files {
5336 let retried = file.sites.iter().filter(|site| {
5339 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
5340 || not_evaluated.contains(&site.id)
5341 });
5342 for site in file.rebuild_sites.iter().chain(retried) {
5343 let mutants = source_mutants(file, site, options.source_only);
5344 if build_regular_mutants {
5345 built.extend(mutants.into_iter().filter_map(|mutant| {
5346 let selected = in_shard(index);
5347 index += 1;
5348 selected.then_some((file, site, mutant, None))
5349 }));
5350 } else {
5351 report.mutants_not_built += mutants.len();
5352 }
5353 }
5354 }
5355 if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
5358 let mut twins = vec![];
5359 for file in &files {
5360 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
5361 let integers = session.binaries.iter().all(|bin| {
5363 let seen = bin.trace.merged(site.id);
5364 !seen.reached() || seen.valued()
5365 });
5366 let candidates = jobs_for_site(&jobs, site.id);
5367 let job_of = |mutation: Mutation| {
5368 candidates
5369 .clone()
5370 .find(|&index| jobs[index].mutation == mutation)
5371 };
5372 let mut compared = vec![];
5373 for mutant in instrument::source_mutants(site) {
5374 let job = mutations_like(site, &mutant, integers)
5376 .into_iter()
5377 .find_map(job_of);
5378 if let Some(job) = job {
5379 compared.push(job);
5380 twins.push((file, site, mutant, Some(job)));
5381 }
5382 }
5383 if let (SiteKind::Cmp { op, .. }, Some(job)) =
5386 (&site.kind, job_of(Mutation::Negate))
5387 && !compared.contains(&job)
5388 {
5389 let negated = instrument::SourceMutant {
5390 start: site.start,
5391 end: site.end,
5392 replacement: format!("!({})", site.text),
5393 what: op.symbol().to_string(),
5394 into: "!".to_string(),
5395 };
5396 twins.push((file, site, negated, Some(job)));
5397 }
5398 }
5399 }
5400 let chosen = spread(twins.len(), wanted);
5401 audit.rebuilt = chosen.len();
5402 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
5403 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
5404 }
5405 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
5406 by_speed.sort_by_key(|bin| bin.baseline);
5407 let root_mutant_suffix = if files.iter().any(|file| {
5409 file.path != root_file
5410 && file
5411 .rendered
5412 .as_ref()
5413 .is_some_and(|rendered| rendered.text != file.original)
5414 }) {
5415 root_suffix.as_str()
5416 } else {
5417 ""
5418 };
5419 if !built.is_empty() {
5420 if options.timeout_seconds.is_some()
5421 && built
5422 .iter()
5423 .any(|(file, _, _, _)| built_sources.contains(file))
5424 {
5425 for bin in &by_speed {
5426 bin.warn_timeout_conflict(None);
5427 }
5428 }
5429 let source_checkpoint = if checkpoint.is_some() {
5430 let keys = built
5431 .iter()
5432 .map(|(file, _, mutation, twin)| {
5433 serde_json::to_string(&(
5434 &file.display,
5435 mutation.start,
5436 mutation.end,
5437 &mutation.replacement,
5438 twin,
5439 ))
5440 })
5441 .collect::<std::result::Result<Vec<_>, _>>()?;
5442 phase("source", keys)?
5443 } else {
5444 None
5445 };
5446 session.note(&format!(
5447 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
5448 built.len()
5449 ));
5450 let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
5451 if file.path == root_file {
5452 format!("{text}{suffix}")
5453 } else {
5454 text.to_string()
5455 }
5456 };
5457 let mut skipped_targets = BTreeSet::new();
5460 let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
5462 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
5463 progress::track(
5464 options.progress,
5465 "source mutants",
5466 built.len(),
5467 |progress| -> Result<()> {
5468 for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
5469 let cached = source_checkpoint
5470 .as_ref()
5471 .map(|phase| phase.get::<Option<Outcome>>(index))
5472 .transpose()?
5473 .flatten();
5474 let left_out = left_out
5475 .entry(&file.path)
5476 .or_insert_with(|| built_sources.left_out(file))
5477 .iter()
5478 .any(|(from, to)| *from <= site.start && site.end <= *to);
5479 if left_out || !built_sources.contains(file) {
5480 if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
5481 {
5482 phase.record(index, &Some(Outcome::Unable))?;
5483 }
5484 if twin.is_none() {
5485 report.mutants_not_evaluated += 1;
5486 report.mutants_not_compiled += 1;
5487 if skipped_targets.insert((&file.path, site.start, site.end)) {
5488 report.skipped.push(report::SkippedSite::new(
5489 report::location(&file.display, site),
5490 file.lines.position(&file.original, site.end),
5491 report::SkipReason::SourceNotBuilt,
5492 left_out.then(|| {
5493 "under a `cfg` that the features of this build turn off"
5494 .to_string()
5495 }),
5496 ));
5497 }
5498 } else if let Some(audit) = report.audit.as_mut() {
5499 audit.not_compared += 1;
5500 }
5501 progress.complete(progress::Outcome::Unable);
5502 continue;
5503 }
5504 let outcome = if let Some(cached) = cached {
5505 cached
5506 } else {
5507 let mutated = format!(
5508 "{}{}{}",
5509 &file.original[..mutant.start],
5510 mutant.replacement,
5511 &file.original[mutant.end..]
5512 );
5513 let attempt = || -> Result<Option<Outcome>> {
5515 state.write(
5516 &file.path,
5517 &instrumented(file, &mutated, root_mutant_suffix),
5518 )?;
5519 match source_build(&cargo_build()?) {
5520 SourceBuild::Built => run_source_tests(&by_speed).map(Some),
5521 SourceBuild::Refused => Ok(None),
5522 SourceBuild::Failed(why) => {
5525 session.note(&format!(
5526 "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
5527 ));
5528 Ok(Some(Outcome::Unable))
5529 }
5530 }
5531 };
5532 let attempted = attempt();
5533 let rendered = file.rendered.as_ref().expect("rendered before building");
5535 state.write(
5536 &file.path,
5537 &instrumented(file, &rendered.text, &root_suffix),
5538 )?;
5539 let outcome = attempted?;
5540 if let Some(phase) = &source_checkpoint
5543 && outcome != Some(Outcome::Unable)
5544 {
5545 phase.record(index, &outcome)?;
5546 }
5547 outcome
5548 };
5549 progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
5550 if let Some(job) = twin {
5551 let as_probe = results[*job].survived.is_some();
5553 let Some(audit) = report.audit.as_mut() else {
5554 continue;
5555 };
5556 let comparable = outcome.filter(|_| !results[*job].unable);
5558 match comparable {
5559 Some(_) => audit.compared += 1,
5560 None => audit.not_compared += 1,
5561 }
5562 if comparable.is_some_and(|built| (built == Outcome::Pass) != as_probe) {
5563 let verdict = |passes: bool| if passes { "passes" } else { "fails" };
5564 audit.source_disagreements.push(report::SourceDisagreement {
5565 at: report::location(&file.display, site),
5566 mutant: report::describe(site, mutation_of(site, mutant)),
5567 as_probe: verdict(as_probe).to_string(),
5568 built: verdict(!as_probe).to_string(),
5569 });
5570 }
5571 continue;
5572 }
5573 match outcome {
5574 None => report.unviable_mutants += 1,
5575 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
5576 Some(outcome) => {
5577 report.mutants_run += 1;
5578 report.mutants_killed += (outcome != Outcome::Pass) as usize;
5579 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
5580 }
5581 }
5582 let survived = outcome == Some(Outcome::Pass);
5583 if survived {
5584 let at = report::location(&file.display, site);
5585 let text = match (&site.kind, mutant.replacement.is_empty()) {
5586 (SiteKind::Field { .. }, true) => {
5587 format!("without the field `{}`", report::one_line(&site.text))
5588 }
5589 _ => report::describe(site, mutation_of(site, mutant)),
5590 };
5591 match survivors.last_mut() {
5592 Some((last, texts)) if *last == at => texts.push(text),
5593 _ => survivors.push((at, vec![text])),
5594 }
5595 }
5596 }
5597 Ok(())
5598 },
5599 )?;
5600 if let Some(phase) = &source_checkpoint {
5601 phase.finish()?;
5602 }
5603 report.findings.extend(
5604 survivors
5605 .into_iter()
5606 .map(|(at, survivors)| Finding::Survivor {
5607 at,
5608 survivors,
5609 witness: None,
5610 change_since: None,
5611 advice: None,
5612 }),
5613 );
5614 }
5615
5616 if let Some(revision) = options
5618 .since
5619 .as_deref()
5620 .filter(|_| !options.list && options.shard.is_none())
5621 {
5622 let hunks = scope::hunks(&since_diff(&workspace, revision)?);
5623 let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
5624 .iter()
5625 .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
5626 .filter_map(|file| {
5627 let relative = file
5628 .path
5629 .strip_prefix(©)
5630 .ok()?
5631 .to_string_lossy()
5632 .replace('\\', "/");
5633 let of_file: Vec<_> = hunks
5634 .iter()
5635 .filter(|hunk| hunk.file == relative)
5636 .cloned()
5637 .collect();
5638 let changes = reverts::changes(&file.original, &of_file);
5639 (!changes.is_empty()).then_some((file, changes))
5640 })
5641 .collect();
5642 let total: usize = changed.iter().map(|(_, changes)| changes.len()).sum();
5643 let mixed: usize = files
5646 .iter()
5647 .map(|file| {
5648 let relative = file
5649 .path
5650 .strip_prefix(©)
5651 .unwrap_or(&file.path)
5652 .to_string_lossy()
5653 .replace('\\', "/");
5654 let of_file: Vec<_> = hunks
5655 .iter()
5656 .filter(|hunk| hunk.file == relative)
5657 .cloned()
5658 .collect();
5659 reverts::mixed(&file.original, &of_file)
5660 })
5661 .sum();
5662 if mixed > 0 && (options.rebuild || options.source_only) {
5663 report.mutants_not_evaluated += mixed;
5664 session.note(&format!(
5665 "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
5666 ));
5667 }
5668 if !(options.rebuild || options.source_only) {
5669 report.mutants_not_built += total;
5670 } else if total > 0 {
5671 session.note(&format!(
5672 "building {total} changes undone, one by one (the code as it was at {})",
5673 report::short_revision(revision)
5674 ));
5675 let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
5676 let suffix = if file.path == root_file { suffix } else { "" };
5677 state.write(&file.path, &format!("{text}{suffix}"))
5678 };
5679 let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
5681 let attempted = (|| -> Result<Option<Outcome>> {
5682 for (file, text) in edits {
5683 write(file, text, root_mutant_suffix)?;
5684 }
5685 Ok(match source_build(&cargo_build()?) {
5686 SourceBuild::Built => Some(run_source_tests(&by_speed)?),
5687 SourceBuild::Refused => None,
5688 SourceBuild::Failed(why) => {
5689 session.note(&format!(
5690 "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
5691 ));
5692 Some(Outcome::Unable)
5693 }
5694 })
5695 })();
5696 for (file, _) in edits {
5698 let rendered = file.rendered.as_ref().expect("rendered before building");
5699 write(file, &rendered.text, &root_suffix)?;
5700 }
5701 attempted
5702 };
5703 let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
5704 match outcome {
5705 None => report.unviable_mutants += 1,
5706 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
5707 Some(outcome) => {
5708 report.mutants_run += 1;
5709 report.mutants_killed += (outcome != Outcome::Pass) as usize;
5710 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
5711 }
5712 }
5713 if outcome == Some(Outcome::Pass) {
5714 report.findings.push(Finding::Survivor {
5715 at,
5716 survivors: vec![what],
5717 witness: None,
5718 advice: None,
5719 change_since: Some(revision.to_string()),
5720 });
5721 }
5722 };
5723 let place = |file: &SourceFile, change: &reverts::Change| report::Location {
5724 file: file.display.clone(),
5725 line: change.line,
5726 column: 1,
5727 code: change.code.clone(),
5728 ..Default::default()
5729 };
5730 let mut stuck_files = 0;
5733 for (file, changes) in &changed {
5734 let mut stuck = false;
5735 for change in changes {
5736 let outcome = match &change.undone {
5737 Some(text) => undone(&[(file, text.as_str())])?,
5738 None => None,
5739 };
5740 stuck |= outcome.is_none();
5741 judged(outcome, place(file, change), change.describe());
5742 }
5743 if stuck && changes.len() > 1 {
5744 let whole = reverts::all_undone(&file.original, changes);
5745 let outcome = match &whole {
5746 Some(text) => undone(&[(file, text.as_str())])?,
5747 None => None,
5748 };
5749 stuck = outcome.is_none();
5750 judged(
5751 outcome,
5752 place(file, &changes[0]),
5753 format!("with all {} changes to this file undone", changes.len()),
5754 );
5755 }
5756 stuck_files += usize::from(stuck);
5757 }
5758 if stuck_files > 0 && changed.len() > 1 {
5759 let whole: Option<Vec<String>> = changed
5760 .iter()
5761 .map(|(file, changes)| reverts::all_undone(&file.original, changes))
5762 .collect();
5763 let outcome = match &whole {
5764 Some(texts) => {
5765 let edits: Vec<(&SourceFile, &str)> = changed
5766 .iter()
5767 .zip(texts)
5768 .map(|((file, _), text)| (*file, text.as_str()))
5769 .collect();
5770 undone(&edits)?
5771 }
5772 None => None,
5773 };
5774 let (file, changes) = &changed[0];
5775 judged(
5776 outcome,
5777 place(file, &changes[0]),
5778 format!("with every change undone, in all {} files", changed.len()),
5779 );
5780 }
5781 }
5782 }
5783
5784 let mut witness_files: Vec<&PathBuf> = vec![];
5787 for candidate in &witness_candidates {
5788 if !witness_files.contains(&&candidate.file) {
5789 witness_files.push(&candidate.file);
5790 }
5791 }
5792 for witness_file in witness_files {
5793 let in_root = *witness_file == root_file;
5794 let witness_candidates: Vec<&witness::Candidate> = witness_candidates
5795 .iter()
5796 .filter(|candidate| candidate.file == *witness_file)
5797 .collect();
5798 let file = files
5799 .iter()
5800 .find(|file| file.path == *witness_file)
5801 .expect("witness candidates are of files that are analysed");
5802 let rendered = file.rendered.as_ref().expect("rendered before building");
5803 let left_out_here = built_sources.left_out(file);
5804 let restore = if in_root {
5805 format!("{}{root_suffix}", rendered.text)
5806 } else {
5807 rendered.text.clone()
5808 };
5809 let library_runners: Vec<_> = session
5810 .binaries
5811 .iter()
5812 .filter(|bin| {
5813 root_exe
5814 .as_deref()
5815 .is_some_and(|exe| bin.runner.executable() == Some(exe))
5816 })
5817 .collect();
5818 let ignored = library_runners
5819 .iter()
5820 .find_map(|bin| match &bin.runner {
5821 Runner::Exe(exe) => Some(list_tests(
5822 exe,
5823 &bin.cwd,
5824 &bin.git_ceiling,
5825 true,
5826 false,
5827 bin.work_lock.as_deref(),
5828 )),
5829 _ => None,
5830 })
5831 .transpose()?
5832 .unwrap_or_default();
5833 let runner_for = |scenario: &witness::Scenario| {
5834 library_runners.iter().copied().find(|bin| {
5835 scenario
5836 .source_test
5837 .as_ref()
5838 .is_none_or(|required| match &bin.runner {
5839 Runner::Exe(_) if !in_root => {
5842 let inner = format!("::{required}");
5843 bin.tests
5844 .iter()
5845 .any(|test| test.ends_with(&inner) && !ignored.contains(test))
5846 }
5847 Runner::Exe(_) => {
5848 bin.tests.contains(required) && !ignored.contains(required)
5849 }
5850 Runner::Isolated { test, .. } if !in_root => {
5851 test.ends_with(&format!("::{required}"))
5852 }
5853 Runner::Isolated { test, .. } => test == required,
5854 Runner::Doc { .. } | Runner::Nextest { .. } => false,
5855 })
5856 })
5857 };
5858 let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
5859 let Some(source) = witness::render_edits(&file.original, edits, None) else {
5860 return Ok(false);
5861 };
5862 let suffix = if in_root { root_mutant_suffix } else { "" };
5863 state.write(&file.path, &format!("{source}{suffix}"))?;
5864 Ok(true)
5865 };
5866 let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
5867 if !write_edits(edits)? || !cargo_build()?.status.success() {
5868 return Ok(None);
5869 }
5870 run_source_tests(&by_speed).map(Some)
5871 };
5872 let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
5873 if !write_edits(edits)? {
5874 return Ok(None);
5875 }
5876 let build = build_test_binaries(true)?;
5877 if !build.status.success() {
5878 return Ok(None);
5879 }
5880 let artifacts = parse_build_output(
5881 &String::from_utf8_lossy(&build.stdout),
5882 &[package.name.as_str()],
5883 );
5884 Ok(root_test_exe(&artifacts))
5885 };
5886 let observe = |scenario: &witness::Scenario,
5887 baseline: &TestBinary,
5888 edits: &[witness::Edit],
5889 expected: Option<&str>|
5890 -> Result<Option<witness::Observation>> {
5891 let test = scenario.test_edit(&file.original, witness::TEST_NAME, expected);
5892 let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
5893 let Some(exe) = compile_observer(&edits)? else {
5894 return Ok(None);
5895 };
5896 observe_witness(
5897 baseline,
5898 exe,
5899 wrapper.as_deref(),
5900 scenario,
5901 witness::TEST_NAME,
5902 expected.is_some(),
5903 in_root,
5904 )
5905 };
5906 let witness_checkpoint = if checkpoint.is_some() {
5907 let keys = witness_candidates
5908 .iter()
5909 .map(|candidate| {
5910 let edits = candidate
5911 .edits
5912 .iter()
5913 .map(|edit| (&edit.span, &edit.replacement))
5914 .collect::<Vec<_>>();
5915 serde_json::to_string(&(&candidate.description, edits))
5916 })
5917 .collect::<std::result::Result<Vec<_>, _>>()?;
5918 let name = if in_root {
5919 "witness".to_string()
5920 } else {
5921 format!("witness:{}", file.display)
5922 };
5923 phase(&name, keys)?
5924 } else {
5925 None
5926 };
5927 let mut survivors = vec![];
5928 progress::track(
5929 options.progress,
5930 "source witness mutants",
5931 witness_candidates.len(),
5932 |progress| -> Result<()> {
5933 for (index, candidate) in witness_candidates.iter().copied().enumerate() {
5934 let cached = witness_checkpoint
5935 .as_ref()
5936 .map(|phase| phase.get::<WitnessTrial>(index))
5937 .transpose()?
5938 .flatten();
5939 let at = witness_location(file, candidate);
5940 if !built_sources.contains(file)
5942 || candidate.edits.iter().any(|edit| {
5943 left_out_here
5944 .iter()
5945 .any(|(from, to)| *from <= edit.span.start && edit.span.end <= *to)
5946 })
5947 {
5948 if let Some(phase) =
5949 witness_checkpoint.as_ref().filter(|_| cached.is_none())
5950 {
5951 phase.record(index, &WitnessTrial::Inapplicable)?;
5952 }
5953 if !candidate.existing {
5954 report.mutants_not_evaluated += 1;
5955 report.mutants_not_compiled += 1;
5956 let span = &candidate.edits[0].span;
5957 report.skipped.push(report::SkippedSite::new(
5958 at,
5959 file.lines.position(&file.original, span.end),
5960 report::SkipReason::SourceNotBuilt,
5961 Some(
5962 "under a `cfg` that the features of this build turn off"
5963 .to_string(),
5964 ),
5965 ));
5966 }
5967 progress.complete(progress::Outcome::Unable);
5968 continue;
5969 }
5970 let existing = candidate
5971 .existing
5972 .then(|| {
5973 report.findings.iter().position(|finding| {
5974 let location = finding.at();
5975 location.file == at.file
5976 && location.line == at.line
5977 && location.column == at.column
5978 && finding.survivors().contains(&candidate.description)
5979 })
5980 })
5981 .flatten();
5982 let scenarios: Vec<_> = candidate
5983 .scenarios
5984 .iter()
5985 .filter_map(|scenario| {
5986 runner_for(scenario).map(|runner| (scenario, runner))
5987 })
5988 .take(4)
5989 .collect();
5990 let paired = candidate.edits.len() > 1;
5991 if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
5992 || (paired && scenarios.is_empty())
5993 {
5994 if let Some(phase) =
5995 witness_checkpoint.as_ref().filter(|_| cached.is_none())
5996 {
5997 phase.record(index, &WitnessTrial::Inapplicable)?;
5998 }
5999 progress.complete(progress::Outcome::Unable);
6000 continue;
6001 }
6002 let trial = if let Some(cached) = cached {
6005 cached
6006 } else {
6007 let attempted = (|| -> Result<WitnessTrial> {
6008 if paired {
6009 for edit in &candidate.edits {
6010 if suite(std::slice::from_ref(edit))? != Some(Outcome::Fail) {
6011 return Ok(WitnessTrial::Inapplicable);
6012 }
6013 }
6014 }
6015 Ok(suite(&candidate.edits)?
6016 .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
6017 })();
6018 state.write(&file.path, &restore)?;
6019 let trial = attempted?;
6020 if let Some(phase) = &witness_checkpoint {
6021 phase.record(index, &trial)?;
6022 }
6023 trial
6024 };
6025 let outcome = match trial {
6026 WitnessTrial::Inapplicable => {
6027 progress.complete(progress::Outcome::Unable);
6028 continue;
6029 }
6030 WitnessTrial::Unviable => {
6031 progress.complete(progress::Outcome::Unable);
6032 report.unviable_mutants += usize::from(!candidate.existing);
6033 continue;
6034 }
6035 WitnessTrial::Evaluated(outcome) => outcome,
6036 };
6037 progress.complete(outcome.into());
6038 if !candidate.existing {
6039 report.mutants_run += 1;
6040 report.mutants_killed += usize::from(outcome != Outcome::Pass);
6041 report.mutants_timed_out += usize::from(outcome == Outcome::Timeout);
6042 }
6043 if outcome == Outcome::Pass {
6044 survivors.push(WitnessSurvivor {
6045 candidate,
6046 at,
6047 existing,
6048 scenarios,
6049 });
6050 }
6051 }
6052 Ok(())
6053 },
6054 )?;
6055
6056 if let Some(phase) = &witness_checkpoint {
6057 phase.finish()?;
6058 }
6059 let originals = shared_witnesses(
6060 &file.original,
6061 &survivors,
6062 wrapper.as_deref(),
6063 in_root,
6064 compile_observer,
6065 note,
6066 );
6067 if !survivors.is_empty() {
6068 state.write(&file.path, &restore)?;
6069 }
6070 let originals = originals?;
6071
6072 progress::track(
6073 options.progress,
6074 "distinguishing tests",
6075 survivors.len(),
6076 |progress| -> Result<()> {
6077 for (survivor, original) in survivors.into_iter().zip(originals) {
6078 let mut evidence = None;
6079 let mut original = original;
6080 for (scenario, baseline) in survivor.scenarios {
6081 let shared = original.take();
6082 let distinction = (|| -> Result<_> {
6083 if let Some(shared) = shared {
6084 let edits: Vec<_> = survivor
6086 .candidate
6087 .edits
6088 .iter()
6089 .chain(shared.tests.iter())
6090 .cloned()
6091 .collect();
6092 if let Some(exe) = compile_observer(&edits)?
6093 && let Some(mutant) = observe_witness(
6094 baseline,
6095 exe,
6096 wrapper.as_deref(),
6097 scenario,
6098 &shared.name,
6099 true,
6100 in_root,
6101 )
6102 .ok()
6103 .flatten()
6104 && mutant.equals_expected == Some(false)
6105 && let Some(verified) =
6106 scenario.verified(shared.value, mutant.value)
6107 {
6108 return Ok(Some(verified));
6109 }
6110 }
6113 let Some(original) = observe(scenario, baseline, &[], None)? else {
6114 return Ok(None);
6115 };
6116 let value = original.value;
6117 if !witness::is_expected_literal(&value) {
6118 return Ok(None);
6119 }
6120 let Some(mutant) = observe(
6121 scenario,
6122 baseline,
6123 &survivor.candidate.edits,
6124 Some(&value),
6125 )?
6126 else {
6127 return Ok(None);
6128 };
6129 if mutant.equals_expected != Some(false) || value == mutant.value {
6130 return Ok(None);
6131 }
6132 let Some(checked) = observe(scenario, baseline, &[], Some(&value))?
6133 else {
6134 return Ok(None);
6135 };
6136 if checked.equals_expected != Some(true) || checked.value != value {
6137 return Ok(None);
6138 }
6139 Ok(scenario.verified(value, mutant.value))
6140 })();
6141 match distinction {
6142 Ok(Some(mut verified)) => {
6143 let edits = survivor.candidate.edits.len();
6144 verified.individually_killed = (edits > 1).then_some(edits);
6145 evidence = Some(verified);
6146 break;
6147 }
6148 Ok(None) => {}
6149 Err(err) => note(&format!(
6150 "could not check a distinguishing test for {}: {err:#}",
6151 scenario.expression,
6152 )),
6153 }
6154 }
6155 state.write(&file.path, &restore)?;
6156 progress.complete(Outcome::Pass.into());
6157 if let Some(index) = survivor.existing {
6158 if let Some(evidence) = evidence {
6159 report.findings[index].set_witness(evidence);
6160 }
6161 } else {
6162 report.findings.push(Finding::Survivor {
6163 at: survivor.at,
6164 survivors: vec![survivor.candidate.description.clone()],
6165 advice: survivor
6166 .candidate
6167 .advice
6168 .clone()
6169 .filter(|_| evidence.is_none()),
6170 witness: evidence,
6171 change_since: None,
6172 });
6173 }
6174 }
6175 Ok(())
6176 },
6177 )?;
6178 }
6179
6180 report.record_evaluation();
6181 report.sort_findings();
6182 let places: Vec<FilePlaces> = files
6183 .iter()
6184 .map(|file| FilePlaces {
6185 display: &file.display,
6186 source: &file.original,
6187 lines: &file.lines,
6188 places: &file.places,
6189 })
6190 .collect();
6191 name_findings(&mut report.findings, &places);
6192
6193 let files_with_findings: BTreeSet<&str> = report
6195 .findings
6196 .iter()
6197 .map(|finding| finding.at().file.as_str())
6198 .collect();
6199 let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
6200 .iter()
6201 .filter(|file| files_with_findings.contains(file.display.as_str()))
6202 .map(|f| {
6203 (
6204 f.display.as_str(),
6205 crate::baseline::ignored_lines(&f.original),
6206 )
6207 })
6208 .collect();
6209 let known = match &options.baseline {
6210 Some(path) => Some(crate::baseline::load(path)?),
6211 None => None,
6212 };
6213 let before = report.findings.len();
6214 report.findings.retain(|finding| {
6215 let at = finding.at();
6216 !ignored
6217 .get(at.file.as_str())
6218 .is_some_and(|lines| lines.contains_key(&at.line))
6219 });
6220 if let Some(path) = &options.write_baseline {
6221 crate::baseline::write(path, &report.findings)?;
6222 }
6223 report
6224 .findings
6225 .retain(|finding| !known.as_ref().is_some_and(|known| known.knows(finding)));
6226 report.suppressed = before - report.findings.len();
6227 if let Some(checkpoint) = &checkpoint {
6228 checkpoint.finish()?;
6229 }
6230 Ok(report)
6231}
6232
6233fn repository_prefix(dir: &Path) -> String {
6237 let shown = Command::new("git")
6238 .arg("-C")
6239 .arg(dir)
6240 .args(["rev-parse", "--show-prefix"])
6241 .stderr(Stdio::null())
6242 .output();
6243 match shown {
6244 Ok(output) if output.status.success() => {
6245 String::from_utf8_lossy(&output.stdout).trim().to_string()
6246 }
6247 _ => String::new(),
6248 }
6249}
6250
6251fn spread(count: usize, wanted: usize) -> Vec<usize> {
6254 let wanted = wanted.min(count);
6255 (0..wanted).map(|nth| nth * count / wanted).collect()
6256}
6257
6258struct FilePlaces<'a> {
6260 display: &'a str,
6261 source: &'a str,
6262 lines: &'a scope::LineIndex,
6263 places: &'a [(usize, usize, String)],
6265}
6266
6267fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
6272 let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
6273 for finding in findings {
6274 by_file
6275 .entry(finding.at().file.clone())
6276 .or_default()
6277 .push(finding);
6278 }
6279 for file in files {
6280 let Some(findings) = by_file.remove(file.display) else {
6281 continue;
6282 };
6283 let items = instrument::named_items(file.source);
6284 let index = instrument::ItemIndex::new(&items);
6285 let item_at = |line, column| {
6286 file.lines
6287 .offset_of(file.source, line, column)
6288 .map_or("", |offset| index.at(offset))
6289 };
6290 let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
6291 for (line, column, code) in file.places {
6292 positions
6293 .entry((item_at(*line, *column), code))
6294 .or_default()
6295 .push((*line, *column));
6296 }
6297 for places in positions.values_mut() {
6298 places.sort_unstable();
6299 places.dedup();
6300 }
6301 for finding in findings {
6302 let kind = finding.kind();
6303 let at = finding.at_mut();
6304 let item = item_at(at.line, at.column);
6305 let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
6306 places.partition_point(|&place| place < (at.line, at.column))
6307 });
6308 at.item = item.to_string();
6309 at.id = report::finding_id(kind, at, nth);
6310 }
6311 }
6312}
6313
6314fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
6316 match &site.kind {
6317 SiteKind::Cmp { .. } => plan::CmpOp::ALL
6318 .into_iter()
6319 .find(|op| op.symbol() == mutant.into)
6320 .map_or(Mutation::Negate, Mutation::Op),
6321 SiteKind::Arith { op, .. } => {
6322 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
6323 Mutation::ArithSwap
6324 } else {
6325 Mutation::ArithSwap2
6326 }
6327 }
6328 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
6329 SiteKind::Logic { .. } => Mutation::LogicSwap,
6330 SiteKind::Not { .. } => Mutation::DropNot,
6331 SiteKind::Range { .. } => Mutation::RangeEnd,
6332 _ => Mutation::Delete,
6335 }
6336}
6337
6338fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
6347 let mut all = vec![mutation_of(site, mutant)];
6348 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
6349 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
6350 if into == op.negated() && (integers || !an_order_is_needed) {
6351 all.push(Mutation::Negate);
6352 }
6353 match (op, into) {
6354 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
6355 all.push(Mutation::Shift(1))
6356 }
6357 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
6358 all.push(Mutation::Shift(-1))
6359 }
6360 _ => {}
6361 }
6362 }
6363 all
6364}
6365
6366fn describe_effects(
6369 changes: &BTreeMap<String, BTreeSet<Change>>,
6370 sites: &BTreeMap<u32, (&str, &Site)>,
6371) -> Vec<String> {
6372 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
6373 for (test, found) in changes {
6374 for change in found {
6375 by_change.entry(change).or_default().push(test);
6376 }
6377 }
6378 if by_change.is_empty() {
6379 return vec![
6380 "with the mutant, these tests still reach the same code with the same outcomes: they do not use its result, or it is the same for their inputs".to_string(),
6381 ];
6382 }
6383 let mut out = vec![];
6384 for (change, tests) in by_change.iter().take(3) {
6385 let Some((file, site)) = sites.get(&change.site()) else {
6386 continue;
6387 };
6388 let code = report::location(file, site).code;
6389 let at = format!("{file}:{}", site.line);
6390 let who = match tests[..] {
6391 ["?"] => "a test".to_string(),
6392 [one] => format!("`{one}`"),
6393 [first, ..] => format!("`{first}` (and {} more)", tests.len() - 1),
6394 [] => continue,
6395 };
6396 out.push(match change {
6397 Change::Returns { value, .. } => {
6398 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
6399 }
6400 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
6401 Change::NoLongerRuns { .. } => {
6402 format!("with the mutant, {who} no longer runs `{code}` ({at})")
6403 }
6404 Change::NewOutcome { .. } => {
6405 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
6406 }
6407 });
6408 }
6409 if by_change.len() > 3 {
6410 out.push(format!("(and {} more such changes)", by_change.len() - 3));
6411 }
6412 out
6413}
6414
6415#[cfg(test)]
6416mod tests {
6417 use super::*;
6418 use crate::trace::UNKNOWN_TEST;
6419
6420 #[test]
6421 fn explicit_timeout_conflict_matches_the_coverage_table() {
6422 for row in include_str!("../tests/data/timeout-baseline.pict.tsv")
6423 .lines()
6424 .skip(1)
6425 {
6426 let columns: Vec<_> = row.split('\t').collect();
6427 let &[limit, baseline, selection] = columns.as_slice() else {
6428 panic!("invalid PICT row: {row}");
6429 };
6430 let timeout = (limit == "explicit").then_some(Duration::from_secs(1));
6431 let measured = Duration::from_millis(match baseline {
6432 "below" => 999,
6433 "equal" => 1_000,
6434 "above" => 1_001,
6435 _ => panic!("invalid baseline: {baseline}"),
6436 });
6437 let selected_count = match selection {
6438 "full" => None,
6439 "all-names" => Some(2),
6440 "filtered" => Some(1),
6441 _ => panic!("invalid selection: {selection}"),
6442 };
6443 let expected = limit == "explicit" && baseline != "below" && selection != "filtered";
6444 assert_eq!(
6445 explicit_timeout_conflict(timeout, measured, selected_count, 2).is_some(),
6446 expected,
6447 "{row}"
6448 );
6449 }
6450 }
6451
6452 #[test]
6453 fn campaign_phase_combinations() {
6454 let rows = include_str!("../tests/data/campaign-phases.pict.tsv");
6455 for line in rows.lines().skip(1) {
6456 let columns: Vec<_> = line.split('\t').collect();
6457 let &[baselines, workers, policy, verdict] = columns.as_slice() else {
6458 panic!("invalid PICT row: {line}");
6459 };
6460 let count = |value| if value == "one" { 1 } else { 2 };
6461 let ready = std::sync::Barrier::new(count(baselines));
6462 let baselines = run_pool(2, count(baselines), |index| {
6463 ready.wait();
6464 Ok(index)
6465 })
6466 .unwrap();
6467 assert_eq!(baselines, [0, 1]);
6468
6469 let serial = policy == "serial";
6470 let workers = count(workers);
6471 let results = evaluate_jobs(
6472 2,
6473 workers,
6474 serial,
6475 false,
6476 "test",
6477 None,
6478 &|index, sharing| {
6479 let time_out =
6480 index == 0 && verdict != "pass" && (sharing > 1 || verdict == "timeout");
6481 let unable = index == 0 && verdict == "unable" && sharing == 1;
6482 Ok(JobResult {
6483 first_pass_timeout: false,
6484 unconfirmed_timeout: false,
6485 survived: (!time_out && !unable).then(|| vec![index.to_string()]),
6486 timed_out: time_out,
6487 unable,
6488 })
6489 },
6490 )
6491 .unwrap();
6492 assert_eq!(results[1].survived.as_deref(), Some(&["1".to_owned()][..]));
6493 let mut stats = report::TimeoutRechecks::default();
6494 stats.include(&results[0]);
6495 let first_pass = usize::from(workers == 2 && verdict != "pass");
6496 assert_eq!(stats.first_pass, first_pass, "{line}");
6497 assert_eq!(
6498 stats.confirmed,
6499 usize::from(first_pass == 1 && serial && verdict == "timeout"),
6500 "{line}"
6501 );
6502 assert_eq!(
6503 stats.recovered,
6504 usize::from(first_pass == 1 && serial && verdict == "recovered"),
6505 "{line}"
6506 );
6507 assert_eq!(
6508 stats.unconfirmed,
6509 usize::from(first_pass == 1 && (!serial || verdict == "unable")),
6510 "{line}"
6511 );
6512 }
6513 }
6514
6515 #[cfg(unix)]
6516 #[test]
6517 fn mutant_timeout_uses_the_measured_filter_and_an_explicit_override_wins() {
6518 use std::os::unix::fs::PermissionsExt;
6519 let dir = scratch("filtered-timeout");
6520 let exe = dir.join("runner");
6521 fs::write(
6522 &exe,
6523 "#!/bin/sh\n[ \"$2\" = --exact ] && [ \"$3\" = fast ]\n",
6524 )
6525 .unwrap();
6526 fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
6527 let mut bin = TestBinary {
6528 name: "tests".into(),
6529 cwd: dir.clone(),
6530 marks: marks_dir(&dir).unwrap(),
6531 git_ceiling: dir.clone(),
6532 work_lock: None,
6533 tests: ["fast".to_string(), "slow".to_string()]
6534 .into_iter()
6535 .collect(),
6536 runner: Runner::Exe(exe),
6537 baseline: Duration::from_secs(70),
6538 untraced_baseline: None,
6539 timeout_diagnostic: std::sync::Once::new(),
6540 traced: Duration::from_secs(70),
6541 timeout: None,
6542 wrapper_grace: Duration::ZERO,
6543 report_slow: false,
6544 filtered_timings: Default::default(),
6545 trace: Trace::default(),
6546 effects_baseline: std::sync::OnceLock::new(),
6547 };
6548 assert!(bin.filtered_limit(Some(&["fast".to_string()]), false) < Duration::from_secs(355));
6551 assert_eq!(
6552 bin.filtered_limit(Some(&["slow".to_string()]), false),
6553 Duration::from_secs(355)
6554 );
6555 assert_eq!(bin.filtered_limit(None, false), Duration::from_secs(355));
6556 assert_eq!(bin.filtered_timings.lock().unwrap().len(), 2);
6557 bin.timeout = Some(Duration::from_secs(8));
6558 assert_eq!(
6559 bin.filtered_limit(Some(&["fast".to_string()]), false),
6560 Duration::from_secs(8)
6561 );
6562 fs::remove_dir_all(dir).unwrap();
6563 }
6564
6565 #[test]
6566 fn failed_build_retains_spanless_and_source_diagnostics() {
6567 let stdout = r#"
6568{"reason":"compiler-message","message":{"level":"error","message":"linking with cc failed","rendered":"ld: library not found for -liconv","spans":[]}}
6569{"reason":"compiler-message","message":{"level":"error","message":"source error","rendered":null,"spans":[{"file_name":"src/lib.rs","byte_start":1,"line_start":2,"is_primary":true}]}}
6570"#;
6571 let failed = parse_build_output(stdout, &["p"]);
6572 assert_eq!(failed.errors.len(), 1);
6573 let text = failed.diagnostics.join("\n");
6574 assert!(text.contains("ld: library not found for -liconv"), "{text}");
6575 assert!(text.contains("source error"), "{text}");
6576 }
6577
6578 #[test]
6579 fn test_build_scope_uses_only_known_local_features() {
6580 let package = Package {
6581 name: "pkg".to_owned(),
6582 dependencies: vec![],
6583 features: BTreeMap::from([
6584 ("default".to_owned(), vec!["alias".to_owned()]),
6585 (
6586 "alias".to_owned(),
6587 vec!["extra".to_owned(), "dep/extra".to_owned()],
6588 ),
6589 ("extra".to_owned(), vec![]),
6590 ("separate".to_owned(), vec![]),
6591 ]),
6592 manifest_path: PathBuf::from("workspace/pkg/Cargo.toml"),
6593 targets: vec![],
6594 };
6595 let enabled = |workspace: &str, features: &str, no_default_features, all_features| {
6596 package.enabled_local_features(
6597 Path::new(workspace),
6598 &CargoConfig {
6599 features: vec![features.to_owned()],
6600 no_default_features,
6601 all_features,
6602 locked: false,
6603 },
6604 )
6605 };
6606 let root = "workspace/pkg";
6607 assert_eq!(
6608 enabled(root, "", false, false),
6609 BTreeSet::from(["default", "alias", "extra"])
6610 );
6611 assert_eq!(
6612 enabled(root, "", true, true),
6613 BTreeSet::from(["default", "alias", "extra", "separate"])
6614 );
6615 assert_eq!(
6616 enabled(root, "alias, separate", true, false),
6617 BTreeSet::from(["alias", "extra", "separate"])
6618 );
6619 assert_eq!(
6620 enabled("workspace", "extra other/separate", true, false),
6621 BTreeSet::new()
6622 );
6623 assert_eq!(
6624 enabled("workspace", "pkg/extra other/separate", true, false),
6625 BTreeSet::from(["extra"])
6626 );
6627 }
6628
6629 #[test]
6630 fn test_build_scope_preserves_cargo_target_eligibility() {
6631 let target = |name, kind, test, required_features: &[&str]| {
6632 serde_json::from_value(serde_json::json!({
6633 "name": name, "kind": [kind], "test": test, "src_path": "ignored.rs",
6634 "required-features": required_features,
6635 }))
6636 .unwrap()
6637 };
6638 let package = |name: &str, targets| Package {
6639 name: name.to_owned(),
6640 dependencies: vec![],
6641 targets,
6642 manifest_path: PathBuf::new(),
6643 features: BTreeMap::from([("extra".to_owned(), vec![])]),
6644 };
6645 let first = package(
6646 "first",
6647 vec![
6648 target("first", "proc-macro", true, &[]),
6649 target("name", "bin", true, &[]),
6650 target("name", "example", true, &[]),
6651 target("name", "bench", true, &[]),
6652 target("name", "test", true, &[]),
6653 target("conditional", "test", true, &["extra"]),
6654 target("dependency_feature", "test", true, &["dep/extra"]),
6655 target("disabled", "test", false, &[]),
6656 target("glob[a]", "test", true, &[]),
6657 target("--leading-dash", "test", true, &[]),
6658 target("build-script-build", "custom-build", false, &[]),
6659 ],
6660 );
6661 let second = package(
6662 "second",
6663 vec![
6664 target("second", "staticlib", true, &[]),
6665 target("name", "test", false, &[]),
6666 ],
6667 );
6668 let flags = |packages: &[&Package], names: &[&str], all| {
6669 test_build_flags(
6670 packages,
6671 &names.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
6672 Path::new("workspace"),
6673 &CargoConfig {
6674 all_features: all,
6675 ..CargoConfig::default()
6676 },
6677 )
6678 };
6679 assert_eq!(
6680 flags(&[&first], &["name", "first", "unknown"], false).unwrap(),
6681 [
6682 "--bench=name",
6683 "--bin=name",
6684 "--example=name",
6685 "--lib",
6686 "--test=name"
6687 ]
6688 );
6689 assert_eq!(flags(&[&first], &[], false), None);
6690 assert_eq!(flags(&[&first], &["unknown", "disabled"], false), None);
6691 assert_eq!(flags(&[&first], &["glob[a]"], false), None);
6692 assert_eq!(
6693 flags(&[&first], &["--leading-dash"], false).unwrap(),
6694 ["--test=--leading-dash"]
6695 );
6696 assert_eq!(flags(&[&first], &["name", "conditional"], false), None);
6697 assert_eq!(flags(&[&first], &["dependency_feature"], true), None);
6698 assert_eq!(
6699 flags(&[&first], &["conditional"], true).unwrap(),
6700 ["--test=conditional"]
6701 );
6702 assert_eq!(flags(&[&first, &second], &["name"], false), None);
6703 assert_eq!(flags(&[&first, &second], &["first"], false), None);
6704 assert_eq!(
6705 flags(&[&first, &second], &["first", "second"], false).unwrap(),
6706 ["--lib"]
6707 );
6708 }
6709
6710 #[test]
6711 fn parses_cargo_json_messages() {
6712 let stdout = concat!(
6713 r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":false},"executable":null}"#,
6714 "\n",
6715 r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":true},"executable":"/t/p-abc"}"#,
6716 "\n",
6717 r#"{"reason":"compiler-artifact","package_id":"dep 1.0.0","target":{"name":"dep","kind":["lib"]},"profile":{"test":true},"executable":"/t/dep-abc"}"#,
6718 "\n",
6719 r#"{"reason":"compiler-message","message":{"level":"warning","rendered":"w","spans":[{"file_name":"src/lib.rs","byte_start":1,"line_start":1,"is_primary":true}]}}"#,
6720 "\n",
6721 r#"{"reason":"compiler-message","message":{"level":"error","rendered":"E0308","spans":[{"file_name":"src/lib.rs","byte_start":40,"line_start":3,"is_primary":true},{"file_name":"src/lib.rs","byte_start":2,"line_start":1,"is_primary":false}]}}"#,
6722 "\n",
6723 r#"{"reason":"compiler-message","message":{"level":"error","rendered":"E0308","spans":[{"file_name":"src/lib.rs","byte_start":40,"line_start":3,"is_primary":true},{"file_name":"src/lib.rs","byte_start":2,"line_start":1,"is_primary":false}]}}"#,
6724 "\n",
6725 r#"{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}"#,
6726 "\n",
6727 "not json\n",
6728 r#"{"reason":"build-finished","success":false}"#,
6729 "\n",
6730 );
6731 let out = parse_build_output(stdout, &["p", "other"]);
6732 assert_eq!(
6733 out.test_binaries,
6734 [(
6735 "p".to_string(),
6736 PathBuf::from("/t/p-abc"),
6737 "p".to_string(),
6738 vec!["lib".to_string()]
6739 )]
6740 );
6741 let both = parse_build_output(stdout, &["dep", "p"]);
6743 let owners: Vec<&str> = both.test_binaries.iter().map(|b| b.2.as_str()).collect();
6744 assert_eq!(owners, ["dep", "p"]);
6745 assert_eq!(
6746 out.errors,
6747 [CompileError {
6748 primary: vec![ErrorSpan {
6749 file: "src/lib.rs".into(),
6750 byte_start: 40,
6751 line: 3
6752 }],
6753 secondary: vec![ErrorSpan {
6754 file: "src/lib.rs".into(),
6755 byte_start: 2,
6756 line: 1
6757 }],
6758 rendered: "E0308".into(),
6759 }]
6760 );
6761 }
6762
6763 #[test]
6764 fn package_ids_are_matched_by_name() {
6765 assert!(is_package(
6766 "path+file:///w/target/tmt/src#eligibility@0.0.0",
6767 "eligibility"
6768 ));
6769 assert!(is_package(
6770 "path+file:///w/eligibility#0.1.0",
6771 "eligibility"
6772 ));
6773 assert!(is_package(
6774 "eligibility 0.1.0 (path+file:///w)",
6775 "eligibility"
6776 ));
6777 assert!(!is_package(
6778 "path+file:///w/eligibility#other@0.1.0",
6779 "eligibility-core"
6780 ));
6781 assert!(!is_package(
6782 "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.0",
6783 "eligibility"
6784 ));
6785 }
6786
6787 #[test]
6788 fn test_filter_falls_back_to_the_whole_binary() {
6789 let set = |names: &[&str]| {
6790 names
6791 .iter()
6792 .map(|n| n.to_string())
6793 .collect::<BTreeSet<String>>()
6794 };
6795 let known = set(&["tests::a", "tests::b", "tests::c"]);
6796 assert_eq!(
6797 test_filter(&set(&["tests::a", "tests::b"]), &known),
6798 Some(vec!["tests::a".to_string(), "tests::b".to_string()])
6799 );
6800 assert_eq!(test_filter(&set(&["tests::a", UNKNOWN_TEST]), &known), None);
6802 assert_eq!(test_filter(&set(&["tests::a", "worker"]), &known), None);
6804 assert_eq!(test_filter(&set(&["worker"]), &known), None);
6805
6806 let many: BTreeSet<String> = (0..=MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
6807 assert_eq!(test_filter(&many, &many), None);
6808 let limit: BTreeSet<String> = (0..MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
6809 assert!(test_filter(&limit, &limit).is_some());
6810 }
6811
6812 #[test]
6813 fn libtest_listing() {
6814 let listing =
6815 "tests::a: test\ntests::nested::b: test\nbench_it: benchmark\n\n2 tests, 1 benchmark\n";
6816 assert_eq!(
6817 parse_test_list(listing).into_iter().collect::<Vec<_>>(),
6818 ["tests::a", "tests::nested::b"]
6819 );
6820 }
6821
6822 #[test]
6823 fn domains_from_type_bounds() {
6824 let u8s = crate::trace::TypeBounds {
6825 lhs: (0, 255),
6826 rhs: (0, 255),
6827 };
6828 assert_eq!(
6829 domain_of(LiteralSide::Rhs(18), Some(&u8s)),
6830 Some((-18, 237))
6831 );
6832 assert_eq!(
6833 domain_of(LiteralSide::Lhs(18), Some(&u8s)),
6834 Some((-237, 18))
6835 );
6836 assert_eq!(domain_of(LiteralSide::None, Some(&u8s)), None);
6837 assert_eq!(domain_of(LiteralSide::Rhs(18), None), None);
6838 let wide = crate::trace::TypeBounds {
6839 lhs: (i128::MIN, 0),
6840 rhs: (0, 0),
6841 };
6842 assert_eq!(
6843 domain_of(LiteralSide::Rhs(1), Some(&wide)),
6844 None,
6845 "overflow is not a domain"
6846 );
6847 }
6848
6849 #[test]
6850 fn a_primary_blame_does_not_inspect_later_fallbacks() {
6851 let copy = Path::new("/work");
6852 let source = "pub fn f(n: u32) -> bool { n >= 4 }";
6853 let make = |name: &str, rendered: bool| {
6854 let sites = instrument::discover(source, 0).unwrap().sites;
6855 let output = rendered.then(|| instrument::render(source, &sites, &|_| true));
6856 SourceFile {
6857 display: name.to_string(),
6858 path: copy.join(name),
6859 owners: BTreeSet::new(),
6860 lines: scope::LineIndex::new(source),
6861 original: source.to_string(),
6862 places: vec![],
6863 sites,
6864 rebuild_sites: vec![],
6865 rendered: output,
6866 }
6867 };
6868 let files = [make("primary.rs", true), make("secondary.rs", false)];
6869 let rendered = files[0].rendered.as_ref().unwrap();
6870 let probe = rendered.text.find("__tmt_rt::").unwrap();
6871 let span = |file: &str, byte_start| ErrorSpan {
6872 file: file.to_string(),
6873 byte_start,
6874 line: 1,
6875 };
6876 let error = CompileError {
6877 primary: vec![span("primary.rs", probe)],
6878 secondary: vec![span("secondary.rs", 0)],
6879 rendered: String::new(),
6880 };
6881 assert_eq!(
6882 blame_error(&error, &files, copy, &HashSet::new()),
6883 [rendered.inserted_by(probe).unwrap()]
6884 );
6885 }
6886
6887 #[test]
6888 fn repair_reuses_a_render_but_still_corrects_the_working_copy() {
6889 let dir = scratch("render-repair");
6890 let root = dir.join("work/src");
6891 let path = root.join("f.rs");
6892 let state = WorkCopy::open(&dir.join("work"), &root);
6893 let source = "pub fn f(n: u32) -> bool { n >= 4 }";
6894 let suffix = "\n// root suffix\n";
6895 for row in include_str!("../tests/data/repair-reuse.pict.tsv")
6896 .lines()
6897 .skip(1)
6898 {
6899 let columns: Vec<_> = row.split('\t').collect();
6900 let [cache, which, disk] = columns.as_slice() else {
6901 panic!("{row}")
6902 };
6903 let sites = instrument::discover(source, 1).unwrap().sites;
6904 let id = sites
6905 .iter()
6906 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
6907 .unwrap()
6908 .id;
6909 let disabled = match *which {
6910 "here" => HashSet::from([id]),
6911 "elsewhere" => HashSet::from([u32::MAX]),
6912 _ => HashSet::new(),
6913 };
6914 let before = instrument::render(source, &sites, &|_| true);
6915 let expected = instrument::render(source, &sites, &|id| !disabled.contains(&id));
6916 let original_text = format!("{}{suffix}", before.text);
6917 fs::write(
6918 &path,
6919 if *disk == "rendered" {
6920 &original_text
6921 } else {
6922 source
6923 },
6924 )
6925 .unwrap();
6926 let mut file = SourceFile {
6927 display: "f.rs".to_string(),
6928 path: path.clone(),
6929 owners: BTreeSet::new(),
6930 lines: scope::LineIndex::new(source),
6931 original: source.to_string(),
6932 places: vec![],
6933 sites,
6934 rebuild_sites: vec![],
6935 rendered: (*cache == "present").then_some(before),
6936 };
6937 write_rendered(&mut file, &state, suffix, &disabled, &disabled).unwrap();
6938 assert_eq!(
6939 fs::read_to_string(&path).unwrap(),
6940 format!("{}{suffix}", expected.text),
6941 "{row}"
6942 );
6943 let rendered = file.rendered.unwrap();
6944 assert_eq!(rendered.text, expected.text, "{row}");
6945 for offset in 0..rendered.text.len() {
6946 assert_eq!(
6947 rendered.to_original(offset),
6948 expected.to_original(offset),
6949 "{row}"
6950 );
6951 assert_eq!(
6952 rendered.inserted_by(offset),
6953 expected.inserted_by(offset),
6954 "{row}"
6955 );
6956 }
6957 }
6958 fs::remove_dir_all(dir).unwrap();
6959 }
6960
6961 #[test]
6962 fn source_graph_shares_edges_without_sharing_resolution_or_ownership() {
6963 let scratch = scratch("shared-source-graph");
6964 let copy = scratch.join("work/src");
6965 let before = copy.join("before.rs");
6966 let library = copy.join("lib.rs");
6967 let after = copy.join("after.rs");
6968 let shared = copy.join("shared.rs");
6969 let leaf = copy.join("leaf.rs");
6970 let test_helper = copy.join("test_helper.rs");
6971 let nested_leaf = copy.join("shared/leaf.rs");
6972 let sources = BTreeMap::from([
6973 (before.clone(), r#"#[path = "shared.rs"] mod dep;"#),
6974 (
6975 library.clone(),
6976 r#"mod shared; #[path = "shared.rs"] mod dep;"#,
6977 ),
6978 (after.clone(), r#"include!("shared.rs");"#),
6979 (shared.clone(), "mod leaf; #[cfg(test)] mod test_helper;"),
6980 (leaf.clone(), "fn top() {}"),
6981 (test_helper.clone(), "fn testing() {}"),
6982 (nested_leaf.clone(), "fn nested() {}"),
6983 ]);
6984 for path in sources.keys() {
6985 fs::create_dir_all(path.parent().unwrap()).unwrap();
6986 fs::File::create(path).unwrap();
6987 }
6988 let mut reads = BTreeMap::new();
6989 let graph = source_graph(
6990 [
6991 (before.clone(), false),
6992 (library.clone(), true),
6993 (after.clone(), false),
6994 ],
6995 ©,
6996 |path| {
6997 *reads.entry(path.to_path_buf()).or_insert(0) += 1;
6998 Ok(sources.get(path).map(|source| (*source).to_string()))
6999 },
7000 )
7001 .unwrap();
7002 fs::remove_dir_all(scratch).unwrap();
7003
7004 assert_eq!(
7005 reads[&shared], 2,
7006 "one load in each of two resolution contexts"
7007 );
7008 assert_eq!(reads[&leaf], 1);
7009 assert_eq!(reads[&test_helper], 1);
7010 assert!(!graph.contains_key(&test_helper));
7011 assert_eq!(reads[&nested_leaf], 1);
7012 for path in [&leaf, &shared] {
7013 assert_eq!(
7014 graph[path].consumers,
7015 BTreeSet::from([before.clone(), library.clone(), after.clone()])
7016 );
7017 assert_eq!(graph[path].production, BTreeSet::from([library.clone()]));
7018 }
7019 assert_eq!(
7020 graph[&nested_leaf].consumers,
7021 BTreeSet::from([library.clone()])
7022 );
7023 assert_eq!(graph[&nested_leaf].production, BTreeSet::from([library]));
7024 assert!(!graph.contains_key(&before) && !graph.contains_key(&after));
7025 }
7026
7027 #[test]
7028 fn out_of_line_module_locations() {
7029 let file = Path::new("src/cli.rs");
7030 let statements = "mod child; #[path = \"spec/support.rs\"] mod helper;";
7031 let roots = crate::modules::external(statements, file, Path::new("src"));
7032 assert_eq!(
7033 roots[0].paths,
7034 [
7035 PathBuf::from("src/child.rs"),
7036 PathBuf::from("src/child/mod.rs")
7037 ]
7038 );
7039 assert_eq!(roots[1].paths, [PathBuf::from("src/spec/support.rs")]);
7040 let module = crate::modules::external(statements, file, Path::new("src/cli"));
7041 assert_eq!(module[0].paths[0], PathBuf::from("src/cli/child.rs"));
7042 assert_eq!(module[1].paths[0], PathBuf::from("src/spec/support.rs"));
7043 }
7044
7045 #[test]
7046 fn path_dependencies_outside_the_workspace_become_absolute() {
7047 let manifest = r#"[package]
7048name = "app"
7049
7050[dependencies]
7051serde = "1"
7052core = { path = "../core" } # inside the workspace: kept
7053outside = { path = "../../outside", version = "1" }
7054
7055[dev-dependencies.helper]
7056path = "../../../far/helper"
7057
7058[target.'cfg(unix)'.dependencies]
7059unix-only = { path = "../../unix" }
7060
7061[patch.crates-io]
7062serde = { path = "../../serde-fork" }
7063"#;
7064 let out = absolutize_path_dependencies(
7065 manifest,
7066 Path::new("/w/ws/app"),
7067 Path::new("/w/ws"),
7068 Path::new("/copy"),
7069 )
7070 .unwrap()
7071 .expect("something to rewrite");
7072 assert!(
7073 out.contains(r#"core = { path = "../core" } # inside the workspace: kept"#),
7074 "{out}"
7075 );
7076 assert!(
7077 out.contains(r#"outside = { path = "/w/outside", version = "1" }"#),
7078 "{out}"
7079 );
7080 assert!(out.contains("path = \"/far/helper\""), "{out}");
7081 assert!(out.contains(r#"unix-only = { path = "/w/unix" }"#), "{out}");
7082 assert!(
7083 out.contains(r#"serde = { path = "/w/serde-fork" }"#),
7084 "{out}"
7085 );
7086 assert!(out.contains("serde = \"1\""), "{out}");
7087
7088 let inside = "[dependencies]\ncore = { path = \"../core\" }\n[workspace.dependencies]\nx = { path = \"x\" }\n";
7089 assert_eq!(
7090 absolutize_path_dependencies(
7091 inside,
7092 Path::new("/w/ws/app"),
7093 Path::new("/w/ws"),
7094 Path::new("/copy")
7095 )
7096 .unwrap(),
7097 None
7098 );
7099 let ws = "[workspace.dependencies]\nshared = { path = \"../shared\" }\n";
7100 let out = absolutize_path_dependencies(
7101 ws,
7102 Path::new("/w/ws"),
7103 Path::new("/w/ws"),
7104 Path::new("/copy"),
7105 )
7106 .unwrap()
7107 .unwrap();
7108 assert!(out.contains(r#"shared = { path = "/w/shared" }"#), "{out}");
7109 assert!(
7110 absolutize_path_dependencies(
7111 "not [ toml",
7112 Path::new("/w"),
7113 Path::new("/w"),
7114 Path::new("/copy")
7115 )
7116 .is_err()
7117 );
7118 assert_eq!(normalize(Path::new("/a/./b/../c")), PathBuf::from("/a/c"));
7119 let absolute = "[dependencies]\nhelper = { path = \"/w/ws/helper\" }\n";
7121 let out = absolutize_path_dependencies(
7122 absolute,
7123 Path::new("/w/ws/app"),
7124 Path::new("/w/ws"),
7125 Path::new("/copy"),
7126 )
7127 .unwrap()
7128 .unwrap();
7129 assert!(
7130 out.contains(r#"helper = { path = "/copy/helper" }"#),
7131 "{out}"
7132 );
7133 }
7134
7135 #[test]
7136 fn pool_runs_every_job_once_and_keeps_the_order() {
7137 use std::sync::atomic::{AtomicUsize, Ordering};
7138 for workers in [0, 1, 2, 3, 8, 100] {
7139 for count in [0, 1, 2, 7, 50] {
7140 let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
7141 let results = run_pool(count, workers, |i| {
7142 calls[i].fetch_add(1, Ordering::SeqCst);
7143 std::thread::yield_now();
7144 Ok(i * 10)
7145 })
7146 .unwrap();
7147 assert_eq!(
7148 results,
7149 (0..count).map(|i| i * 10).collect::<Vec<_>>(),
7150 "workers={workers}"
7151 );
7152 assert!(
7153 calls.iter().all(|c| c.load(Ordering::SeqCst) == 1),
7154 "workers={workers} count={count}"
7155 );
7156 }
7157 }
7158 let failed = run_pool(5, 3, |i| {
7159 if i == 3 {
7160 Err(anyhow!("job {i} broke"))
7161 } else {
7162 Ok(i)
7163 }
7164 });
7165 assert_eq!(failed.unwrap_err().to_string(), "job 3 broke");
7166 }
7167
7168 #[test]
7169 fn operand_ranges_ignore_wrapping_parentheses() {
7170 assert_eq!(core_range(10, "a > 0"), (10, 15));
7171 assert_eq!(core_range(10, "(a > 0)"), (11, 16));
7172 assert_eq!(core_range(10, " ( (a > 0) ) "), (14, 19));
7173 assert_eq!(core_range(0, "(a) && (b)"), (0, 10));
7175 assert_eq!(core_range(0, "f(a)"), (0, 4));
7176 assert_eq!(core_range(3, "()"), (4, 4));
7177 assert_eq!(core_range(0, "(a"), (0, 2));
7179 assert_eq!(core_range(0, "a)"), (0, 2));
7180 assert_eq!(core_range(0, ")"), (0, 1));
7181 }
7182
7183 #[test]
7184 fn pool_never_uses_more_threads_than_asked() {
7185 for workers in [1, 2] {
7186 let seen = std::sync::Mutex::new(HashSet::new());
7187 run_pool(6, workers, |_| {
7188 seen.lock().unwrap().insert(std::thread::current().id());
7189 std::thread::sleep(Duration::from_millis(30));
7191 Ok(())
7192 })
7193 .unwrap();
7194 assert_eq!(seen.lock().unwrap().len(), workers);
7195 }
7196 }
7197
7198 #[test]
7199 fn workspace_dependents() {
7200 let package = |name: &str, deps: &[&str]| Package {
7201 name: name.to_string(),
7202 features: BTreeMap::new(),
7203 dependencies: deps
7204 .iter()
7205 .map(|d| Dependency {
7206 name: d.to_string(),
7207 })
7208 .collect(),
7209 manifest_path: PathBuf::new(),
7210 targets: vec![],
7211 };
7212 let packages = [
7213 package("core", &["serde"]),
7214 package("mid", &["core"]),
7215 package("app", &["mid", "other"]),
7216 package("other", &[]),
7217 package("cycle", &["app", "core"]),
7218 ];
7219 assert_eq!(dependents_of("core", &packages), ["app", "cycle", "mid"]);
7220 assert_eq!(dependents_of("mid", &packages), ["app", "cycle"]);
7221 assert_eq!(dependents_of("other", &packages), ["app", "cycle"]);
7222 assert!(dependents_of("app", &packages) == ["cycle"]);
7223 assert!(dependents_of("nobody", &packages).is_empty());
7224 let mutual = [package("x", &["y"]), package("y", &["x"])];
7226 assert_eq!(dependents_of("x", &mutual), ["y"]);
7227 }
7228
7229 #[test]
7230 fn failure_lines_of_libtest() {
7231 assert!(is_failure_line("test tests::a ... FAILED"));
7232 assert!(is_failure_line(
7233 "test src/lib.rs - double (line 3) ... FAILED"
7234 ));
7235 assert!(!is_failure_line("test tests::a ... ok"));
7236 assert!(!is_failure_line("test result: FAILED. 1 passed; 1 failed"));
7237 assert!(!is_failure_line("my output says ... FAILED"));
7238 assert!(!is_failure_line(
7239 "test tests::a ... FAILED (but printed by the test)"
7240 ));
7241 }
7242
7243 #[test]
7244 fn effects_in_words() {
7245 let source = "fn f(s: &mut S) -> bool { s.reset(); s.count > 1 }";
7246 let mut found = instrument::discover(source, 0).unwrap().sites;
7247 found.retain(|s| !matches!(s.kind, SiteKind::Body { .. }));
7248 for (id, site) in found.iter_mut().enumerate() {
7249 site.id = id as u32;
7250 }
7251 let sites: BTreeMap<u32, (&str, &Site)> =
7252 found.iter().map(|s| (s.id, ("src/lib.rs", s))).collect();
7253 let texts: Vec<&str> = found.iter().map(|s| s.text.as_str()).collect();
7254 assert_eq!(
7255 texts,
7256 ["fn f(s: &mut S) -> bool", "s.reset();", "s.count > 1"]
7257 );
7258
7259 let set = |list: &[Change]| list.iter().cloned().collect::<BTreeSet<Change>>();
7260 let mut changes = BTreeMap::new();
7261 changes.insert(
7262 "tests::a".to_string(),
7263 set(&[
7264 Change::Returns {
7265 site: 0,
7266 value: true,
7267 },
7268 Change::NowRuns { site: 1 },
7269 ]),
7270 );
7271 changes.insert(
7272 "tests::b".to_string(),
7273 set(&[Change::NowRuns { site: 1 }, Change::NewOutcome { site: 2 }]),
7274 );
7275 changes.insert("?".to_string(), set(&[Change::NoLongerRuns { site: 2 }]));
7276 assert_eq!(
7277 describe_effects(&changes, &sites),
7278 [
7279 "with the mutant, `tests::a` gets `true` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
7280 "with the mutant, `tests::a` (and 1 more) now runs `s.reset();` (src/lib.rs:1)",
7281 "with the mutant, a test no longer runs `s.count > 1` (src/lib.rs:1)",
7282 "(and 1 more such changes)",
7283 ]
7284 );
7285 let mut many = BTreeMap::new();
7287 many.insert(
7288 "tests::a".to_string(),
7289 set(&[
7290 Change::NowRuns { site: 0 },
7291 Change::NowRuns { site: 1 },
7292 Change::NowRuns { site: 2 },
7293 Change::NoLongerRuns { site: 0 },
7294 Change::NoLongerRuns { site: 1 },
7295 Change::NoLongerRuns { site: 2 },
7296 ]),
7297 );
7298 assert_eq!(
7299 describe_effects(&many, &sites).last().map(String::as_str),
7300 Some("(and 3 more such changes)")
7301 );
7302 let mut few = BTreeMap::new();
7304 few.insert(
7305 "tests::a".to_string(),
7306 set(&[
7307 Change::NowRuns { site: 1 },
7308 Change::NewOutcome { site: 2 },
7309 Change::Returns {
7310 site: 0,
7311 value: false,
7312 },
7313 ]),
7314 );
7315 assert_eq!(
7316 describe_effects(&few, &sites),
7317 [
7318 "with the mutant, `tests::a` gets `false` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
7319 "with the mutant, `tests::a` now runs `s.reset();` (src/lib.rs:1)",
7320 "with the mutant, `tests::a` takes `s.count > 1` (src/lib.rs:1) a way it did not before",
7321 ]
7322 );
7323 assert_eq!(
7324 describe_effects(&BTreeMap::new(), &sites),
7325 [
7326 "with the mutant, these tests still reach the same code with the same outcomes: they do not use its result, or it is the same for their inputs"
7327 ]
7328 );
7329 }
7330
7331 #[test]
7332 fn mutant_timeout_scales_with_the_baseline() {
7333 assert_eq!(mutant_timeout(Duration::ZERO), Duration::from_secs(5));
7334 assert_eq!(
7335 mutant_timeout(Duration::from_secs(2)),
7336 Duration::from_secs(15)
7337 );
7338 }
7339
7340 #[cfg(unix)]
7341 #[test]
7342 fn stopping_nextest_reaps_a_runner_that_ignores_termination() {
7343 use std::io::Read as _;
7344 use std::os::unix::process::CommandExt as _;
7345
7346 let mut child = Command::new("sh")
7347 .args([
7349 "-c",
7350 "trap '' TERM; printf X; n=0; while [ $n -lt 60 ]; do sleep 1; n=$((n+1)); done",
7351 ])
7352 .process_group(0)
7353 .stdout(Stdio::piped())
7354 .spawn()
7355 .unwrap();
7356 child.stdout.take().unwrap().read_exact(&mut [0]).unwrap();
7357
7358 stop_nextest(&mut child, Duration::from_millis(10));
7359 let status = child.try_wait().unwrap().expect("runner was reaped");
7360 assert!(!status.success());
7361 }
7362
7363 #[test]
7364 fn nextest_counts_only_a_test_failure_as_a_kill() {
7365 assert_eq!(nextest_outcome(Some(0)).unwrap(), Outcome::Pass);
7366 assert_eq!(nextest_outcome(Some(100)).unwrap(), Outcome::Fail);
7367 for code in [Some(4), Some(101), Some(102), Some(105), None] {
7368 assert!(nextest_outcome(code).is_err(), "{code:?}");
7369 }
7370 }
7371
7372 #[test]
7373 fn test_polling_backs_off_and_respects_the_remaining_time() {
7374 let mut delay = TEST_POLL_INITIAL;
7375 for micros in [250, 500, 1_000, 2_000, 4_000, 5_000, 5_000] {
7376 assert_eq!(
7377 next_test_poll(&mut delay, Duration::from_secs(1)),
7378 Duration::from_micros(micros)
7379 );
7380 }
7381 let remaining = Duration::from_micros(120);
7382 assert_eq!(next_test_poll(&mut delay, remaining), remaining);
7383 assert_eq!(next_test_poll(&mut delay, Duration::ZERO), Duration::ZERO);
7384 assert_eq!(delay, Duration::from_millis(5));
7385 }
7386 fn scratch(name: &str) -> PathBuf {
7388 let dir = std::env::temp_dir().join(format!("tmt-{name}-{}", std::process::id()));
7389 let _ = fs::remove_dir_all(&dir);
7390 fs::create_dir_all(dir.join("ws/src")).unwrap();
7391 fs::create_dir_all(dir.join("work/src")).unwrap();
7392 dir.canonicalize().unwrap()
7393 }
7394
7395 #[cfg(unix)]
7396 #[test]
7397 fn a_descendant_cannot_keep_the_completed_runner_output_open() {
7398 use std::os::unix::fs::PermissionsExt as _;
7399
7400 let dir = scratch("descendant-output");
7401 let work = dir.join("work");
7402 let exe = work.join("runner");
7403 fs::write(&exe, "#!/bin/sh\nsleep 8 &\nexit 0\n").unwrap();
7404 fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
7405 let bin = TestBinary {
7406 name: "runner".into(),
7407 cwd: work.join("src"),
7408 marks: marks_dir(&work).unwrap(),
7409 git_ceiling: work,
7410 work_lock: None,
7411 tests: BTreeSet::new(),
7412 runner: Runner::Exe(exe),
7413 baseline: Duration::ZERO,
7414 untraced_baseline: None,
7415 timeout_diagnostic: std::sync::Once::new(),
7416 traced: Duration::ZERO,
7417 timeout: None,
7418 wrapper_grace: Duration::ZERO,
7419 report_slow: false,
7420 filtered_timings: Default::default(),
7421 trace: Trace::default(),
7422 effects_baseline: std::sync::OnceLock::new(),
7423 };
7424 let started = Instant::now();
7425 assert_eq!(
7426 run_binary(
7427 &bin,
7428 None,
7429 &[],
7430 Duration::from_secs(2),
7431 RunOutput::FirstFailure,
7432 1
7433 )
7434 .unwrap(),
7435 Outcome::Pass
7436 );
7437 assert!(
7438 started.elapsed() < Duration::from_secs(6),
7439 "a descendant held the output pipe open"
7440 );
7441 fs::remove_dir_all(dir).unwrap();
7442 }
7443
7444 #[cfg(unix)]
7445 #[test]
7446 fn a_detached_descendant_does_not_hold_the_runner_open() {
7447 let dir = scratch("detached-output");
7448 let work = dir.join("work");
7449 let source = work.join("runner.rs");
7450 let exe = work.join("runner");
7451 fs::write(
7452 &source,
7453 r#"
7454use std::os::unix::process::CommandExt;
7455fn main() {
7456 let child = std::process::Command::new("sleep").arg("8").process_group(0).spawn().unwrap();
7457 std::fs::write("child.pid", child.id().to_string()).unwrap();
7458}
7459"#,
7460 )
7461 .unwrap();
7462 let output = Command::new("rustc")
7463 .arg(&source)
7464 .arg("-o")
7465 .arg(&exe)
7466 .output()
7467 .unwrap();
7468 assert!(
7469 output.status.success(),
7470 "{}",
7471 String::from_utf8_lossy(&output.stderr)
7472 );
7473 let bin = TestBinary {
7474 name: "runner".into(),
7475 cwd: work.join("src"),
7476 marks: marks_dir(&work).unwrap(),
7477 git_ceiling: work,
7478 work_lock: None,
7479 tests: BTreeSet::new(),
7480 runner: Runner::Exe(exe),
7481 baseline: Duration::ZERO,
7482 untraced_baseline: None,
7483 timeout_diagnostic: std::sync::Once::new(),
7484 traced: Duration::ZERO,
7485 timeout: None,
7486 wrapper_grace: Duration::ZERO,
7487 report_slow: false,
7488 filtered_timings: Default::default(),
7489 trace: Trace::default(),
7490 effects_baseline: std::sync::OnceLock::new(),
7491 };
7492 let started = Instant::now();
7493 let outcome = run_binary(
7494 &bin,
7495 None,
7496 &[],
7497 Duration::from_secs(2),
7498 RunOutput::FirstFailure,
7499 1,
7500 );
7501 let elapsed = started.elapsed();
7502 let pid = fs::read_to_string(bin.cwd.join("child.pid"))
7504 .unwrap()
7505 .parse()
7506 .unwrap();
7507 kill_test_group(pid);
7508 fs::remove_dir_all(dir).unwrap();
7509 assert_eq!(outcome.unwrap(), Outcome::Pass);
7510 assert!(
7511 elapsed < Duration::from_secs(6),
7512 "a detached descendant held the output pipe open"
7513 );
7514 }
7515
7516 fn set_modified(path: &Path, time: std::time::SystemTime) {
7517 fs::File::options()
7518 .write(true)
7519 .open(path)
7520 .unwrap()
7521 .set_modified(time)
7522 .unwrap();
7523 }
7524
7525 fn modified(path: &Path) -> std::time::SystemTime {
7526 fs::metadata(path).unwrap().modified().unwrap()
7527 }
7528
7529 fn copy_run(dir: &Path, selected: &[&str], write: bool) -> WorkCopy {
7532 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7533 let copy = work.join("src");
7534 let state = WorkCopy::open(&work, ©);
7535 copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
7536 prune(©, &state).unwrap();
7537 for name in selected {
7538 let path = copy.join(name);
7539 let original = state.original(&path, &workspace).unwrap().unwrap();
7540 assert_eq!(original, fs::read_to_string(workspace.join(name)).unwrap());
7541 if write {
7542 state
7543 .write(&path, &format!("instrumented {original}"))
7544 .unwrap();
7545 } else {
7546 state.record(&path).unwrap(); }
7548 }
7549 if write {
7550 state.settle(&workspace).unwrap();
7551 }
7552 state
7553 }
7554
7555 #[test]
7557 fn work_copy_table() {
7558 let table = include_str!("../tests/data/workcopy.pict.tsv");
7559 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
7560 let mut rows = 0;
7561 for (index, line) in table.lines().skip(1).enumerate() {
7562 let [earlier, source, selected] = line.split('\t').collect::<Vec<_>>()[..] else {
7563 panic!("bad row: {line}");
7564 };
7565 let dir = scratch(&format!("copy-table-{index}"));
7566 let (file, copied) = (dir.join("ws/src/a.rs"), dir.join("work/src/src/a.rs"));
7567 let log = dir.join("work").join(WRITTEN_LOG);
7568 fs::write(&file, "v1").unwrap();
7569 set_modified(&file, hour_ago);
7570 match earlier {
7571 "none" => {}
7572 "plain" => drop(copy_run(&dir, &[], true)),
7573 "written" => drop(copy_run(&dir, &["src/a.rs"], true)),
7574 "logged_only" => drop(copy_run(&dir, &["src/a.rs"], false)),
7575 _ => panic!("{line}"),
7576 }
7577 if copied.exists() {
7578 set_modified(&copied, hour_ago);
7579 }
7580 let before = fs::read_to_string(&copied).ok();
7581 match source {
7582 "same" => {}
7583 "edited" => fs::write(&file, "version 2").unwrap(),
7584 "deleted" => fs::remove_file(&file).unwrap(),
7585 _ => panic!("{line}"),
7586 }
7587 let selected = selected == "yes";
7588 copy_run(&dir, if selected { &["src/a.rs"] } else { &[] }, true);
7589
7590 let wanted = match (source, selected) {
7591 ("deleted", _) => None,
7592 ("same", true) => Some("instrumented v1".to_string()),
7593 ("same", false) => Some("v1".to_string()),
7594 (_, true) => Some("instrumented version 2".to_string()),
7595 (_, false) => Some("version 2".to_string()),
7596 };
7597 assert_eq!(fs::read_to_string(&copied).ok(), wanted, "{line}");
7598 assert_eq!(
7599 fs::read_to_string(&log).unwrap_or_default(),
7600 if selected { "src/a.rs\n" } else { "" },
7601 "{line}"
7602 );
7603 if before == wanted && wanted.is_some() && earlier != "logged_only" {
7606 assert_eq!(modified(&copied), hour_ago, "{line}");
7607 }
7608 if before != wanted && wanted.is_some() {
7611 assert!(
7612 modified(&copied) > hour_ago + Duration::from_secs(1800),
7613 "{line}"
7614 );
7615 }
7616 copy_run(&dir, &[], true);
7618 assert_eq!(
7619 fs::read_to_string(&copied).ok(),
7620 fs::read_to_string(&file).ok(),
7621 "{line}"
7622 );
7623 assert_eq!(fs::read_to_string(&log).unwrap(), "", "{line}");
7624 fs::remove_dir_all(&dir).unwrap();
7625 rows += 1;
7626 }
7627 assert_eq!(rows, 20);
7628 }
7629
7630 #[test]
7631 fn streaming_copy_comparison_matches_bytes() {
7632 use std::io::{self, Read};
7633
7634 struct Chunks<'a> {
7635 rest: &'a [u8],
7636 chunk: usize,
7637 interrupt: bool,
7638 fail: bool,
7639 }
7640
7641 impl Read for Chunks<'_> {
7642 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
7643 if self.interrupt {
7644 self.interrupt = false;
7645 return Err(io::ErrorKind::Interrupted.into());
7646 }
7647 if self.fail {
7648 self.fail = false;
7649 return Err(io::ErrorKind::PermissionDenied.into());
7650 }
7651 let limit = out.len().min(self.chunk);
7652 self.rest.read(&mut out[..limit])
7653 }
7654 }
7655
7656 for row in include_str!("../tests/data/workcopy-compare.pict.tsv")
7657 .lines()
7658 .skip(1)
7659 {
7660 let fields: Vec<_> = row.split('\t').collect();
7661 let [size, relation, reads] = fields.as_slice() else {
7662 panic!("{row}")
7663 };
7664 let size = match *size {
7665 "empty" => 0,
7666 "before" => 65535,
7667 "boundary" => 65536,
7668 "after" => 65537,
7669 "multi" => 131079,
7670 _ => panic!("{row}"),
7671 };
7672 let left: Vec<_> = (0..size).map(|i| (i % 251) as u8).collect();
7673 let mut right = left.clone();
7674 match *relation {
7675 "equal" => (),
7676 "early" => right[0] ^= 1,
7677 "late" => right[size - 1] ^= 1,
7678 "suffix" => right.push(1),
7679 "shorter" => {
7680 right.pop();
7681 }
7682 _ => panic!("{row}"),
7683 }
7684 let make_reader = |first, rest, fail_first| Chunks {
7685 rest,
7686 chunk: if *reads == "regular" {
7687 usize::MAX
7688 } else if first {
7689 1031
7690 } else {
7691 2063
7692 },
7693 interrupt: *reads == "interrupted",
7694 fail: first == fail_first && *reads == "failed",
7695 };
7696 for (a, b, fail_first) in [
7697 (&left[..], &right[..], true),
7698 (&right[..], &left[..], false),
7699 ] {
7700 let compared = compare_streams(
7701 make_reader(true, a, fail_first),
7702 make_reader(false, b, fail_first),
7703 );
7704 if *reads == "failed" {
7705 assert_eq!(
7706 compared.unwrap_err().kind(),
7707 io::ErrorKind::PermissionDenied,
7708 "{row}"
7709 );
7710 } else {
7711 assert_eq!(compared.unwrap(), a == b, "{row}");
7712 }
7713 }
7714 }
7715 }
7716
7717 #[test]
7718 fn work_copy_keeps_modification_times() {
7719 let dir = scratch("copy-times");
7720 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
7721 let names = ["src/lib.rs", "src/plain.rs", "src/edited.rs"];
7722 for name in names {
7723 fs::write(dir.join("ws").join(name), format!("// {name}")).unwrap();
7724 set_modified(&dir.join("ws").join(name), hour_ago);
7725 }
7726 let copy = dir.join("work/src");
7727 let runtime = copy.join("src/__tmt_rt.rs");
7728 let run = || {
7729 let state = copy_run(&dir, &[], false);
7730 for name in ["src/lib.rs", "src/edited.rs"] {
7731 let original = state.original(©.join(name), &dir.join("ws")).unwrap();
7732 state
7733 .write(©.join(name), &format!("probe {}", original.unwrap()))
7734 .unwrap();
7735 }
7736 assert_eq!(state.original(&runtime, &dir.join("ws")).ok(), {
7738 if runtime.exists() { Some(None) } else { None }
7739 });
7740 state.write(&runtime, "runtime").unwrap();
7741 state.settle(&dir.join("ws")).unwrap();
7742 };
7743 run();
7744 for name in names.iter().map(|n| copy.join(n)).chain([runtime.clone()]) {
7745 set_modified(&name, hour_ago);
7746 }
7747 fs::write(dir.join("ws/src/edited.rs"), "// edited since").unwrap();
7748 run();
7749 for name in ["src/lib.rs", "src/plain.rs", "src/__tmt_rt.rs"] {
7751 assert_eq!(modified(©.join(name)), hour_ago, "{name}");
7752 }
7753 assert_ne!(modified(©.join("src/edited.rs")), hour_ago);
7754 assert_eq!(
7755 fs::read_to_string(copy.join("src/edited.rs")).unwrap(),
7756 "probe // edited since"
7757 );
7758 assert_eq!(
7759 fs::read_to_string(copy.join("src/lib.rs")).unwrap(),
7760 "probe // src/lib.rs"
7761 );
7762 assert_eq!(
7763 fs::read_to_string(dir.join("work").join(WRITTEN_LOG)).unwrap(),
7764 "src/__tmt_rt.rs\nsrc/edited.rs\nsrc/lib.rs\n"
7765 );
7766 let later = hour_ago + Duration::from_secs(60);
7768 set_modified(&dir.join("ws/src/plain.rs"), later);
7769 run();
7770 assert_eq!(modified(©.join("src/plain.rs")), hour_ago);
7771 let plain = fs::read_to_string(dir.join("ws/src/plain.rs")).unwrap();
7774 fs::write(dir.join("ws/src/plain.rs"), plain.to_uppercase()).unwrap();
7775 set_modified(
7776 &dir.join("ws/src/plain.rs"),
7777 hour_ago - Duration::from_secs(60),
7778 );
7779 run();
7780 assert_eq!(
7781 fs::read_to_string(copy.join("src/plain.rs")).unwrap(),
7782 plain.to_uppercase()
7783 );
7784 assert!(modified(©.join("src/plain.rs")) > later);
7785 fs::remove_dir_all(&dir).unwrap();
7786 }
7787
7788 #[test]
7789 fn work_copy_log_is_not_trusted() {
7790 let dir = scratch("copy-log");
7791 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7792 let copy = work.join("src");
7793 let outside = dir.join("outside.txt");
7794 fs::write(&outside, "keep").unwrap();
7795 fs::write(workspace.join("src/a.rs"), "a").unwrap();
7796 fs::write(
7798 work.join(WRITTEN_LOG),
7799 format!(
7800 "../../outside.txt\n{}\n\nsrc/../../../outside.txt\nsrc/a.rs\n",
7801 outside.display()
7802 ),
7803 )
7804 .unwrap();
7805 let state = WorkCopy::open(&work, ©);
7806 assert_eq!(
7807 state.earlier,
7808 [copy.join("src/a.rs")].into_iter().collect::<HashSet<_>>()
7809 );
7810 copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
7811 state.settle(&workspace).unwrap();
7812 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7813 assert_eq!(fs::read_to_string(copy.join("src/a.rs")).unwrap(), "a");
7814
7815 let state = WorkCopy::open(&work, ©);
7817 assert!(state.write(&outside, "x").is_err());
7818 assert!(state.write(©.join("src/a\nb.rs"), "x").is_err());
7819 assert!(!copy.join("src/a\nb.rs").exists());
7820 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7821 fs::remove_dir_all(&dir).unwrap();
7822 }
7823 #[test]
7824 fn work_copy_log_follows_every_write() {
7825 let dir = scratch("copy-log-order");
7826 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7827 let copy = work.join("src");
7828 let log = work.join(WRITTEN_LOG);
7829 let names = ["h", "c", "f", "a", "e", "b", "g", "d"].map(|n| format!("src/{n}.rs"));
7830 for name in &names {
7831 fs::write(workspace.join(name), "x").unwrap();
7832 }
7833 let state = copy_run(&dir, &[], false);
7834 state.record(©.join(&names[0])).unwrap();
7836 state.record(©.join(&names[0])).unwrap();
7837 assert_eq!(fs::read_to_string(&log).unwrap(), "src/h.rs\n");
7838 assert_eq!(fs::read_to_string(copy.join(&names[0])).unwrap(), "x");
7839 for name in &names {
7840 state.write(©.join(name), "probe").unwrap();
7841 }
7842 state.settle(&workspace).unwrap();
7843 let mut sorted = names.to_vec();
7844 sorted.sort();
7845 assert_eq!(
7846 fs::read_to_string(&log).unwrap(),
7847 sorted.iter().map(|n| format!("{n}\n")).collect::<String>()
7848 );
7849
7850 let state = copy_run(&dir, &[], false);
7852 state.settle(&workspace).unwrap();
7853 assert_eq!(fs::read_to_string(&log).unwrap(), "");
7854 state.write(©.join(&names[3]), "probe").unwrap();
7855 assert_eq!(fs::read_to_string(&log).unwrap(), "src/a.rs\n");
7856 fs::remove_dir_all(&dir).unwrap();
7857 }
7858
7859 #[test]
7860 fn sync_copies_what_is_not_up_to_date_and_nothing_else() {
7861 let dir = scratch("copy-sync");
7862 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7863 let copy = work.join("src");
7864 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
7865 for name in [
7866 "same",
7867 "longer",
7868 "newer",
7869 "was_dir",
7870 "was_link",
7871 "short_link",
7872 "twin_link",
7873 "shorter",
7874 ] {
7875 fs::write(workspace.join("src").join(name), "source").unwrap();
7876 set_modified(&workspace.join("src").join(name), hour_ago);
7877 }
7878 let locked = workspace.join("src/locked");
7880 fs::write(&locked, "read only").unwrap();
7881 let mut permissions = fs::metadata(&locked).unwrap().permissions();
7882 permissions.set_readonly(true);
7883 fs::set_permissions(&locked, permissions).unwrap();
7884 fs::create_dir_all(copy.join("src/was_dir/inner")).unwrap();
7885 fs::write(copy.join("src/same"), "SOURCE").unwrap();
7887 fs::write(workspace.join("src/copied"), "as it is").unwrap();
7889 fs::write(copy.join("src/copied"), "as it is").unwrap();
7890 let long_ago = hour_ago - Duration::from_secs(7200);
7891 set_modified(©.join("src/copied"), long_ago);
7892 let elsewhere = dir.join("elsewhere");
7894 fs::create_dir_all(&elsewhere).unwrap();
7895 std::os::unix::fs::symlink(&elsewhere, copy.join("linked")).unwrap();
7896 fs::create_dir_all(workspace.join("linked/deep")).unwrap();
7897 fs::write(workspace.join("linked/deep/z"), "z").unwrap();
7898 fs::write(copy.join("src/longer"), "SOURCE+").unwrap();
7899 fs::write(copy.join("src/newer"), "SOURCE").unwrap();
7900 set_modified(©.join("src/newer"), hour_ago - Duration::from_secs(60));
7901 let outside = dir.join("outside");
7903 fs::write(&outside, "keep").unwrap();
7904 std::os::unix::fs::symlink(&outside, copy.join("src/was_link")).unwrap();
7905 let twin = dir.join("twin");
7907 fs::write(&twin, "source").unwrap();
7908 std::os::unix::fs::symlink(&twin, copy.join("src/twin_link")).unwrap();
7909 fs::write(copy.join("src/shorter"), "sour").unwrap();
7911 std::os::unix::fs::symlink("abcdef", copy.join("src/short_link")).unwrap();
7913 fs::create_dir_all(copy.join("old/deep")).unwrap();
7915 fs::write(copy.join("old/deep/x"), "x").unwrap();
7916 fs::create_dir_all(workspace.join("keep/deep")).unwrap();
7917 fs::write(workspace.join("keep/deep/y"), "y").unwrap();
7918
7919 copy_run(&dir, &[], true);
7920 let read = |name: &str| fs::read_to_string(copy.join(name)).unwrap();
7921 assert_eq!(read("src/locked"), "read only");
7922 assert_eq!(read("src/copied"), "as it is");
7923 assert_eq!(
7924 fs::metadata(copy.join("src/copied"))
7925 .unwrap()
7926 .modified()
7927 .unwrap(),
7928 long_ago
7929 );
7930 assert_eq!(read("linked/deep/z"), "z");
7931 assert!(fs::symlink_metadata(copy.join("linked")).unwrap().is_dir());
7932 assert_eq!(
7933 fs::read_dir(&elsewhere).unwrap().count(),
7934 0,
7935 "nothing written through"
7936 );
7937 for name in [
7938 "src/same",
7939 "src/longer",
7940 "src/newer",
7941 "src/was_dir",
7942 "src/was_link",
7943 "src/short_link",
7944 "src/twin_link",
7945 "src/shorter",
7946 ] {
7947 assert_eq!(read(name), "source", "{name}");
7948 assert!(
7949 fs::symlink_metadata(copy.join(name)).unwrap().is_file(),
7950 "{name}"
7951 );
7952 }
7953 assert!(
7954 fs::symlink_metadata(copy.join("src/was_link"))
7955 .unwrap()
7956 .is_file()
7957 );
7958 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7959 assert!(!copy.join("old").exists());
7960 assert_eq!(read("keep/deep/y"), "y");
7961 fs::remove_dir_all(&dir).unwrap();
7962 }
7963 #[test]
7964 fn a_finding_keeps_its_number_when_the_one_before_it_is_closed() {
7965 let source = "impl S {\n fn f(a: u8, b: u8) -> u8 {\n let x = if a > b { 1 } else { 0 };\n let y = if a > b { 2 } else { 0 };\n x + y\n }\n}\nfn g(a: u8, b: u8) -> bool {\n a > b\n}\n";
7966 let found = instrument::discover(source, 0).unwrap();
7967 let mut all: Vec<(usize, usize, String)> = found
7968 .sites
7969 .iter()
7970 .map(|site| {
7971 let at = report::location("", site);
7972 (at.line, at.column, at.code)
7973 })
7974 .collect();
7975 all.push(
7976 all.iter()
7977 .find(|(line, _, code)| *line == 3 && code == "a > b")
7978 .unwrap()
7979 .clone(),
7980 );
7981 all.reverse();
7982 let places = [FilePlaces {
7983 display: "src/lib.rs",
7984 source,
7985 lines: &scope::LineIndex::new(source),
7986 places: &all,
7987 }];
7988 let gap = |line: usize, column: usize, file: &str| Finding::InputGap {
7989 at: report::Location {
7990 file: file.to_string(),
7991 line,
7992 column,
7993 code: "a > b".to_string(),
7994 ..report::Location::default()
7995 },
7996 survivors: vec![],
7997 survivor_count: 0,
7998 add_tests: vec![],
7999 observed: None,
8000 verified: true,
8001 };
8002 let name = |finding: &Finding| {
8003 let at = finding.at();
8004 (at.item.clone(), at.id.clone())
8005 };
8006 let mut findings = [
8008 gap(4, 20, "src/lib.rs"),
8009 gap(9, 5, "src/lib.rs"),
8010 gap(9, 5, "src/other.rs"),
8011 gap(5, 9, "src/lib.rs"), ];
8013 name_findings(&mut findings, &places);
8014 assert_eq!(
8015 name(&findings[0]),
8016 (
8017 "S::f".to_string(),
8018 "input_gap|src/lib.rs|S::f|a > b|1".to_string()
8019 )
8020 );
8021 assert_eq!(
8022 name(&findings[1]),
8023 (
8024 "g".to_string(),
8025 "input_gap|src/lib.rs|g|a > b|0".to_string()
8026 )
8027 );
8028 assert_eq!(name(&findings[2]), (String::new(), String::new()));
8030 assert_eq!(
8031 name(&findings[3]),
8032 (
8033 "S::f".to_string(),
8034 "input_gap|src/lib.rs|S::f|a > b|2".to_string()
8035 )
8036 );
8037 }
8038
8039 #[test]
8040 fn an_audit_searches_only_the_jobs_for_its_site() {
8041 let jobs: Vec<_> = [1, 1, 3, 8, 8]
8042 .into_iter()
8043 .map(|site| Job {
8044 site,
8045 mutation: Mutation::Negate,
8046 tests: vec![],
8047 })
8048 .collect();
8049 for (site, range) in [
8050 (0, 0..0),
8051 (1, 0..2),
8052 (2, 2..2),
8053 (3, 2..3),
8054 (4, 3..3),
8055 (8, 3..5),
8056 (9, 5..5),
8057 ] {
8058 let found = jobs_for_site(&jobs, site);
8059 assert_eq!(found, range);
8060 assert_eq!(
8061 found
8062 .clone()
8063 .find(|&index| jobs[index].mutation == Mutation::Negate),
8064 jobs.iter()
8065 .position(|job| job.site == site && job.mutation == Mutation::Negate)
8066 );
8067 }
8068 }
8069
8070 #[test]
8071 fn an_audit_takes_its_sample_evenly_and_the_same_every_time() {
8072 assert_eq!(spread(0, 3), Vec::<usize>::new());
8073 assert_eq!(spread(5, 0), Vec::<usize>::new());
8074 assert_eq!(spread(3, 3), [0, 1, 2]);
8075 assert_eq!(spread(3, 10), [0, 1, 2]);
8076 assert_eq!(spread(10, 1), [0]);
8077 assert_eq!(spread(10, 3), [0, 3, 6]);
8078 assert_eq!(spread(10, 5), [0, 2, 4, 6, 8]);
8079 assert_eq!(spread(4, 3), [0, 1, 2]);
8080 assert_eq!(spread(7, 6), [0, 1, 2, 3, 4, 5]);
8081 }
8082
8083 #[test]
8084 fn a_mutant_of_the_source_is_the_mutation_its_probe_runs() {
8085 assert_ne!(crate::tmt_rt::CANNOT_EVALUATE, 0);
8088 let source = "fn f(a: i32, b: i32, ok: bool, k: Option<i32>, base: O) -> O { \
8089 go(); \
8090 let x = match k { Some(n) if n > 1 => !ok && a < b, _ => -a + b > 0 || ok }; \
8091 for _ in a..b {} for _ in a..=b {} \
8092 O { on: x, ..base } }";
8093 let found = instrument::discover(source, 0).unwrap().sites;
8094 let mut seen = BTreeSet::new();
8095 for site in &found {
8096 for mutant in instrument::source_mutants(site) {
8097 let kind = format!("{:?}", site.kind);
8098 let kind = kind.split([' ', '{', '(']).next().unwrap().to_string();
8099 seen.insert((
8100 kind,
8101 mutant.into.clone(),
8102 format!("{:?}", mutation_of(site, &mutant)),
8103 ));
8104 }
8105 }
8106 let expected = [
8107 ("Arith", "*", "ArithSwap2"),
8108 ("Arith", "-", "ArithSwap"),
8109 ("Arm", "Some(n) if n > 1", "Delete"),
8110 ("Body", "Default::default()", "Delete"),
8111 ("Cmp", "<", "Op(Lt)"),
8112 ("Cmp", "<=", "Op(Le)"),
8113 ("Cmp", "==", "Op(Eq)"),
8114 ("Cmp", ">", "Op(Gt)"),
8115 ("Cmp", ">=", "Op(Ge)"),
8116 ("Field", "on", "Delete"),
8117 ("Guard", "true", "Const(true)"),
8118 ("Logic", "&&", "LogicSwap"),
8119 ("Logic", "||", "LogicSwap"),
8120 ("Neg", "", "Delete"),
8121 ("Not", "", "DropNot"),
8122 ("Range", "..", "RangeEnd"),
8123 ("Range", "..=", "RangeEnd"),
8124 ("Stmt", "", "Delete"),
8125 ];
8126 let like = |source: &str, into: &str| -> Vec<Mutation> {
8129 let sites = instrument::discover(source, 0).unwrap().sites;
8130 let site = sites
8131 .iter()
8132 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
8133 .unwrap();
8134 let mutant = instrument::source_mutants(site)
8135 .into_iter()
8136 .find(|mutant| mutant.into == into)
8137 .unwrap();
8138 mutations_like(site, &mutant, true)
8139 };
8140 use plan::CmpOp::*;
8141 for (op, into, expected) in [
8142 ("==", "!=", vec![Mutation::Op(Ne), Mutation::Negate]),
8143 ("!=", "==", vec![Mutation::Op(Eq), Mutation::Negate]),
8144 ("<=", ">", vec![Mutation::Op(Gt), Mutation::Negate]),
8145 (">=", "<", vec![Mutation::Op(Lt), Mutation::Negate]),
8146 ("<", "<=", vec![Mutation::Op(Le), Mutation::Shift(1)]),
8147 (">", ">=", vec![Mutation::Op(Ge), Mutation::Shift(-1)]),
8148 ("<", "==", vec![Mutation::Op(Eq)]),
8149 ("<", ">", vec![Mutation::Op(Gt)]),
8150 (">", "==", vec![Mutation::Op(Eq)]),
8151 (">", "<", vec![Mutation::Op(Lt)]),
8152 ] {
8153 let source = format!("fn f(a: i32, b: i32) -> bool {{ a {op} b }}");
8154 assert_eq!(like(&source, into), expected, "{op} as {into}");
8155 }
8156 let unordered = |op: &str, into: &str| -> Vec<Mutation> {
8159 let source = format!("fn f(a: f64, b: f64) -> bool {{ a {op} b }}");
8160 let sites = instrument::discover(&source, 0).unwrap().sites;
8161 let site = sites
8162 .iter()
8163 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
8164 .unwrap();
8165 let mutant = instrument::source_mutants(site)
8166 .into_iter()
8167 .find(|mutant| mutant.into == into)
8168 .unwrap();
8169 mutations_like(site, &mutant, false)
8170 };
8171 assert_eq!(unordered(">=", "<"), [Mutation::Op(Lt)]);
8172 assert_eq!(unordered("<=", ">"), [Mutation::Op(Gt)]);
8173 assert_eq!(unordered("==", "!="), [Mutation::Op(Ne), Mutation::Negate]);
8174 for d in -3..=3 {
8176 assert_eq!(
8177 plan::eval_mutated_d(Lt, Mutation::Shift(1), d),
8178 Le.eval_d(d)
8179 );
8180 assert_eq!(
8181 plan::eval_mutated_d(Gt, Mutation::Shift(-1), d),
8182 Ge.eval_d(d)
8183 );
8184 }
8185 let seen: Vec<(&str, &str, &str)> = seen
8186 .iter()
8187 .map(|(kind, into, mutation)| (kind.as_str(), into.as_str(), mutation.as_str()))
8188 .collect();
8189 assert_eq!(seen, expected);
8190 }
8191
8192 #[test]
8193 fn the_mark_of_a_run_is_a_new_file_and_says_one_of_three_things() {
8194 let dir = scratch("unable-mark");
8195 fs::create_dir_all(&dir).unwrap();
8196 let runs = std::sync::atomic::AtomicUsize::new(0);
8197 let name = |n: usize| dir.join(format!("tmt-unable-{}-{n}", std::process::id()));
8198 fs::write(name(0), "not ours").unwrap();
8201 fs::write(name(1), "nor this").unwrap();
8202 let mark = reserve_file(&dir, "unable", &runs).unwrap();
8203 assert_eq!(mark, name(2));
8204 assert!(mark.is_absolute());
8205 assert_eq!(fs::read_to_string(&mark).unwrap(), "");
8206 assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
8207 assert_eq!(fs::read_to_string(name(1)).unwrap(), "nor this");
8208 assert!(!release_mark(&mark).unwrap());
8210 assert!(!mark.exists());
8211 let mark = reserve_file(&dir, "unable", &runs).unwrap();
8213 assert_eq!(mark, name(3));
8214 fs::remove_file(&mark).unwrap();
8215 assert!(release_mark(&mark).unwrap());
8216 let in_the_way = dir.join("a-directory");
8219 fs::create_dir_all(&in_the_way).unwrap();
8220 let refused = format!("{:#}", release_mark(&in_the_way).unwrap_err());
8221 assert!(refused.contains("cannot tell whether"), "{refused}");
8222 assert!(refused.contains("a-directory"), "{refused}");
8223 assert!(in_the_way.is_dir());
8224 let unmade = format!("{:#}", reserve_file(&name(0), "unable", &runs).unwrap_err());
8226 assert!(unmade.contains("creating"), "{unmade}");
8227 assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
8228 fs::remove_dir_all(&dir).unwrap();
8229 }
8230
8231 #[test]
8232 fn the_directory_of_the_marks_is_made_or_used_and_nothing_is_removed_for_it() {
8233 let dir = scratch("marks-dir");
8234 let work = dir.join("work");
8235 assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
8237 assert!(work.join("marks").is_dir());
8238 fs::write(work.join("marks/left-over"), "x").unwrap();
8239 assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
8240 assert_eq!(
8241 fs::read_to_string(work.join("marks/left-over")).unwrap(),
8242 "x"
8243 );
8244 let taken = dir.join("taken");
8246 fs::create_dir_all(&taken).unwrap();
8247 fs::write(taken.join("marks"), "grades of the class").unwrap();
8248 let said = format!("{:#}", marks_dir(&taken).unwrap_err());
8249 assert!(
8250 said.contains("is in the way") && said.contains("marks"),
8251 "{said}"
8252 );
8253 assert_eq!(
8254 fs::read_to_string(taken.join("marks")).unwrap(),
8255 "grades of the class"
8256 );
8257 #[cfg(unix)]
8259 {
8260 let linked = dir.join("linked");
8261 let elsewhere = dir.join("elsewhere");
8262 fs::create_dir_all(&linked).unwrap();
8263 fs::create_dir_all(&elsewhere).unwrap();
8264 std::os::unix::fs::symlink(&elsewhere, linked.join("marks")).unwrap();
8265 assert!(marks_dir(&linked).is_err());
8266 assert!(
8267 fs::symlink_metadata(linked.join("marks"))
8268 .unwrap()
8269 .is_symlink()
8270 );
8271 assert_eq!(fs::read_dir(&elsewhere).unwrap().count(), 0);
8272 }
8273 fs::remove_dir_all(&dir).unwrap();
8274 }
8275
8276 #[test]
8277 fn what_the_runs_left_is_said_only_when_there_was_something() {
8278 assert_eq!(leftover_note(0, 0), None);
8279 assert_eq!(
8280 leftover_note(3, 0).unwrap(),
8281 "stopped 3 processes that the tests had left running after their run"
8282 );
8283 assert_eq!(
8284 leftover_note(0, 2).unwrap(),
8285 "after 2 runs something the tests started may still be running (it could not be \
8286 found or stopped)"
8287 );
8288 let both = leftover_note(1, 1).unwrap();
8289 assert!(both.starts_with("stopped 1 processes") && both.contains("; after 1 runs"));
8290 }
8291
8292 #[test]
8293 fn a_predicted_survivor_is_unstable_only_when_a_re_run_was_found_out() {
8294 let run = |survived: bool, unable: bool, unconfirmed_timeout: bool| JobResult {
8295 first_pass_timeout: unconfirmed_timeout,
8296 unconfirmed_timeout,
8297 survived: survived.then(Vec::new),
8298 timed_out: unconfirmed_timeout,
8299 unable,
8300 };
8301 let passed = || run(true, false, false);
8302 let found_out = || run(false, false, false);
8303 let unable = || run(false, true, false);
8304 let unconfirmed = || run(false, false, true);
8305 let of = |runs: Vec<JobResult>| Prediction::of(runs.iter());
8306 assert_eq!(of(vec![]), Prediction::Confirmed);
8307 assert_eq!(of(vec![passed(), passed()]), Prediction::Confirmed);
8308 assert_eq!(of(vec![passed(), found_out()]), Prediction::Refuted);
8309 assert_eq!(of(vec![found_out(), passed()]), Prediction::Refuted);
8310 assert_eq!(of(vec![unable(), found_out()]), Prediction::Refuted);
8312 assert_eq!(of(vec![found_out(), unconfirmed()]), Prediction::Refuted);
8313 assert_eq!(of(vec![passed(), unable()]), Prediction::Unknown);
8314 assert_eq!(of(vec![unable(), passed()]), Prediction::Unknown);
8315 assert_eq!(of(vec![unconfirmed()]), Prediction::Unknown);
8316 }
8317
8318 #[cfg(unix)]
8319 #[test]
8320 fn a_build_that_failed_is_not_code_the_compiler_refused() {
8321 use std::os::unix::process::ExitStatusExt;
8322 let output = |status: i32, stdout: &str, stderr: &str| std::process::Output {
8323 status: std::process::ExitStatus::from_raw(status),
8324 stdout: stdout.as_bytes().to_vec(),
8325 stderr: stderr.as_bytes().to_vec(),
8326 };
8327 let refusal = r#"{"reason":"compiler-message","message":{"level":"error","message":"mismatched types","rendered":"error: mismatched types","spans":[]}}"#;
8328 let warning = r#"{"reason":"compiler-message","message":{"level":"warning","message":"unused","rendered":"warning: unused","spans":[]}}"#;
8329 assert_eq!(source_build(&output(0, warning, "")), SourceBuild::Built);
8331 assert_eq!(
8332 source_build(&output(101 << 8, refusal, "error: could not compile")),
8333 SourceBuild::Refused
8334 );
8335 let killed = source_build(&output(9, warning, "Compiling x\nlast words"));
8337 assert!(
8338 matches!(&killed, SourceBuild::Failed(why) if why.contains("last words")),
8339 "{killed:?}"
8340 );
8341 let cargo = source_build(&output(
8342 101 << 8,
8343 "",
8344 "error: failed to open lock\nno space left on device",
8345 ));
8346 assert!(
8347 matches!(&cargo, SourceBuild::Failed(why) if why.contains("no space left")),
8348 "{cargo:?}"
8349 );
8350 }
8351
8352 #[test]
8353 fn concurrent_runs_share_the_cores() {
8354 assert_eq!(test_threads(16, 1), 16);
8356 assert_eq!(test_threads(16, 4), 4);
8357 assert_eq!(test_threads(18, 4), 4);
8358 assert_eq!(test_threads(16, 8), 2);
8360 assert_eq!(test_threads(16, 9), 2);
8361 assert_eq!(test_threads(4, 16), 2);
8362 assert_eq!(test_threads(1, 1), 2);
8363 assert_eq!(test_threads(8, 0), 8);
8364 }
8365
8366 #[test]
8367 fn cargo_is_told_the_same_everywhere() {
8368 assert!(CargoConfig::default().flags().is_empty());
8369 let some = CargoConfig {
8370 features: vec!["a".to_string(), "dep/b".to_string()],
8371 no_default_features: true,
8372 ..CargoConfig::default()
8373 };
8374 assert_eq!(
8375 some.flags(),
8376 ["--features", "a,dep/b", "--no-default-features"]
8377 );
8378 let all = CargoConfig {
8379 all_features: true,
8380 locked: true,
8381 ..CargoConfig::default()
8382 };
8383 assert_eq!(all.flags(), ["--all-features", "--locked"]);
8384 }
8385
8386 #[test]
8387 fn source_mutants_are_described_like_the_others() {
8388 let source = "fn f(a: i32, b: i32, k: Option<i32>) -> bool { \
8389 match k { Some(n) if n > 1 => !(a < b) || a + b == 0, _ => -a * b > 1 } }";
8390 let found = instrument::discover(source, 0).unwrap().sites;
8391 let described: Vec<String> = found
8392 .iter()
8393 .flat_map(|site| {
8394 instrument::source_mutants(site)
8395 .into_iter()
8396 .map(|mutant| report::describe(site, mutation_of(site, &mutant)))
8397 })
8398 .collect();
8399 assert_eq!(
8400 described,
8401 [
8402 "the body of `f` replaced by `true`",
8403 "the body of `f` replaced by `false`",
8404 "remove the arm `Some(n) if n > 1 => ..`",
8406 "the guard `n > 1` replaced by `true`",
8407 "`n == 1`",
8408 "`n < 1`",
8409 "`n >= 1`",
8410 "`!(a < b) && a + b == 0`",
8411 "`(a < b)`",
8412 "`a == b`",
8413 "`a > b`",
8414 "`a <= b`",
8415 "`a + b != 0`",
8416 "`a - b`",
8417 "`a * b`",
8418 "`-a * b == 1`",
8419 "`-a * b < 1`",
8420 "`-a * b >= 1`",
8421 "`-a / b`",
8422 "`-a + b`",
8423 "`a`",
8424 ]
8425 );
8426 let source = "fn f(k: K) -> u8 { match k { K::A(n) if n > 1 => 1, K::A(_) => 2 } }";
8428 let found = instrument::discover(source, 0).unwrap().sites;
8429 let guard = found
8430 .iter()
8431 .find(|s| matches!(s.kind, SiteKind::Guard { .. }))
8432 .unwrap();
8433 let described: Vec<String> = instrument::source_mutants(guard)
8434 .iter()
8435 .map(|mutant| report::describe(guard, mutation_of(guard, mutant)))
8436 .collect();
8437 assert_eq!(
8438 described,
8439 [
8440 "the guard `n > 1` replaced by `true`",
8441 "the guard `n > 1` replaced by `false`"
8442 ]
8443 );
8444 }
8445
8446 #[test]
8447 fn dependents_are_found_once_through_a_cycle_that_leaves_the_package_out() {
8448 let package = |name: &str, deps: &[&str]| Package {
8449 name: name.to_string(),
8450 features: BTreeMap::new(),
8451 dependencies: deps
8452 .iter()
8453 .map(|d| Dependency {
8454 name: d.to_string(),
8455 })
8456 .collect(),
8457 manifest_path: PathBuf::new(),
8458 targets: vec![],
8459 };
8460 let packages = [
8463 package("z", &[]),
8464 package("x", &["y", "z"]),
8465 package("y", &["x"]),
8466 ];
8467 assert_eq!(dependents_of("z", &packages), ["x", "y"]);
8468 }
8469
8470 #[test]
8471 fn an_error_is_said_once_and_only_when_it_says_something() {
8472 let stdout = r#"
8473{"reason":"compiler-message","message":{"level":"error","spans":[]}}
8474{"reason":"compiler-message","message":{"level":"error","message":"","rendered":null,"spans":[]}}
8475{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}
8476{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}
8477"#;
8478 assert_eq!(parse_build_output(stdout, &["p"]).diagnostics, ["aborting"]);
8479 }
8480
8481 #[cfg(unix)]
8483 fn script_binary(dir: &Path, body: &str) -> TestBinary {
8484 use std::os::unix::fs::PermissionsExt as _;
8485 let work = dir.join("work");
8486 let exe = work.join("runner");
8487 fs::write(&exe, format!("#!/bin/sh\n{body}\n")).unwrap();
8488 fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
8489 TestBinary {
8490 name: "runner".into(),
8491 cwd: work.join("src"),
8492 marks: marks_dir(&work).unwrap(),
8493 git_ceiling: work,
8494 work_lock: None,
8495 tests: BTreeSet::new(),
8496 runner: Runner::Exe(exe),
8497 baseline: Duration::ZERO,
8498 untraced_baseline: None,
8499 timeout_diagnostic: std::sync::Once::new(),
8500 traced: Duration::ZERO,
8501 timeout: None,
8502 wrapper_grace: Duration::ZERO,
8503 report_slow: false,
8504 filtered_timings: Default::default(),
8505 trace: Trace::default(),
8506 effects_baseline: std::sync::OnceLock::new(),
8507 }
8508 }
8509
8510 #[cfg(unix)]
8512 fn isolated(mut bin: TestBinary) -> TestBinary {
8513 let exe = bin.runner.executable().unwrap().to_path_buf();
8514 bin.runner = Runner::Isolated {
8515 exe,
8516 test: "t".to_string(),
8517 ignored: false,
8518 wrapper: None,
8519 };
8520 bin
8521 }
8522
8523 #[cfg(unix)]
8526 fn ends(pid: u32) -> bool {
8527 let deadline = Instant::now() + Duration::from_secs(10);
8528 loop {
8529 let state = Command::new("ps")
8530 .args(["-o", "stat=", "-p", &pid.to_string()])
8531 .output()
8532 .unwrap();
8533 let state = String::from_utf8_lossy(&state.stdout);
8534 if state.trim().is_empty() || state.trim().starts_with('Z') {
8535 return true;
8536 }
8537 if Instant::now() >= deadline {
8538 let _ = Command::new("kill").args(["-9", &pid.to_string()]).status();
8540 return false;
8541 }
8542 std::thread::sleep(Duration::from_millis(5));
8543 }
8544 }
8545
8546 #[cfg(unix)]
8549 fn nothing_runs(path: &Path) -> bool {
8550 let deadline = Instant::now() + Duration::from_secs(10);
8551 loop {
8552 let processes = Command::new("ps")
8553 .args(["-e", "-o", "args="])
8554 .output()
8555 .unwrap();
8556 let processes = String::from_utf8_lossy(&processes.stdout).into_owned();
8557 if !processes.contains(&*path.to_string_lossy()) {
8558 return true;
8559 }
8560 if Instant::now() >= deadline {
8561 return false;
8562 }
8563 std::thread::sleep(Duration::from_millis(5));
8564 }
8565 }
8566
8567 #[cfg(unix)]
8568 #[test]
8569 fn a_filter_is_timed_only_for_a_slow_libtest_binary_without_a_given_limit() {
8570 let dir = scratch("unmeasured-filters");
8571 let slow = Duration::from_secs(70);
8572 let fast = ["fast".to_string()];
8573 let all = ["fast".to_string(), "slow".to_string()];
8574 let binary = |baseline, timeout| {
8575 let mut bin = script_binary(&dir, "exit 0");
8576 bin.tests = all.iter().cloned().collect();
8577 bin.baseline = baseline;
8578 bin.timeout = timeout;
8579 bin
8580 };
8581 let timed = |bin: &TestBinary| bin.filtered_timings.lock().unwrap().len();
8582
8583 let given = binary(slow, Some(Duration::from_secs(8)));
8585 assert_eq!(
8586 given.filtered_limit(Some(&fast), false),
8587 Duration::from_secs(8)
8588 );
8589 assert_eq!(timed(&given), 0);
8590 let quick = binary(Duration::from_secs(1), None);
8592 assert_eq!(
8593 quick.filtered_limit(Some(&fast), false),
8594 Duration::from_secs(10)
8595 );
8596 assert_eq!(timed(&quick), 0);
8597 let at_the_threshold = binary(SLOW_TRACE, None);
8599 at_the_threshold.filtered_limit(Some(&fast), false);
8600 assert_eq!(timed(&at_the_threshold), 1);
8601 let one_by_one = isolated(binary(slow, None));
8603 assert_eq!(
8604 one_by_one.filtered_limit(Some(&fast), false),
8605 Duration::from_secs(355)
8606 );
8607 assert_eq!(timed(&one_by_one), 0);
8608 let whole = binary(slow, None);
8610 for filter in [&[][..], &all[..]] {
8611 assert_eq!(
8612 whole.filtered_limit(Some(filter), false),
8613 Duration::from_secs(355),
8614 "{filter:?}"
8615 );
8616 }
8617 assert_eq!(timed(&whole), 0);
8618 fs::remove_dir_all(dir).unwrap();
8619 }
8620
8621 #[test]
8622 fn a_command_in_the_copy_cannot_reach_the_repository_around_it() {
8623 use std::ffi::OsStr;
8624 let mut command = Command::new("git");
8625 isolate_copy_command(&mut command, Path::new("/work"));
8626 let set: Vec<_> = command.get_envs().collect();
8627 for removed in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"] {
8628 assert!(set.contains(&(OsStr::new(removed), None)), "{removed}");
8629 }
8630 assert!(set.contains(&(
8631 OsStr::new("GIT_CEILING_DIRECTORIES"),
8632 Some(OsStr::new("/work"))
8633 )));
8634 }
8635
8636 #[cfg(unix)]
8637 #[test]
8638 fn the_tests_are_given_the_mark_the_mutant_and_the_fence_for_git() {
8639 let dir = scratch("run-environment");
8640 let work = dir.join("work");
8641 let bin = script_binary(
8642 &dir,
8643 &format!(
8644 "[ -f \"$TMT_UNABLE\" ] && [ \"$TMT_MUTANT\" = 7 ] \
8645 && [ \"$GIT_CEILING_DIRECTORIES\" = '{}' ]",
8646 work.display()
8647 ),
8648 );
8649 assert_eq!(
8650 run_binary(
8651 &bin,
8652 None,
8653 &[("TMT_MUTANT", "7")],
8654 Duration::from_secs(60),
8655 RunOutput::Quiet,
8656 1
8657 )
8658 .unwrap(),
8659 Outcome::Pass
8660 );
8661 fs::remove_dir_all(dir).unwrap();
8662 }
8663
8664 #[cfg(unix)]
8665 #[test]
8666 fn a_failure_line_ends_the_run_before_the_tests_do() {
8667 let dir = scratch("first-failure");
8668 let bin = script_binary(
8671 &dir,
8672 "sleep 30 &\necho $! > child.pid\necho 'test tests::a ... FAILED'\nwait",
8673 );
8674 let outcome = run_binary(
8675 &bin,
8676 None,
8677 &[],
8678 Duration::from_secs(20),
8679 RunOutput::FirstFailure,
8680 1,
8681 );
8682 let pid = fs::read_to_string(bin.cwd.join("child.pid"))
8683 .unwrap()
8684 .trim()
8685 .parse()
8686 .unwrap();
8687 let stopped = ends(pid);
8688 fs::remove_dir_all(dir).unwrap();
8689 assert_eq!(outcome.unwrap(), Outcome::Fail);
8690 assert!(stopped, "the failed run left a process behind");
8691 }
8692
8693 #[cfg(unix)]
8694 #[test]
8695 fn failure_lines_are_found_in_output_that_comes_in_pieces() {
8696 use std::io::Write as _;
8697 let dir = scratch("failure-output");
8698 let path = dir.join("output");
8699 let mut written = fs::File::create(&path).unwrap();
8700 let mut output = FailureOutput::new(fs::File::open(&path).unwrap());
8701 let mut next = |text: &str| {
8702 written.write_all(text.as_bytes()).unwrap();
8703 output.failed().unwrap()
8704 };
8705 assert!(!next(""));
8706 assert!(!next("running 2 tests\ntest tests::a ... ok\n"));
8707 assert!(!next("test tests::b ... FA"));
8709 assert!(next("ILED\n"));
8710 let long = format!("test {} ... FAILED\n", "x".repeat(8 * 1024));
8713 assert!(!next(&long));
8714 assert!(!next("test tests::c ... ok\n"));
8715 assert!(next("test tests::d ... FAILED\n"));
8716 assert!(next(
8718 "noise\ntest tests::e ... FAILED\ntest tests::f ... ok\n"
8719 ));
8720
8721 let longest = format!("test {} ... FAILED\n", "x".repeat(8 * 1024 - 17));
8723 assert_eq!(longest.len(), 8 * 1024);
8724 for (pieces, found) in [(vec![&longest[..]], true), (vec!["t", &longest[1..]], true)] {
8725 let path = dir.join("longest");
8726 let mut written = fs::File::create(&path).unwrap();
8727 let mut output = FailureOutput::new(fs::File::open(&path).unwrap());
8728 let mut last = false;
8729 for piece in pieces {
8730 written.write_all(piece.as_bytes()).unwrap();
8731 last = output.failed().unwrap();
8732 }
8733 assert_eq!(last, found);
8734 }
8735 let over = format!("test {} ... FAILED\n", "x".repeat(8 * 1024 - 16));
8736 assert_eq!(over.len(), 8 * 1024 + 1);
8737 let path = dir.join("over");
8738 let mut written = fs::File::create(&path).unwrap();
8739 let mut output = FailureOutput::new(fs::File::open(&path).unwrap());
8740 written.write_all(b"t").unwrap();
8741 assert!(!output.failed().unwrap());
8742 written.write_all(&over.as_bytes()[1..]).unwrap();
8743 assert!(!output.failed().unwrap());
8744 fs::remove_dir_all(dir).unwrap();
8745 }
8746
8747 #[cfg(unix)]
8748 #[test]
8749 fn output_nobody_reads_is_discarded() {
8750 let dir = scratch("discarded-output");
8751 let nowhere = "[ /dev/stdout -ef /dev/null ] && [ /dev/stderr -ef /dev/null ]";
8752 let run = |bin: &TestBinary, output| {
8753 run_binary(bin, None, &[], Duration::from_secs(60), output, 1).unwrap()
8754 };
8755 let quiet = script_binary(&dir, nowhere);
8757 assert_eq!(run(&quiet, RunOutput::Quiet), Outcome::Pass);
8758 let one_by_one = isolated(script_binary(
8762 &dir,
8763 &format!(
8764 "{nowhere} && [ \"$*\" = '--exact --test-threads=1 t' ] && [ \"$TMT_TEST\" = t ]"
8765 ),
8766 ));
8767 assert_eq!(run(&one_by_one, RunOutput::FirstFailure), Outcome::Pass);
8768 let watched = script_binary(
8770 &dir,
8771 "[ ! /dev/stdout -ef /dev/null ] && [ /dev/stderr -ef /dev/null ]",
8772 );
8773 assert_eq!(run(&watched, RunOutput::FirstFailure), Outcome::Pass);
8774 fs::remove_dir_all(dir).unwrap();
8775 }
8776
8777 #[cfg(unix)]
8778 #[test]
8779 fn what_a_finished_run_left_running_is_stopped() {
8780 let left_running = "sleep 30 &\necho $! > child.pid";
8781 let check = |name: &str, one_by_one: bool, output| {
8782 let dir = scratch(name);
8783 let mut bin = script_binary(&dir, left_running);
8784 if one_by_one {
8785 bin = isolated(bin);
8786 }
8787 let outcome = run_binary(&bin, None, &[], Duration::from_secs(60), output, 1);
8788 let pid = fs::read_to_string(bin.cwd.join("child.pid"))
8789 .unwrap()
8790 .trim()
8791 .parse()
8792 .unwrap();
8793 let stopped = ends(pid);
8794 fs::remove_dir_all(dir).unwrap();
8795 assert_eq!(outcome.unwrap(), Outcome::Pass, "{name}");
8796 assert!(stopped, "{name}: the run left a process behind");
8797 };
8798 check("left-running-watched", false, RunOutput::FirstFailure);
8799 check("left-running-isolated", true, RunOutput::Quiet);
8800 }
8801
8802 #[cfg(unix)]
8803 #[test]
8804 fn tests_that_do_not_end_in_time_are_stopped_as_a_timeout() {
8805 let dir = scratch("run-timeout");
8806 let bin = script_binary(&dir, "sleep 20");
8807 let outcome = run_binary(
8808 &bin,
8809 None,
8810 &[],
8811 Duration::from_millis(100),
8812 RunOutput::Quiet,
8813 1,
8814 );
8815 let stopped = nothing_runs(bin.runner.executable().unwrap());
8817 fs::remove_dir_all(dir).unwrap();
8818 assert_eq!(outcome.unwrap(), Outcome::Timeout);
8819 assert!(stopped, "the tests went on after the timeout");
8820 }
8821
8822 #[cfg(unix)]
8823 #[test]
8824 fn stopping_nextest_asks_first_and_takes_the_answer() {
8825 use std::io::Read as _;
8826 use std::os::unix::process::CommandExt as _;
8827
8828 let mut child = Command::new("sh")
8830 .args(["-c", "trap 'exit 7' TERM; printf X; sleep 60; exit 3"])
8831 .process_group(0)
8832 .stdout(Stdio::piped())
8833 .spawn()
8834 .unwrap();
8835 child.stdout.take().unwrap().read_exact(&mut [0]).unwrap();
8836
8837 let grace = Duration::from_secs(30);
8838 let started = Instant::now();
8839 stop_nextest(&mut child, grace);
8840 let status = child.try_wait().unwrap().expect("runner was reaped");
8841 assert_eq!(status.code(), Some(7));
8844 assert!(started.elapsed() < grace);
8845 }
8846
8847 #[cfg(unix)]
8848 #[test]
8849 fn stopping_nextest_stops_the_groups_its_tests_run_in() {
8850 use std::io::BufRead as _;
8851 use std::os::unix::process::CommandExt as _;
8852
8853 let dir = scratch("nextest-groups");
8856 let source = dir.join("runner.rs");
8857 let exe = dir.join("runner");
8858 fs::write(
8859 &source,
8860 r#"
8861use std::os::unix::process::CommandExt;
8862extern "C" {
8863 fn signal(signal: i32, handler: usize) -> usize;
8864}
8865fn main() {
8866 // Ignored (SIG_IGN), which what is started from here inherits.
8867 unsafe { signal(15, 1) };
8868 let test = std::process::Command::new("sleep").arg("60").process_group(0).spawn().unwrap();
8869 println!("{}", test.id());
8870 std::thread::sleep(std::time::Duration::from_secs(60));
8871}
8872"#,
8873 )
8874 .unwrap();
8875 let output = Command::new("rustc")
8876 .arg(&source)
8877 .arg("-o")
8878 .arg(&exe)
8879 .output()
8880 .unwrap();
8881 assert!(
8882 output.status.success(),
8883 "{}",
8884 String::from_utf8_lossy(&output.stderr)
8885 );
8886 let mut child = Command::new(&exe)
8887 .process_group(0)
8888 .stdout(Stdio::piped())
8889 .spawn()
8890 .unwrap();
8891 let mut line = String::new();
8892 std::io::BufReader::new(child.stdout.take().unwrap())
8893 .read_line(&mut line)
8894 .unwrap();
8895 let test: u32 = line.trim().parse().unwrap();
8896
8897 stop_nextest(&mut child, Duration::from_millis(10));
8898 let reaped = child.try_wait().unwrap();
8899 let stopped = ends(test);
8900 fs::remove_dir_all(dir).unwrap();
8901 assert!(reaped.is_some(), "runner was not reaped");
8902 assert!(stopped, "the group of the test was left running");
8903 }
8904
8905 #[cfg(unix)]
8906 fn process(pid: u32, parent: u32, group: u32, started: &str) -> TestProcess {
8907 TestProcess {
8908 pid,
8909 parent,
8910 group,
8911 started: started.to_string(),
8912 }
8913 }
8914
8915 #[cfg(unix)]
8916 #[test]
8917 fn the_processes_of_a_runner_are_its_descendants_in_groups_they_lead() {
8918 let table = || {
8919 vec![
8920 process(30, 20, 30, "t"),
8922 process(20, 10, 10, "t"),
8923 process(10, 1, 10, "t"),
8924 process(40, 10, 77, "t"),
8926 process(77, 1, 77, "t"),
8927 process(50, 1, 10, "t"),
8929 process(60, 1, 60, "t"),
8930 ]
8931 };
8932 assert_eq!(
8933 owned_among(table(), 10),
8934 [
8935 process(30, 20, 30, "t"),
8936 process(20, 10, 10, "t"),
8937 process(10, 1, 10, "t")
8938 ]
8939 );
8940 assert!(owned_among(table(), 11).is_empty());
8942 }
8943
8944 #[cfg(unix)]
8945 #[test]
8946 fn a_group_survives_only_through_the_very_process_seen_in_it() {
8947 let owned = [process(10, 1, 10, "a"), process(30, 10, 30, "b")];
8948 let surviving = |current: &[TestProcess]| surviving_groups(&owned, current);
8949 assert_eq!(
8950 surviving(&[
8951 process(10, 1, 10, "a"),
8952 process(30, 1, 30, "b"),
8953 process(60, 1, 60, "a")
8954 ]),
8955 BTreeSet::from([10, 30])
8956 );
8957 assert_eq!(surviving(&[process(10, 1, 10, "later")]), BTreeSet::new());
8959 assert_eq!(surviving(&[process(30, 1, 99, "b")]), BTreeSet::new());
8961 assert_eq!(surviving(&[process(31, 1, 30, "b")]), BTreeSet::new());
8963 }
8964
8965 #[test]
8966 fn a_working_directory_that_cannot_be_inspected_is_not_created_over() {
8967 let dir = scratch("marks-below-a-file");
8968 let file = dir.join("file");
8969 fs::write(&file, "").unwrap();
8970 let error = work_directory(&file, "marks").unwrap_err();
8971 assert!(error.to_string().starts_with("inspecting "), "{error:#}");
8972 fs::remove_dir_all(dir).unwrap();
8973 }
8974
8975 #[test]
8976 fn an_error_is_blamed_on_the_file_it_names() {
8977 let copy = Path::new("/work");
8978 let make = |name: &str, source: &str, first_id| {
8979 let sites = instrument::discover(source, first_id).unwrap().sites;
8980 let rendered = instrument::render(source, &sites, &|_| true);
8981 SourceFile {
8982 display: name.to_string(),
8983 path: copy.join(name),
8984 owners: BTreeSet::new(),
8985 lines: scope::LineIndex::new(source),
8986 original: source.to_string(),
8987 places: vec![],
8988 sites,
8989 rebuild_sites: vec![],
8990 rendered: Some(rendered),
8991 }
8992 };
8993 let files = [
8994 make("first.rs", "pub fn f(n: u32) -> bool { n >= 4 }", 0),
8995 make("second.rs", "pub fn g(a: u8, b: u8) -> bool { a < b }", 100),
8996 ];
8997 let rendered = files[1].rendered.as_ref().unwrap();
8998 let probe = rendered.text.find("__tmt_rt::").unwrap();
8999 let blamed = rendered.inserted_by(probe).unwrap();
9000 assert!(blamed >= 100, "{blamed}");
9001 let error = CompileError {
9002 primary: vec![ErrorSpan {
9003 file: "second.rs".to_string(),
9004 byte_start: probe,
9005 line: 1,
9006 }],
9007 secondary: vec![],
9008 rendered: String::new(),
9009 };
9010 assert_eq!(blame_error(&error, &files, copy, &HashSet::new()), [blamed]);
9011 }
9012
9013 #[test]
9014 fn modules_are_followed_to_files_that_exist_in_the_copy() {
9015 let scratch = scratch("module-files");
9016 let copy = scratch.join("work/src");
9017 let library = copy.join("lib.rs");
9018 let directory_module = copy.join("nested/mod.rs");
9019 let outside = scratch.join("work/outside.rs");
9020 let sources = BTreeMap::from([
9021 (
9022 library.clone(),
9023 r#"mod nested; #[path = "../outside.rs"] mod outside;"#,
9024 ),
9025 (directory_module.clone(), "fn nested() {}"),
9026 (outside.clone(), "fn outside() {}"),
9027 ]);
9028 for path in sources.keys() {
9029 fs::create_dir_all(path.parent().unwrap()).unwrap();
9030 fs::File::create(path).unwrap();
9031 }
9032 let graph = source_graph([(library.clone(), true)], ©, |path| {
9033 Ok(sources.get(path).map(|source| (*source).to_string()))
9034 })
9035 .unwrap();
9036 fs::remove_dir_all(scratch).unwrap();
9037 assert_eq!(
9040 graph.keys().collect::<Vec<_>>(),
9041 [&library, &directory_module]
9042 );
9043 }
9044
9045 #[test]
9046 fn an_empty_directory_the_run_asked_for_is_not_pruned() {
9047 let dir = scratch("prune-kept-directory");
9048 let copy = dir.join("work/src");
9049 fs::create_dir(copy.join("fixture")).unwrap();
9050 fs::create_dir(copy.join("stale")).unwrap();
9051 let state = WorkCopy::open(&dir.join("work"), ©);
9052 state.kept.borrow_mut().insert(copy.join("fixture"));
9054 prune(©, &state).unwrap();
9055 assert!(copy.join("fixture").is_dir());
9056 assert!(!copy.join("stale").exists());
9057 fs::remove_dir_all(dir).unwrap();
9058 }
9059
9060 #[test]
9061 fn pool_with_one_worker_runs_nothing_after_the_first_error() {
9062 use std::sync::atomic::{AtomicUsize, Ordering};
9063 let calls = AtomicUsize::new(0);
9064 let failed = run_pool(3, 1, |index| {
9065 calls.fetch_add(1, Ordering::SeqCst);
9066 if index == 0 {
9067 Err(anyhow!("job {index} broke"))
9068 } else {
9069 Ok(index)
9070 }
9071 });
9072 assert_eq!(failed.unwrap_err().to_string(), "job 0 broke");
9073 assert_eq!(calls.load(Ordering::SeqCst), 1);
9074 }
9075
9076 #[test]
9077 fn a_checkpoint_gets_every_verdict_once_it_is_final() {
9078 use std::sync::atomic::{AtomicUsize, Ordering};
9079 let dir = scratch("checkpointed-verdicts");
9080 let keys = || vec!["first".to_string(), "second".to_string()];
9081 for serial in [false, true] {
9082 let checkpoint = Checkpoint::open(&dir.join(format!("checkpoint-{serial}"))).unwrap();
9083 let runs = AtomicUsize::new(0);
9084 let run = |index: usize, sharing: usize| {
9086 runs.fetch_add(1, Ordering::SeqCst);
9087 let timed_out = index == 0 && sharing > 1;
9088 Ok(JobResult {
9089 first_pass_timeout: false,
9090 unconfirmed_timeout: false,
9091 survived: (!timed_out).then(|| vec![index.to_string()]),
9092 timed_out,
9093 unable: false,
9094 })
9095 };
9096 checkpoint.start("campaign", serde_json::json!({})).unwrap();
9097 let phase = checkpoint.begin("mutants", "context", keys()).unwrap();
9098 let results = evaluate_jobs(2, 2, serial, false, "test", Some(&phase), &run).unwrap();
9101 assert_eq!(runs.load(Ordering::SeqCst), if serial { 3 } else { 2 });
9102 assert_eq!(results[0].unconfirmed_timeout, !serial);
9103 assert_eq!(results[0].survived.is_some(), serial);
9104 checkpoint.finish().unwrap();
9106
9107 checkpoint.start("campaign", serde_json::json!({})).unwrap();
9109 let phase = checkpoint.begin("mutants", "context", keys()).unwrap();
9110 let again = evaluate_jobs(2, 2, serial, false, "test", Some(&phase), &run).unwrap();
9111 assert_eq!(again, results);
9112 assert_eq!(runs.load(Ordering::SeqCst), if serial { 3 } else { 2 });
9113 checkpoint.finish().unwrap();
9114 }
9115 fs::remove_dir_all(dir).unwrap();
9116 }
9117}