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, progress, 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 message: Option<Diagnostic>,
298}
299
300#[derive(Deserialize)]
301struct ArtifactTarget {
302 name: String,
303 kind: Vec<String>,
304 src_path: Option<PathBuf>,
305}
306
307#[derive(Deserialize)]
308struct Profile {
309 test: bool,
310}
311
312#[derive(Deserialize)]
313struct Diagnostic {
314 level: String,
315 rendered: Option<String>,
316 message: Option<String>,
317 #[serde(default)]
318 spans: Vec<DiagnosticSpan>,
319}
320
321#[derive(Deserialize)]
322struct DiagnosticSpan {
323 file_name: String,
324 byte_start: usize,
325 line_start: usize,
326 is_primary: bool,
327}
328
329#[derive(Debug, PartialEq, Clone)]
330struct ErrorSpan {
331 file: String,
332 byte_start: usize,
333 line: usize,
334}
335
336#[derive(Debug, PartialEq)]
339struct CompileError {
340 primary: Vec<ErrorSpan>,
341 secondary: Vec<ErrorSpan>,
342 rendered: String,
343}
344
345#[derive(Debug, Default, PartialEq)]
346struct BuildOutput {
347 test_binaries: Vec<(String, PathBuf, String, Vec<String>)>,
349 errors: Vec<CompileError>,
350 diagnostics: Vec<String>,
351 build_scripts: Vec<serde_json::Value>,
352 artifacts: Vec<(PathBuf, Vec<PathBuf>)>,
353}
354
355#[derive(Debug, PartialEq)]
357enum SourceBuild {
358 Built,
359 Refused,
361 Failed(String),
365}
366
367fn source_build(output: &std::process::Output) -> SourceBuild {
368 if output.status.success() {
369 return SourceBuild::Built;
370 }
371 let refused = !parse_build_output(&String::from_utf8_lossy(&output.stdout), &[])
372 .diagnostics
373 .is_empty();
374 if refused {
375 return SourceBuild::Refused;
376 }
377 let said = String::from_utf8_lossy(&output.stderr);
378 let last: Vec<&str> = said.lines().rev().take(3).collect();
379 let last: Vec<&str> = last.into_iter().rev().collect();
380 SourceBuild::Failed(format!("{} ({})", last.join(" / "), output.status))
381}
382
383fn dependents_of(package: &str, packages: &[Package]) -> Vec<String> {
385 let mut reverse = BTreeMap::<&str, Vec<&str>>::new();
386 for other in packages {
387 for dependency in &other.dependencies {
388 reverse
389 .entry(&dependency.name)
390 .or_default()
391 .push(&other.name);
392 }
393 }
394 let mut found = BTreeSet::new();
395 let mut frontier = vec![package];
396 while let Some(current) = frontier.pop() {
397 if let Some(next) = reverse.get(current) {
398 for &other in next {
399 if other != package && found.insert(other) {
400 frontier.push(other);
401 }
402 }
403 }
404 }
405 found.into_iter().map(str::to_owned).collect()
406}
407
408fn is_package(id: &str, name: &str) -> bool {
411 let (path, fragment) = id.split_once('#').unwrap_or((id, ""));
412 fragment.split('@').next() == Some(name)
413 || path.rsplit('/').next() == Some(name)
414 || id.split(' ').next() == Some(name)
415}
416
417fn parse_build_output(stdout: &str, packages: &[&str]) -> BuildOutput {
418 let mut out = BuildOutput::default();
419 for line in stdout.lines() {
420 let Ok(msg) = serde_json::from_str::<CargoMessage>(line) else {
421 continue;
422 };
423 match msg.reason.as_str() {
424 "compiler-artifact" => {
425 let Some(target) = msg.target else { continue };
426 if let Some(path) = target.src_path {
427 out.artifacts.push((normalize(&path), msg.filenames));
428 }
429 if let (Some(exe), Some(profile), Some(id)) =
430 (msg.executable, msg.profile, msg.package_id.as_deref())
431 && profile.test
432 && let Some(package) = packages.iter().find(|name| is_package(id, name))
433 {
434 out.test_binaries
435 .push((target.name, exe, package.to_string(), target.kind));
436 }
437 }
438 "build-script-executed" => {
439 if let Ok(script) = serde_json::from_str(line) {
440 out.build_scripts.push(script);
441 }
442 }
443 "compiler-message" => {
444 let Some(diag) = msg.message else { continue };
445 if diag.level != "error" {
446 continue;
447 }
448 let rendered = diag.rendered.or(diag.message).unwrap_or_default();
449 if !rendered.is_empty() && !out.diagnostics.contains(&rendered) {
450 out.diagnostics.push(rendered.clone());
451 }
452 let span = |s: &DiagnosticSpan| ErrorSpan {
453 file: s.file_name.clone(),
454 byte_start: s.byte_start,
455 line: s.line_start,
456 };
457 let error = CompileError {
458 primary: diag
459 .spans
460 .iter()
461 .filter(|s| s.is_primary)
462 .map(span)
463 .collect(),
464 secondary: diag
465 .spans
466 .iter()
467 .filter(|s| !s.is_primary)
468 .map(span)
469 .collect(),
470 rendered,
471 };
472 if !error.primary.is_empty() && !out.errors.contains(&error) {
475 out.errors.push(error);
476 }
477 }
478 _ => {}
479 }
480 }
481 out.test_binaries.sort_by(|left, right| {
482 (&left.2, &left.3, &left.0, &left.1).cmp(&(&right.2, &right.3, &right.0, &right.1))
483 });
484 out
485}
486
487fn dependency_file(artifact: &Path) -> Option<String> {
489 let stem = artifact.file_stem()?.to_str()?;
490 let unprefixed = match artifact.extension().and_then(|ext| ext.to_str()) {
491 Some("a" | "so" | "dylib" | "rlib" | "rmeta") => stem.strip_prefix("lib"),
492 _ => None,
493 };
494 unprefixed
495 .and_then(|stem| fs::read_to_string(artifact.with_file_name(format!("{stem}.d"))).ok())
496 .or_else(|| fs::read_to_string(artifact.with_extension("d")).ok())
497}
498
499fn dep_inputs(text: &str, copy: &Path) -> BTreeSet<PathBuf> {
500 text.lines()
503 .filter_map(|line| line.strip_suffix(':'))
504 .map(|name| name.replace("\\ ", " ").replace("\\#", "#"))
505 .map(|name| normalize(©.join(name)))
506 .collect()
507}
508
509fn directory_entries(path: &Path) -> impl Iterator<Item = PathBuf> + use<> {
510 fs::read_dir(path)
511 .into_iter()
512 .flatten()
513 .filter_map(|entry| entry.ok().map(|entry| entry.path()))
514}
515
516fn same_binary(a: &Path, b: &Path) -> Option<bool> {
517 let (a, b) = (fs::File::open(a).ok()?, fs::File::open(b).ok()?);
518 let (left, right) = (a.metadata().ok()?, b.metadata().ok()?);
519 if !left.is_file() || !right.is_file() || left.len() != right.len() {
520 return Some(false);
521 }
522 #[cfg(unix)]
523 {
524 use std::os::unix::fs::MetadataExt;
525 if left.ino() == right.ino() && left.dev() == right.dev() {
526 return Some(true);
527 }
528 }
529 compare_streams(a, b).ok()
530}
531
532fn compare_streams(a: impl std::io::Read, b: impl std::io::Read) -> std::io::Result<bool> {
533 use std::io::{BufRead, BufReader, ErrorKind};
534 const BUFFER_BYTES: usize = 64 * 1024;
535 let mut a = BufReader::with_capacity(BUFFER_BYTES, a);
536 let mut b = BufReader::with_capacity(BUFFER_BYTES, b);
537 loop {
538 let left = match a.fill_buf() {
539 Ok(bytes) => bytes,
540 Err(error) if error.kind() == ErrorKind::Interrupted => continue,
541 Err(error) => return Err(error),
542 };
543 let right = match b.fill_buf() {
544 Ok(bytes) => bytes,
545 Err(error) if error.kind() == ErrorKind::Interrupted => continue,
546 Err(error) => return Err(error),
547 };
548 let count = left.len().min(right.len());
549 if count == 0 {
550 return Ok(left.is_empty() && right.is_empty());
551 }
552 if left[..count] != right[..count] {
553 return Ok(false);
554 }
555 a.consume(count);
556 b.consume(count);
557 }
558}
559
560fn artifact_inputs(artifact: &Path, root: &Path, copy: &Path) -> BTreeSet<PathBuf> {
561 let read = |binary: &Path| {
562 dependency_file(binary)
563 .map(|text| dep_inputs(&text, copy))
564 .filter(|inputs| inputs.contains(root))
565 };
566 if let Some(inputs) = read(artifact) {
567 return inputs;
568 }
569 let Some((profile, stem)) = artifact
572 .parent()
573 .zip(artifact.file_stem().and_then(|s| s.to_str()))
574 else {
575 return BTreeSet::new();
576 };
577 let crate_stem = stem.replace('-', "_");
578 let hashed = format!("{crate_stem}-");
579 let old = directory_entries(&profile.join("deps")).filter(|path| {
580 path.extension() == artifact.extension()
581 && path
582 .file_stem()
583 .and_then(|s| s.to_str())
584 .is_some_and(|name| name.starts_with(&hashed))
585 });
586 let mut private_name = std::ffi::OsString::from(crate_stem);
587 if let Some(extension) = artifact.extension() {
588 private_name.push(".");
589 private_name.push(extension);
590 }
591 let new = directory_entries(&profile.join("build"))
592 .flat_map(|package| directory_entries(&package))
593 .map(|unit| unit.join("out").join(&private_name));
594 old.chain(new)
597 .filter_map(|path| {
598 let inputs = read(&path)?;
599 (same_binary(artifact, &path) == Some(true)).then_some(inputs)
600 })
601 .reduce(|left, right| left.intersection(&right).cloned().collect())
602 .unwrap_or_default()
603}
604
605#[derive(Default)]
606struct BuiltSources(BTreeMap<PathBuf, BTreeSet<PathBuf>>);
607
608impl BuiltSources {
609 fn from_artifacts(artifacts: &[(PathBuf, Vec<PathBuf>)], copy: &Path) -> Self {
610 let mut built = Self::default();
611 for (root, artifacts) in artifacts {
612 if !root.starts_with(copy) {
613 continue;
614 }
615 let files = built.0.entry(root.clone()).or_default();
616 files.insert(root.clone());
617 if let Some(inputs) = artifacts
618 .iter()
619 .map(|file| artifact_inputs(file, root, copy))
620 .find(|inputs| !inputs.is_empty())
621 {
622 files.extend(inputs);
623 }
624 }
625 built
626 }
627
628 fn contains(&self, source: &SourceFile) -> bool {
629 source.owners.iter().any(|root| {
630 self.0
631 .get(root)
632 .is_some_and(|files| files.contains(&source.path))
633 })
634 }
635}
636
637struct SourceFile {
638 display: String,
640 path: PathBuf,
642 owners: BTreeSet<PathBuf>,
643 original: String,
644 lines: scope::LineIndex,
645 sites: Vec<Site>,
646 rebuild_sites: Vec<Site>,
648 places: Vec<(usize, usize, String)>,
651 rendered: Option<Rendered>,
652}
653
654fn write_rendered(
655 file: &mut SourceFile,
656 state: &WorkCopy,
657 suffix: &str,
658 disabled: &HashSet<u32>,
659 newly_disabled: &HashSet<u32>,
660) -> Result<()> {
661 if file.rendered.is_none()
662 || file
663 .sites
664 .iter()
665 .any(|site| newly_disabled.contains(&site.id))
666 {
667 file.rendered = Some(instrument::render(&file.original, &file.sites, &|id| {
668 !disabled.contains(&id)
669 }));
670 }
671 let rendered = file.rendered.as_ref().expect("rendered before writing");
672 if suffix.is_empty() {
673 state.write(&file.path, &rendered.text)
674 } else {
675 state.write(&file.path, &format!("{}{suffix}", rendered.text))
676 }
677}
678
679#[derive(Clone)]
681enum Runner {
682 Exe(PathBuf),
684 Isolated {
685 exe: PathBuf,
686 test: String,
687 ignored: bool,
688 wrapper: Option<PathBuf>,
689 },
690 Nextest {
691 copy: PathBuf,
692 target_dir: PathBuf,
693 profile: Option<String>,
694 opt_level: Option<u8>,
695 flags: Vec<String>,
696 },
697 Doc {
700 copy: PathBuf,
701 target_dir: PathBuf,
702 package: String,
703 opt_level: Option<u8>,
704 flags: Vec<String>,
705 },
706}
707
708impl Runner {
709 fn executable(&self) -> Option<&Path> {
710 match self {
711 Self::Exe(exe) | Self::Isolated { exe, .. } => Some(exe),
712 Self::Doc { .. } | Self::Nextest { .. } => None,
713 }
714 }
715}
716
717#[derive(Clone, Copy)]
718enum BaselineTiming {
719 Completed(Duration),
720 StillRunning(Duration),
721}
722
723fn explicit_timeout_conflict(
724 timeout: Option<Duration>,
725 baseline: Duration,
726 selected_count: Option<usize>,
727 test_count: usize,
728) -> Option<Duration> {
729 let entire_runner = selected_count.is_none_or(|count| count == test_count);
730 timeout.filter(|&limit| entire_runner && baseline >= limit)
731}
732
733struct TestBinary {
734 name: String,
735 cwd: PathBuf,
737 marks: PathBuf,
739 git_ceiling: PathBuf,
740 work_lock: Option<Arc<WorkLock>>,
741 tests: BTreeSet<String>,
743 runner: Runner,
744 baseline: Duration,
746 untraced_baseline: Option<BaselineTiming>,
748 timeout_diagnostic: std::sync::Once,
749 traced: Duration,
751 timeout: Option<Duration>,
752 wrapper_grace: Duration,
753 report_slow: bool,
754 filtered_timings:
755 std::sync::Mutex<BTreeMap<Vec<String>, std::sync::Arc<std::sync::OnceLock<Duration>>>>,
756 trace: Trace,
757 effects_baseline: std::sync::OnceLock<propagation::BaselineIndex>,
758}
759
760impl TestBinary {
761 fn mutant_limit(&self, baseline: Duration) -> Duration {
762 self.timeout.unwrap_or_else(|| mutant_timeout(baseline))
763 }
764
765 fn warn_timeout_conflict(&self, filter: Option<&[String]>) {
766 let Some(limit) = explicit_timeout_conflict(
768 self.timeout,
769 self.baseline,
770 filter.map(<[String]>::len),
771 self.tests.len(),
772 ) else {
773 return;
774 };
775 self.timeout_diagnostic.call_once(|| {
776 let timing = self.untraced_baseline.or_else(|| {
777 let started = Instant::now();
778 match run_binary(self, None, &[], self.traced, RunOutput::Quiet, 1) {
781 Ok(Outcome::Pass) => Some(BaselineTiming::Completed(started.elapsed())),
782 Ok(Outcome::Timeout) => Some(BaselineTiming::StillRunning(self.traced)),
783 _ => None,
784 }
785 });
786 let (elapsed, message) = match timing {
787 Some(BaselineTiming::Completed(elapsed)) => (elapsed, "took"),
788 Some(BaselineTiming::StillRunning(elapsed)) => (elapsed, "was still running after"),
789 None => return,
790 };
791 if elapsed >= limit {
792 eprintln!(
793 "tmt: warning: unmutated baseline for `{}` {message} {:.3}s, meeting or exceeding --timeout {}",
794 self.name, elapsed.as_secs_f64(), limit.as_secs()
795 );
796 }
797 });
798 }
799
800 fn filtered_limit(&self, filter: Option<&[String]>, traced: bool) -> Duration {
801 let baseline = if traced { self.traced } else { self.baseline };
802 let Some(filter) =
803 filter.filter(|names| !names.is_empty() && names.len() < self.tests.len())
804 else {
805 return self.mutant_limit(baseline);
806 };
807 if self.timeout.is_some() || baseline < SLOW_TRACE || !matches!(self.runner, Runner::Exe(_))
808 {
809 return self.mutant_limit(baseline);
810 }
811 let timed = {
812 let mut groups = self.filtered_timings.lock().unwrap();
813 groups.entry(filter.to_vec()).or_default().clone()
814 };
815 let timing = *timed.get_or_init(|| {
816 let untraced = self.baseline;
817 let started = Instant::now();
818 match run_binary(self, Some(filter), &[], untraced, RunOutput::Quiet, 1) {
821 Ok(Outcome::Pass) => started.elapsed(),
822 _ => untraced,
823 }
824 });
825 self.mutant_limit(if traced {
826 timing.max(
827 timing.mul_f64(self.traced.as_secs_f64() / self.baseline.as_secs_f64().max(0.001)),
828 )
829 } else {
830 timing
831 })
832 }
833}
834
835#[derive(Debug, PartialEq, Clone, Copy, Serialize, Deserialize)]
836#[serde(rename_all = "snake_case")]
837enum Outcome {
838 Pass,
839 Fail,
840 Timeout,
841 Unable,
843}
844
845impl From<Outcome> for progress::Outcome {
846 fn from(outcome: Outcome) -> Self {
847 match outcome {
848 Outcome::Pass => Self::Survived,
849 Outcome::Fail => Self::Failed,
850 Outcome::Timeout => Self::TimedOut,
851 Outcome::Unable => Self::Unable,
852 }
853 }
854}
855
856fn isolate_copy_command(command: &mut Command, work: &Path) {
857 git_index::remove_git_overrides(command);
858 command.env("GIT_CEILING_DIRECTORIES", work);
859}
860
861const WRITTEN_LOG: &str = ".tmt-written";
863
864struct WorkCopy {
872 root: PathBuf,
873 log: PathBuf,
874 kept: RefCell<HashSet<PathBuf>>,
876 earlier: HashSet<PathBuf>,
878 visited: RefCell<HashSet<PathBuf>>,
880 written: RefCell<HashSet<PathBuf>>,
882 logged: RefCell<HashSet<PathBuf>>,
884}
885
886impl WorkCopy {
887 fn open(work: &Path, root: &Path) -> WorkCopy {
888 let log = work.join(WRITTEN_LOG);
889 for file in [log.clone(), log.with_extension("new")] {
891 if fs::symlink_metadata(&file).is_ok_and(|found| found.is_symlink()) {
892 let _ = fs::remove_file(&file);
893 }
894 }
895 let earlier: HashSet<PathBuf> = fs::read_to_string(&log)
896 .unwrap_or_default()
897 .lines()
898 .map(Path::new)
899 .filter(|relative| {
901 let mut parts = relative.components();
902 parts.clone().next().is_some()
903 && parts.all(|part| matches!(part, std::path::Component::Normal(_)))
904 })
905 .map(|relative| root.join(relative))
906 .collect();
907 WorkCopy {
908 root: root.to_path_buf(),
909 log,
910 kept: RefCell::default(),
911 logged: RefCell::new(earlier.clone()),
912 earlier,
913 visited: RefCell::default(),
914 written: RefCell::default(),
915 }
916 }
917
918 fn is_kept(&self, path: &Path) -> bool {
919 self.kept.borrow().contains(path) || self.earlier.contains(path)
920 }
921
922 fn original(&self, path: &Path, workspace: &Path) -> Result<Option<String>> {
925 let source = if !self.earlier.contains(path) {
926 path.to_path_buf() } else if !self.visited.borrow().contains(path) {
928 return Ok(None);
929 } else {
930 workspace.join(path.strip_prefix(&self.root).unwrap_or(path))
931 };
932 fs::read_to_string(&source)
933 .map(Some)
934 .with_context(|| format!("reading {}", source.display()))
935 }
936
937 fn write(&self, path: &Path, content: &str) -> Result<()> {
940 if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
941 fs::remove_file(path)?;
942 }
943 let parent = path.parent().and_then(|p| p.canonicalize().ok());
944 let inside = match (parent, self.root.canonicalize()) {
945 (Some(parent), Ok(root)) => parent.starts_with(root),
946 _ => false,
947 };
948 if !inside {
949 bail!(
950 "refusing to write outside the working copy: {}",
951 path.display()
952 );
953 }
954 self.record(path)?;
955 if fs::read_to_string(path).is_ok_and(|existing| existing == content) {
956 return Ok(()); }
958 fs::write(path, content).with_context(|| format!("writing {}", path.display()))
959 }
960
961 fn record(&self, path: &Path) -> Result<()> {
962 self.written.borrow_mut().insert(path.to_path_buf());
963 if self.logged.borrow().contains(path) {
964 return Ok(());
965 }
966 let line = path
967 .strip_prefix(&self.root)
968 .ok()
969 .and_then(Path::to_str)
970 .filter(|text| !text.chars().any(char::is_control));
971 let Some(line) = line else {
972 bail!(
973 "cannot instrument {}: its name cannot be written on a line of the log",
974 path.display()
975 );
976 };
977 use std::io::Write as _;
978 let mut log = fs::OpenOptions::new()
979 .create(true)
980 .append(true)
981 .open(&self.log)
982 .with_context(|| format!("opening {}", self.log.display()))?;
983 writeln!(log, "{line}").with_context(|| format!("writing {}", self.log.display()))?;
984 self.logged.borrow_mut().insert(path.to_path_buf());
985 Ok(())
986 }
987
988 fn settle(&self, workspace: &Path) -> Result<()> {
991 let written = self.written.borrow();
992 for path in self.earlier.difference(&written) {
993 if fs::symlink_metadata(path).is_ok() {
994 fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
995 }
996 if self.visited.borrow().contains(path) {
997 let source = workspace.join(path.strip_prefix(&self.root).unwrap_or(path));
998 copy_as_new(&source, path)?;
999 }
1000 }
1001 let mut lines: Vec<&str> = written
1002 .iter()
1003 .filter_map(|path| path.strip_prefix(&self.root).ok()?.to_str())
1004 .collect();
1005 lines.sort_unstable();
1006 let fresh = self.log.with_extension("new");
1007 fs::write(
1008 &fresh,
1009 lines
1010 .iter()
1011 .map(|line| format!("{line}\n"))
1012 .collect::<String>(),
1013 )?;
1014 fs::rename(&fresh, &self.log)?;
1015 *self.logged.borrow_mut() = written.clone();
1016 Ok(())
1017 }
1018}
1019
1020fn sync_file(src: &Path, dst: &Path, state: &WorkCopy) -> Result<()> {
1024 state.kept.borrow_mut().insert(dst.to_path_buf());
1025 if state.earlier.contains(dst) {
1026 state.visited.borrow_mut().insert(dst.to_path_buf());
1027 if fs::symlink_metadata(dst).is_ok_and(|m| m.is_file()) {
1028 return Ok(());
1030 }
1031 }
1032 let up_to_date = fs::symlink_metadata(dst).is_ok_and(|to| to.is_file()) && same_bytes(src, dst);
1036 if up_to_date {
1037 return Ok(());
1038 }
1039 if let Ok(existing) = fs::symlink_metadata(dst) {
1040 if existing.is_dir() {
1041 fs::remove_dir_all(dst)?;
1042 } else {
1043 fs::remove_file(dst)?;
1044 }
1045 }
1046 copy_as_new(src, dst)
1047}
1048
1049fn same_bytes(a: &Path, b: &Path) -> bool {
1051 let (Ok(a), Ok(b)) = (fs::File::open(a), fs::File::open(b)) else {
1052 return false;
1053 };
1054 compare_streams(a, b).unwrap_or(false)
1055}
1056
1057fn real_dir(dir: &Path, state: &WorkCopy) -> Result<()> {
1061 if let Ok(below) = dir.strip_prefix(&state.root) {
1062 let mut path = state.root.clone();
1063 for part in below.components() {
1064 path.push(part);
1065 match fs::symlink_metadata(&path) {
1066 Ok(found) if !found.is_dir() => fs::remove_file(&path)
1067 .with_context(|| format!("removing {}", path.display()))?,
1068 _ => {}
1069 }
1070 }
1071 }
1072 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))
1073}
1074
1075fn copy_as_new(src: &Path, dst: &Path) -> Result<()> {
1079 fs::copy(src, dst).with_context(|| format!("copying {}", src.display()))?;
1080 fs::File::open(dst)
1082 .and_then(|file| file.set_modified(std::time::SystemTime::now()))
1083 .with_context(|| format!("touching {}", dst.display()))
1084}
1085
1086fn prune(dir: &Path, state: &WorkCopy) -> Result<bool> {
1088 let mut empty = true;
1089 for entry in fs::read_dir(dir)? {
1090 let path = entry?.path();
1091 let is_dir = fs::symlink_metadata(&path)?.is_dir();
1092 if is_dir {
1093 if prune(&path, state)? && !state.is_kept(&path) {
1094 fs::remove_dir(&path)?;
1095 } else {
1096 empty = false;
1097 }
1098 } else if state.is_kept(&path) {
1099 empty = false;
1100 } else {
1101 fs::remove_file(&path)?;
1102 }
1103 }
1104 Ok(empty)
1105}
1106
1107fn copy_entry(
1114 src: &Path,
1115 dst: &Path,
1116 workspace: &Path,
1117 skip: &dyn Fn(&Path) -> bool,
1118 state: &WorkCopy,
1119) -> Result<()> {
1120 let kind = fs::symlink_metadata(src)?.file_type();
1121 if kind.is_symlink() {
1122 let Ok(target) = src.canonicalize() else {
1123 return Ok(()); };
1125 if target.is_dir() {
1126 let contains_link = src
1127 .parent()
1128 .is_some_and(|dir| dir.canonicalize().is_ok_and(|dir| dir.starts_with(&target)));
1129 if !target.starts_with(workspace) || contains_link || skip(&target) {
1130 return Ok(());
1131 }
1132 return copy_tree(&target, dst, workspace, skip, state);
1133 }
1134 sync_file(&target, dst, state)?;
1135 } else if kind.is_dir() {
1136 if !src.join("CACHEDIR.TAG").exists() {
1138 copy_tree(src, dst, workspace, skip, state)?;
1139 }
1140 } else {
1141 sync_file(src, dst, state)?;
1142 }
1143 Ok(())
1144}
1145
1146fn copy_tree(
1147 from: &Path,
1148 to: &Path,
1149 workspace: &Path,
1150 skip: &dyn Fn(&Path) -> bool,
1151 state: &WorkCopy,
1152) -> Result<()> {
1153 real_dir(to, state)?;
1154 for entry in fs::read_dir(from).with_context(|| format!("reading {}", from.display()))? {
1155 let src = entry?.path();
1156 if skip(&src) {
1157 continue;
1158 }
1159 let Some(name) = src.file_name() else {
1160 continue;
1161 };
1162 copy_entry(&src, &to.join(name), workspace, skip, state)?;
1163 }
1164 Ok(())
1165}
1166
1167fn fixture_relative(path: &Path) -> Result<PathBuf> {
1168 use std::path::Component;
1169 let relative = path
1170 .components()
1171 .filter(|part| *part != Component::CurDir)
1172 .collect::<PathBuf>();
1173 if relative.as_os_str().is_empty()
1174 || relative
1175 .components()
1176 .any(|part| !matches!(part, Component::Normal(_)))
1177 {
1178 bail!(
1179 "fixture path must be inside the workspace: {}",
1180 path.display()
1181 );
1182 }
1183 Ok(relative)
1184}
1185
1186fn fixture_exclusions(
1187 workspace: &Path,
1188 roots: &[PathBuf],
1189 excluded: &[PathBuf],
1190) -> Result<BTreeSet<PathBuf>> {
1191 excluded
1192 .iter()
1193 .map(|path| {
1194 let relative = fixture_relative(path)?;
1195 if !roots
1196 .iter()
1197 .any(|root| relative != *root && relative.starts_with(root))
1198 {
1199 bail!(
1200 "--copy-fixture-exclude must name an entry under a --copy-fixture: {}",
1201 path.display()
1202 );
1203 }
1204 let path = workspace.join(relative);
1205 fs::symlink_metadata(&path)
1206 .with_context(|| format!("excluding fixture {}", path.display()))?;
1207 confined_fixture_path(workspace, &path)?;
1208 Ok(path)
1209 })
1210 .collect()
1211}
1212
1213fn confined_fixture_path(workspace: &Path, path: &Path) -> Result<()> {
1214 use std::collections::VecDeque;
1215 use std::path::Component;
1216
1217 let parts = |relative: &Path| {
1218 relative
1219 .components()
1220 .map(|part| part.as_os_str().to_owned())
1221 .collect::<Vec<_>>()
1222 };
1223 let mut pending = VecDeque::from(parts(path.strip_prefix(workspace)?));
1224 let mut resolved = workspace.to_path_buf();
1225 let mut hops = 0;
1226 while let Some(part) = pending.pop_front() {
1227 match Path::new(&part).components().next() {
1228 Some(Component::ParentDir) if resolved != workspace => {
1229 resolved.pop();
1230 }
1231 Some(Component::CurDir) => {}
1232 Some(Component::Normal(_)) => {
1233 resolved.push(part);
1234 match fs::symlink_metadata(&resolved) {
1235 Ok(metadata) if metadata.is_symlink() => {
1236 hops += 1;
1237 if hops > 40 {
1238 bail!("fixture {} contains a symbolic link cycle", path.display());
1239 }
1240 let target = fs::read_link(&resolved)?;
1241 resolved.pop();
1242 let target = if target.is_absolute() {
1243 resolved = workspace.to_path_buf();
1244 target.strip_prefix(workspace).with_context(|| {
1245 format!("fixture {} points outside the workspace", path.display())
1246 })?
1247 } else {
1248 &target
1249 };
1250 for component in parts(target).into_iter().rev() {
1251 pending.push_front(component);
1252 }
1253 }
1254 Ok(_) => {}
1255 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
1256 Err(err) => {
1257 return Err(err)
1258 .with_context(|| format!("checking fixture {}", path.display()));
1259 }
1260 }
1261 }
1262 _ => bail!("fixture {} points outside the workspace", path.display()),
1263 }
1264 }
1265 Ok(())
1266}
1267
1268fn copy_fixture_entry(
1271 from: &Path,
1272 to: &Path,
1273 workspace: &Path,
1274 forbidden: &dyn Fn(&Path) -> bool,
1275 state: &WorkCopy,
1276 visiting: &mut BTreeSet<PathBuf>,
1277) -> Result<()> {
1278 let resolved = from
1279 .canonicalize()
1280 .with_context(|| format!("resolving fixture {}", from.display()))?;
1281 let allowed = |path: &Path| {
1282 path.starts_with(workspace)
1283 && path != workspace
1284 && !path
1285 .ancestors()
1286 .take_while(|part| *part != workspace)
1287 .any(forbidden)
1288 };
1289 if !allowed(from) || !allowed(&resolved) {
1290 bail!(
1291 "fixture {} resolves to an excluded path: {}",
1292 from.display(),
1293 resolved.display()
1294 );
1295 }
1296 let kind = fs::metadata(&resolved)?.file_type();
1297 real_dir(to.parent().expect("fixture has a parent"), state)?;
1298 if kind.is_file() {
1299 return sync_file(&resolved, to, state);
1300 }
1301 if !kind.is_dir() || !visiting.insert(resolved.clone()) {
1302 bail!(
1303 "fixture {} is a cycle or is not a regular file or directory",
1304 from.display()
1305 );
1306 }
1307 real_dir(to, state)?;
1308 state.kept.borrow_mut().insert(to.to_path_buf());
1309 for entry in fs::read_dir(&resolved)? {
1310 let entry = entry?;
1311 let path = entry.path();
1312 let destination = to.join(entry.file_name());
1313 let projected = workspace.join(
1314 destination
1315 .strip_prefix(&state.root)
1316 .expect("fixture under copy"),
1317 );
1318 if !forbidden(&path) && !forbidden(&projected) {
1319 copy_fixture_entry(&path, &destination, workspace, forbidden, state, visiting)?;
1320 }
1321 }
1322 visiting.remove(&resolved);
1323 Ok(())
1324}
1325
1326fn git_visible_files(dir: &Path) -> Result<Option<Vec<PathBuf>>> {
1330 let git = |args: &[&str]| {
1331 Command::new("git")
1332 .arg("-C")
1333 .arg(dir)
1334 .args(args)
1335 .stderr(Stdio::null())
1336 .output()
1337 };
1338 let Ok(inside) = git(&["rev-parse", "--is-inside-work-tree"]) else {
1340 return Ok(None);
1341 };
1342 if !inside.status.success() {
1343 return Ok(None);
1344 }
1345 if git(&["check-ignore", "-q", "."])?.status.success() {
1347 return Ok(None);
1348 }
1349 let listing = git(&[
1352 "ls-files",
1353 "--cached",
1354 "--others",
1355 "--exclude-standard",
1356 "-z",
1357 ])?;
1358 if !listing.status.success() {
1359 bail!(
1360 "git could not list the files of {}; pass --all-files to copy everything",
1361 dir.display()
1362 );
1363 }
1364 Ok(Some(
1365 listing
1366 .stdout
1367 .split(|b| *b == 0)
1368 .filter(|name| !name.is_empty())
1369 .filter_map(|name| std::str::from_utf8(name).ok())
1370 .map(PathBuf::from)
1371 .collect(),
1372 ))
1373}
1374
1375fn copy_git_visible(
1378 from: &Path,
1379 to: &Path,
1380 files: Vec<PathBuf>,
1381 workspace: &Path,
1382 skip: &dyn Fn(&Path) -> bool,
1383 state: &WorkCopy,
1384) -> Result<usize> {
1385 let mut copied = 0;
1386 for relative in files {
1387 let (src, dst) = (from.join(&relative), to.join(&relative));
1388 if skip(&src)
1389 || src
1390 .ancestors()
1391 .any(|a| a != from && a.starts_with(from) && skip(a))
1392 {
1393 continue;
1394 }
1395 let Ok(kind) = fs::symlink_metadata(&src).map(|m| m.file_type()) else {
1396 continue; };
1398 if let Some(parent) = dst.parent() {
1399 real_dir(parent, state)?;
1400 }
1401 if kind.is_dir() {
1402 match git_visible_files(&src)? {
1403 Some(inner) => {
1404 copied += copy_git_visible(&src, &dst, inner, workspace, skip, state)?
1405 }
1406 None => copy_tree(&src, &dst, workspace, skip, state)?,
1407 }
1408 } else {
1409 copy_entry(&src, &dst, workspace, skip, state)?;
1410 copied += 1;
1411 }
1412 }
1413 Ok(copied)
1414}
1415
1416#[derive(Default)]
1417struct ModuleOwners {
1418 production: BTreeSet<PathBuf>,
1419 consumers: BTreeSet<PathBuf>,
1420}
1421
1422fn source_graph(
1423 roots: impl IntoIterator<Item = (PathBuf, bool)>,
1424 copy: &Path,
1425 mut original: impl FnMut(&Path) -> Result<Option<String>>,
1426) -> Result<BTreeMap<PathBuf, ModuleOwners>> {
1427 use std::collections::{VecDeque, btree_map::Entry};
1428 let mut files: BTreeMap<PathBuf, ModuleOwners> = BTreeMap::new();
1429 let mut edges = BTreeMap::new();
1430 for (root, production) in roots {
1431 let directory = root.parent().expect("Cargo target directory").to_path_buf();
1432 let mut pending = VecDeque::from([(root.clone(), directory, production)]);
1433 let mut seen = HashSet::new();
1434 while let Some((path, directory, active)) = pending.pop_front() {
1435 if !seen.insert((path.clone(), directory.clone(), active)) {
1436 continue;
1437 }
1438 let children = match edges.entry((path.clone(), directory.clone())) {
1441 Entry::Occupied(entry) => entry.into_mut(),
1442 Entry::Vacant(entry) => {
1443 let children = original(&path)?.map(|source| {
1444 crate::modules::external(&source, &path, &directory)
1445 .into_iter()
1446 .filter_map(|module| {
1447 let file = module
1448 .paths
1449 .iter()
1450 .map(|path| normalize(path))
1451 .find(|path| path.starts_with(copy) && path.is_file())?;
1452 Some((file, normalize(&module.directory), module.production))
1453 })
1454 .collect::<Vec<_>>()
1455 });
1456 entry.insert(children)
1457 }
1458 };
1459 let Some(children) = children else {
1460 continue;
1461 };
1462 let record = files.entry(path).or_default();
1463 record.consumers.insert(root.clone());
1464 if active {
1465 record.production.insert(root.clone());
1466 }
1467 pending.extend(children.iter().map(|(child, directory, production)| {
1468 (child.clone(), directory.clone(), active && *production)
1469 }));
1470 }
1471 }
1472 files.retain(|_, owners| !owners.production.is_empty());
1473 Ok(files)
1474}
1475
1476fn normalize(path: &Path) -> PathBuf {
1478 let mut out = PathBuf::new();
1479 for component in path.components() {
1480 match component {
1481 std::path::Component::CurDir => {}
1482 std::path::Component::ParentDir => {
1483 out.pop();
1484 }
1485 other => out.push(other),
1486 }
1487 }
1488 out
1489}
1490
1491fn relative_source(path: &Path, package: &Path) -> PathBuf {
1492 for (depth, ancestor) in package.ancestors().enumerate() {
1493 if let Ok(local) = path.strip_prefix(ancestor) {
1494 let mut relative: PathBuf = std::iter::repeat_n("..", depth).collect();
1495 relative.push(local);
1496 return relative;
1497 }
1498 }
1499 path.to_path_buf()
1500}
1501
1502fn absolutize_path_dependencies(
1505 manifest: &str,
1506 manifest_dir: &Path,
1507 workspace: &Path,
1508 copy: &Path,
1509) -> Result<Option<String>> {
1510 use toml_edit::{DocumentMut, Item, TableLike, value};
1511
1512 fn fix(deps: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
1513 let (manifest_dir, workspace, copy) = dirs;
1514 for (_, dep) in deps.iter_mut() {
1515 let Some(dep) = dep.as_table_like_mut() else {
1516 continue;
1517 };
1518 let Some(path) = dep.get("path").and_then(Item::as_str) else {
1519 continue;
1520 };
1521 let absolute = Path::new(path).is_absolute();
1522 let target = normalize(&manifest_dir.join(path));
1523 let rewritten = match target.strip_prefix(workspace) {
1524 Err(_) => target,
1526 Ok(inside) if absolute => copy.join(inside),
1529 Ok(_) => continue,
1530 };
1531 dep.insert("path", value(rewritten.to_string_lossy().into_owned()));
1532 *changed = true;
1533 }
1534 }
1535 const SECTIONS: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];
1536 fn fix_sections(table: &mut dyn TableLike, dirs: (&Path, &Path, &Path), changed: &mut bool) {
1537 for section in SECTIONS {
1538 if let Some(deps) = table.get_mut(section).and_then(Item::as_table_like_mut) {
1539 fix(deps, dirs, changed);
1540 }
1541 }
1542 }
1543
1544 let mut doc: DocumentMut = manifest.parse().context("parsing Cargo.toml")?;
1545 let mut changed = false;
1546 let dirs = (manifest_dir, workspace, copy);
1547 fix_sections(doc.as_table_mut(), dirs, &mut changed);
1548 if let Some(ws) = doc.get_mut("workspace").and_then(Item::as_table_like_mut) {
1549 fix_sections(ws, dirs, &mut changed);
1550 }
1551 for per_key in ["target", "patch"] {
1552 let Some(outer) = doc.get_mut(per_key).and_then(Item::as_table_like_mut) else {
1553 continue;
1554 };
1555 for (_, inner) in outer.iter_mut() {
1556 let Some(inner) = inner.as_table_like_mut() else {
1557 continue;
1558 };
1559 if per_key == "target" {
1560 fix_sections(inner, dirs, &mut changed);
1561 } else {
1562 fix(inner, dirs, &mut changed);
1563 }
1564 }
1565 }
1566 Ok(changed.then(|| doc.to_string()))
1567}
1568
1569fn test_filter(tests: &BTreeSet<String>, known: &BTreeSet<String>) -> Option<Vec<String>> {
1575 if tests.len() > MAX_TEST_FILTERS || !tests.iter().all(|t| known.contains(t)) {
1576 None
1577 } else {
1578 Some(tests.iter().cloned().collect())
1579 }
1580}
1581
1582fn parse_test_list(stdout: &str) -> BTreeSet<String> {
1584 stdout
1585 .lines()
1586 .filter_map(|line| line.strip_suffix(": test"))
1587 .map(str::to_string)
1588 .collect()
1589}
1590
1591fn list_tests(
1593 exe: &Path,
1594 cwd: &Path,
1595 work: &Path,
1596 ignored: bool,
1597 strict: bool,
1598 lock: Option<&WorkLock>,
1599) -> Result<BTreeSet<String>> {
1600 let mut command = Command::new(exe);
1601 isolate_copy_command(&mut command, work);
1602 if let Some(lock) = lock {
1603 lock.retain_for(&mut command);
1604 }
1605 command.args(["--list", "--format", "terse"]);
1606 if ignored {
1607 command.arg("--ignored");
1608 }
1609 let listing = command
1610 .current_dir(cwd)
1611 .stdin(Stdio::null())
1612 .output()
1613 .with_context(|| format!("listing tests of {}", exe.display()))?;
1614 if !listing.status.success() {
1615 if !strict {
1616 return Ok(BTreeSet::new());
1617 }
1618 bail!(
1619 "listing tests of {} failed: {}",
1620 exe.display(),
1621 String::from_utf8_lossy(&listing.stderr)
1622 );
1623 }
1624 Ok(parse_test_list(&String::from_utf8_lossy(&listing.stdout)))
1625}
1626
1627fn profile_env(opt_level: Option<u8>) -> Vec<(&'static str, String)> {
1629 opt_level.map_or(vec![], |level| {
1630 vec![
1631 ("CARGO_PROFILE_DEV_OPT_LEVEL", level.to_string()),
1632 ("CARGO_PROFILE_TEST_OPT_LEVEL", level.to_string()),
1633 ]
1634 })
1635}
1636
1637const SLOW_TRACE: Duration = Duration::from_secs(2);
1639
1640fn mutant_timeout(baseline: Duration) -> Duration {
1641 Duration::from_secs(5) + baseline * 5
1642}
1643
1644const TEST_POLL_INITIAL: Duration = Duration::from_micros(250);
1645const TEST_POLL_CAP: Duration = Duration::from_millis(5);
1646
1647fn next_test_poll(delay: &mut Duration, remaining: Duration) -> Duration {
1650 let wait = (*delay).min(remaining);
1651 *delay = (*delay * 2).min(TEST_POLL_CAP);
1652 wait
1653}
1654
1655fn test_threads(cores: usize, sharing: usize) -> usize {
1659 (cores / sharing.max(1)).max(2)
1660}
1661
1662enum RunOutput<'a> {
1663 Quiet,
1664 FirstFailure,
1665 Capture(&'a fs::File),
1666}
1667
1668fn nextest_outcome(code: Option<i32>) -> Result<Outcome> {
1669 match code {
1670 Some(0) => Ok(Outcome::Pass),
1671 Some(100) => Ok(Outcome::Fail),
1673 _ => bail!("cargo nextest failed outside a test (exit code {code:?})"),
1674 }
1675}
1676
1677fn run_binary(
1678 bin: &TestBinary,
1679 tests: Option<&[String]>,
1680 env: &[(&str, &str)],
1681 timeout: Duration,
1682 output: RunOutput<'_>,
1683 sharing: usize,
1684) -> Result<Outcome> {
1685 let cores = std::thread::available_parallelism().map_or(2, |n| n.get());
1686 let threads = test_threads(cores, sharing);
1687 static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1688 let unable_mark = reserve_file(&bin.marks, "unable", &RUNS)?;
1689
1690 let mut cmd = match &bin.runner {
1691 Runner::Exe(exe) => {
1692 let mut cmd = Command::new(exe);
1693 cmd.arg(format!("--test-threads={threads}"));
1696 if let Some(tests) = tests {
1697 cmd.arg("--exact").args(tests);
1698 }
1699 cmd.current_dir(&bin.cwd)
1700 .env("CARGO_MANIFEST_DIR", &bin.cwd);
1701 cmd
1702 }
1703 Runner::Isolated {
1704 exe,
1705 test,
1706 ignored,
1707 wrapper,
1708 } => {
1709 let mut cmd = if let Some(wrapper) = wrapper {
1710 let mut cmd = Command::new(wrapper);
1711 cmd.arg(exe);
1712 cmd
1713 } else {
1714 Command::new(exe)
1715 };
1716 cmd.args(["--exact", "--test-threads=1", test]);
1717 if *ignored {
1718 cmd.arg("--ignored");
1719 }
1720 cmd.current_dir(&bin.cwd)
1721 .env("CARGO_MANIFEST_DIR", &bin.cwd);
1722 cmd
1723 }
1724 Runner::Nextest {
1725 copy,
1726 target_dir,
1727 profile,
1728 opt_level,
1729 flags,
1730 } => {
1731 let mut cmd = Command::new("cargo");
1732 cmd.args(["nextest", "run", "--no-tests=fail"]);
1733 if let Some(profile) = profile {
1734 cmd.args(["--profile", profile]);
1735 }
1736 cmd.args(flags)
1737 .current_dir(copy)
1738 .env("CARGO_TARGET_DIR", target_dir)
1739 .env("CARGO_BUILD_BUILD_DIR", target_dir)
1740 .envs(profile_env(*opt_level));
1741 cmd
1742 }
1743 Runner::Doc {
1744 copy,
1745 target_dir,
1746 package,
1747 opt_level,
1748 flags,
1749 } => {
1750 let mut cmd = Command::new("cargo");
1751 cmd.args(["test", "--doc", "-p", package])
1752 .args(flags)
1753 .current_dir(copy)
1754 .env("CARGO_TARGET_DIR", target_dir)
1755 .env("CARGO_BUILD_BUILD_DIR", target_dir)
1756 .envs(profile_env(*opt_level));
1757 cmd
1758 }
1759 };
1760 isolate_copy_command(&mut cmd, &bin.git_ceiling);
1761 if let Some(lock) = &bin.work_lock {
1762 lock.retain_for(&mut cmd);
1763 }
1764 cmd.env_remove("TMT_TRACE")
1765 .env_remove("TMT_MUTANT")
1766 .env_remove("TMT_TEST")
1767 .env_remove(witness::OUTPUT_ENV)
1768 .env("TMT_UNABLE", &unable_mark)
1769 .envs(env.iter().copied())
1770 .stdin(Stdio::null());
1771 if let Runner::Isolated { test, .. } = &bin.runner {
1772 cmd.env("TMT_TEST", test);
1773 }
1774 let nextest = matches!(bin.runner, Runner::Nextest { .. });
1775 let mut output_to_watch = None;
1776 match output {
1777 RunOutput::Capture(file) => {
1778 cmd.stdout(file.try_clone()?).stderr(file.try_clone()?);
1779 }
1780 RunOutput::FirstFailure if !nextest && !matches!(bin.runner, Runner::Isolated { .. }) => {
1781 let writer = fs::OpenOptions::new().append(true).open(&unable_mark)?;
1784 output_to_watch = Some(FailureOutput::new(fs::File::open(&unable_mark)?));
1785 cmd.stdout(writer).stderr(Stdio::null());
1786 }
1787 RunOutput::Quiet | RunOutput::FirstFailure => {
1788 cmd.stdout(Stdio::null()).stderr(Stdio::null());
1789 }
1790 }
1791 #[cfg(unix)]
1793 std::os::unix::process::CommandExt::process_group(&mut cmd, 0);
1794 let mut child = cmd
1795 .spawn()
1796 .with_context(|| format!("starting the tests of `{}`", bin.name))?;
1797 let group = child.id();
1798 let kill = |child: &mut std::process::Child| {
1799 if nextest {
1800 stop_nextest(child, Duration::from_secs(12));
1803 return;
1804 }
1805 kill_test_group(group);
1806 let _ = child.kill();
1807 let _ = child.wait();
1808 };
1809 let started = Instant::now();
1810 let mut delay = TEST_POLL_INITIAL;
1811 let mut waiting_reported = false;
1812 let running_mutant = env.iter().any(|(key, _)| *key == "TMT_MUTANT")
1813 || matches!(output, RunOutput::FirstFailure);
1814 let result: Result<Outcome> = (|| loop {
1815 if let Some(status) = child.try_wait()? {
1816 if matches!(bin.runner, Runner::Isolated { .. }) || output_to_watch.is_some() {
1817 kill_test_group(group);
1818 }
1819 if nextest {
1820 return nextest_outcome(status.code());
1821 }
1822 return Ok(if status.success() {
1823 Outcome::Pass
1824 } else {
1825 Outcome::Fail
1826 });
1827 }
1828 if output_to_watch
1829 .as_mut()
1830 .map(FailureOutput::failed)
1831 .transpose()?
1832 .unwrap_or(false)
1833 {
1834 kill(&mut child);
1835 return Ok(Outcome::Fail);
1836 }
1837 let elapsed = started.elapsed();
1838 if bin.report_slow
1839 && running_mutant
1840 && !waiting_reported
1841 && elapsed >= Duration::from_secs(5).min(timeout / 2)
1842 {
1843 let selected = tests
1844 .filter(|names| !names.is_empty())
1845 .map(|names| names.join(", "))
1846 .unwrap_or_else(|| bin.name.clone());
1847 eprintln!(
1848 "tmt: waiting for mutant tests `{selected}` (limit {:.2}s)",
1849 timeout.as_secs_f64()
1850 );
1851 waiting_reported = true;
1852 }
1853 if elapsed >= timeout {
1854 if cfg!(unix)
1855 && !bin.wrapper_grace.is_zero()
1856 && matches!(
1857 &bin.runner,
1858 Runner::Isolated {
1859 wrapper: Some(_),
1860 ..
1861 }
1862 )
1863 {
1864 signal_test_group(group, 15);
1865 let began = Instant::now();
1866 while began.elapsed() < bin.wrapper_grace && child.try_wait().ok() == Some(None) {
1867 std::thread::sleep(
1868 Duration::from_millis(10)
1869 .min(bin.wrapper_grace.saturating_sub(began.elapsed())),
1870 );
1871 }
1872 }
1873 kill(&mut child);
1874 return Ok(Outcome::Timeout);
1875 }
1876 std::thread::sleep(next_test_poll(&mut delay, timeout - elapsed));
1877 })();
1878 drop(output_to_watch);
1879 if result.is_err() {
1880 kill(&mut child);
1881 let _ = release_mark(&unable_mark);
1882 }
1883 let outcome = result?;
1884
1885 if release_mark(&unable_mark)? {
1889 return Ok(Outcome::Unable);
1890 }
1891 Ok(outcome)
1892}
1893
1894struct FailureOutput {
1895 file: fs::File,
1896 line: Vec<u8>,
1897 discarded: bool,
1898}
1899
1900impl FailureOutput {
1901 fn new(file: fs::File) -> Self {
1902 Self {
1903 file,
1904 line: Vec::new(),
1905 discarded: false,
1906 }
1907 }
1908
1909 fn failed(&mut self) -> std::io::Result<bool> {
1910 use std::io::Read as _;
1911 const MAX_LINE: usize = 8 * 1024;
1912 let mut chunk = [0; MAX_LINE];
1913 let read = self.file.read(&mut chunk)?;
1914 for part in chunk[..read].split_inclusive(|byte| *byte == b'\n') {
1915 self.discarded |= self.line.len() + part.len() > MAX_LINE;
1916 if !self.discarded {
1917 self.line.extend_from_slice(part);
1918 }
1919 if part.ends_with(b"\n") {
1920 if !self.discarded
1921 && is_failure_line(String::from_utf8_lossy(&self.line).trim_end())
1922 {
1923 return Ok(true);
1924 }
1925 self.discarded = false;
1926 self.line.clear();
1927 }
1928 }
1929 Ok(false)
1930 }
1931}
1932
1933fn stop_nextest(child: &mut std::process::Child, grace: Duration) {
1934 let wait = |child: &mut std::process::Child, limit: Duration| {
1935 let started = Instant::now();
1936 loop {
1937 match child.try_wait() {
1938 Ok(Some(_)) => return true,
1939 Ok(None) if started.elapsed() < limit => {
1940 std::thread::sleep(Duration::from_millis(10));
1941 }
1942 _ => return false,
1943 }
1944 }
1945 };
1946 if wait(child, Duration::ZERO) {
1947 return;
1948 }
1949 let group = child.id();
1950 #[cfg(unix)]
1953 let mut owned = owned_test_processes(group);
1954 signal_test_group(group, 15);
1955 let mut reaped = wait(child, grace);
1956 if !reaped {
1957 signal_test_group(group, 15);
1959 reaped = wait(child, grace.min(Duration::from_secs(1)));
1960 }
1961 #[cfg(unix)]
1962 {
1963 if !reaped {
1964 owned.extend(owned_test_processes(group));
1965 }
1966 let current = test_processes();
1967 let surviving_groups: BTreeSet<_> = current
1968 .iter()
1969 .filter(|process| {
1970 owned.iter().any(|before| {
1971 process.pid == before.pid
1972 && process.group == before.group
1973 && process.started == before.started
1974 })
1975 })
1976 .map(|process| process.group)
1977 .collect();
1978 for surviving in surviving_groups {
1979 kill_test_group(surviving);
1980 }
1981 }
1982 if !reaped {
1983 kill_test_group(group);
1984 let _ = child.kill();
1985 let _ = child.wait();
1986 }
1987}
1988
1989#[cfg(unix)]
1990struct TestProcess {
1991 pid: u32,
1992 parent: u32,
1993 group: u32,
1994 started: String,
1995}
1996
1997#[cfg(unix)]
1998fn test_processes() -> Vec<TestProcess> {
1999 let Ok(processes) = Command::new("ps")
2000 .args([
2001 "-e", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "lstart=",
2002 ])
2003 .output()
2004 else {
2005 return vec![];
2006 };
2007 String::from_utf8_lossy(&processes.stdout)
2008 .lines()
2009 .filter_map(|line| {
2010 let mut fields = line.split_whitespace();
2011 Some(TestProcess {
2012 pid: fields.next()?.parse().ok()?,
2013 parent: fields.next()?.parse().ok()?,
2014 group: fields.next()?.parse().ok()?,
2015 started: fields.collect::<Vec<_>>().join(" "),
2016 })
2017 })
2018 .collect()
2019}
2020
2021#[cfg(unix)]
2022fn owned_test_processes(root: u32) -> Vec<TestProcess> {
2023 let data = test_processes();
2024 let mut owned = HashSet::from([root]);
2025 loop {
2026 let before = owned.len();
2027 for process in &data {
2028 if owned.contains(&process.parent) {
2029 owned.insert(process.pid);
2030 }
2031 }
2032 if owned.len() == before {
2033 break;
2034 }
2035 }
2036 let groups: HashSet<_> = data
2039 .iter()
2040 .filter(|process| process.pid == process.group && owned.contains(&process.pid))
2041 .map(|process| process.group)
2042 .collect();
2043 data.into_iter()
2044 .filter(|process| owned.contains(&process.pid) && groups.contains(&process.group))
2045 .collect()
2046}
2047
2048fn kill_test_group(id: u32) {
2049 signal_test_group(id, 9);
2050}
2051
2052fn signal_test_group(id: u32, signal: i32) {
2053 #[cfg(any(target_os = "linux", target_os = "macos"))]
2054 {
2055 unsafe extern "C" {
2056 fn killpg(group: std::ffi::c_int, signal: std::ffi::c_int) -> std::ffi::c_int;
2057 }
2058 if let Ok(group) = std::ffi::c_int::try_from(id) {
2059 unsafe { killpg(group, signal) };
2061 }
2062 }
2063 #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
2064 let _ = Command::new("kill")
2065 .args([format!("-{signal}"), "--".to_owned(), format!("-{id}")])
2066 .stdout(Stdio::null())
2067 .stderr(Stdio::null())
2068 .status();
2069 #[cfg(not(unix))]
2070 let _ = (id, signal);
2071}
2072
2073fn run_baseline(
2075 bin: &TestBinary,
2076 env: &[(&str, &str)],
2077 timeout: Duration,
2078 path: &Path,
2079 timing_only: bool,
2080) -> Result<bool> {
2081 use std::io::{Read, Seek, SeekFrom};
2082
2083 let mut suffix = 0;
2084 let (path, mut log) = loop {
2085 let candidate = if suffix == 0 {
2086 path.to_path_buf()
2087 } else {
2088 path.with_extension(format!("{suffix}.log"))
2089 };
2090 match fs::OpenOptions::new()
2091 .create_new(true)
2092 .read(true)
2093 .write(true)
2094 .open(&candidate)
2095 {
2096 Ok(log) => break (candidate, log),
2097 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => suffix += 1,
2098 Err(err) => {
2099 return Err(err)
2100 .with_context(|| format!("creating baseline log {}", candidate.display()));
2101 }
2102 }
2103 };
2104 let result =
2105 run_binary(bin, None, env, timeout, RunOutput::Capture(&log), 1).with_context(|| {
2106 format!(
2107 "running baseline for `{}`; output: {}",
2108 bin.name,
2109 path.display()
2110 )
2111 })?;
2112 if result == Outcome::Pass || (timing_only && result == Outcome::Timeout) {
2113 drop(log);
2114 fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
2115 return Ok(result == Outcome::Pass);
2116 }
2117 let reason = match result {
2118 Outcome::Pass => unreachable!("pass handled above"),
2119 Outcome::Fail => "do not pass on the unmutated code",
2120 Outcome::Timeout => "timed out on the unmutated code",
2121 Outcome::Unable => "could not be evaluated on the unmutated code",
2122 };
2123 const LIMIT: u64 = 16 * 1024;
2124 log.seek(SeekFrom::Start(log.metadata()?.len().saturating_sub(LIMIT)))?;
2125 let mut tail = Vec::new();
2126 log.take(LIMIT).read_to_end(&mut tail)?;
2127 bail!(
2128 "the tests in `{}` {reason}; full output: {}\n{}",
2129 bin.name,
2130 path.display(),
2131 String::from_utf8_lossy(&tail).trim_end()
2132 );
2133}
2134
2135fn marks_dir(work: &Path) -> Result<PathBuf> {
2139 work_directory(work, "marks")
2140}
2141
2142fn work_directory(work: &Path, name: &str) -> Result<PathBuf> {
2143 let path = work.join(name);
2144 match fs::symlink_metadata(&path) {
2145 Ok(found) if found.is_dir() => {}
2146 Ok(_) => bail!(
2147 "{} is in the way: the working directory needs a directory of that name, and \
2148 this is not one. Move it, or choose another --work-dir",
2149 path.display()
2150 ),
2151 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
2152 fs::create_dir(&path).with_context(|| format!("creating {}", path.display()))?
2153 }
2154 Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
2155 }
2156 Ok(path)
2157}
2158
2159fn reserve_file(dir: &Path, label: &str, runs: &std::sync::atomic::AtomicUsize) -> Result<PathBuf> {
2168 let dir = std::path::absolute(dir).unwrap_or(dir.to_path_buf());
2171 loop {
2172 let mark = dir.join(format!(
2173 "tmt-{label}-{}-{}",
2174 std::process::id(),
2175 runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
2176 ));
2177 match fs::OpenOptions::new()
2178 .write(true)
2179 .create_new(true)
2180 .open(&mark)
2181 {
2182 Ok(_) => return Ok(mark),
2183 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
2184 Err(err) => {
2186 return Err(err).with_context(|| format!("creating {}", mark.display()));
2187 }
2188 }
2189 }
2190}
2191
2192fn run_source_tests(binaries: &[&TestBinary]) -> Result<Outcome> {
2193 for bin in binaries {
2194 bin.warn_timeout_conflict(None);
2195 let outcome = run_binary(
2196 bin,
2197 None,
2198 &[],
2199 bin.mutant_limit(bin.baseline),
2200 RunOutput::FirstFailure,
2201 1,
2202 )?;
2203 if outcome != Outcome::Pass {
2204 return Ok(outcome);
2205 }
2206 }
2207 Ok(Outcome::Pass)
2208}
2209
2210fn observe_witness(
2211 baseline: &TestBinary,
2212 exe: PathBuf,
2213 wrapper: Option<&Path>,
2214 scenario: &witness::Scenario,
2215 name: &str,
2216 compares: bool,
2217) -> Result<Option<witness::Observation>> {
2218 use std::io::Read as _;
2219 let test_name = scenario.test_name(name);
2220 let test = TestBinary {
2221 name: test_name.clone(),
2222 cwd: baseline.cwd.clone(),
2223 marks: baseline.marks.clone(),
2224 git_ceiling: baseline.git_ceiling.clone(),
2225 work_lock: baseline.work_lock.clone(),
2226 tests: BTreeSet::new(),
2227 runner: Runner::Isolated {
2228 exe,
2229 test: test_name,
2230 ignored: false,
2231 wrapper: wrapper.map(Path::to_path_buf),
2232 },
2233 baseline: baseline.baseline,
2234 untraced_baseline: None,
2235 timeout_diagnostic: std::sync::Once::new(),
2236 traced: Duration::ZERO,
2237 timeout: baseline.timeout,
2238 wrapper_grace: baseline.wrapper_grace,
2239 report_slow: false,
2240 filtered_timings: Default::default(),
2241 trace: Trace::default(),
2242 effects_baseline: std::sync::OnceLock::new(),
2243 };
2244 static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2245 let path = reserve_file(&test.marks, "witness", &RUNS)?;
2246 let result = (|| {
2247 let Some(output) = path.to_str() else {
2248 return Ok(None);
2249 };
2250 if run_binary(
2251 &test,
2252 None,
2253 &[(witness::OUTPUT_ENV, output)],
2254 test.mutant_limit(test.baseline),
2255 RunOutput::Quiet,
2256 1,
2257 )? != Outcome::Pass
2258 {
2259 return Ok(None);
2260 }
2261 let mut text = String::new();
2262 const MAX_OBSERVATION: u64 = 2048;
2263 fs::File::open(&path)?
2264 .take(MAX_OBSERVATION + 1)
2265 .read_to_string(&mut text)?;
2266 Ok((text.len() <= MAX_OBSERVATION as usize)
2267 .then(|| scenario.observation(&text, compares))
2268 .flatten())
2269 })();
2270 release_mark(&path)?;
2271 result
2272}
2273
2274fn candidate_edit(
2275 file: &SourceFile,
2276 start: usize,
2277 end: usize,
2278 replacement: String,
2279) -> report::CandidateEdit {
2280 let (line, column) = file.lines.position(&file.original, start);
2281 report::CandidateEdit {
2282 file: file.display.clone(),
2283 line,
2284 column,
2285 start,
2286 end,
2287 before: file.original[start..end].to_string(),
2288 replacement,
2289 }
2290}
2291
2292fn witness_location(source: &SourceFile, candidate: &witness::Candidate) -> report::Location {
2293 let span = &candidate.edits[0].span;
2294 let (line, column) = source.lines.position(&source.original, span.start);
2295 report::Location {
2296 file: source.display.clone(),
2297 line,
2298 column,
2299 code: report::one_line(&source.original[span.clone()]),
2300 ..Default::default()
2301 }
2302}
2303
2304#[derive(Serialize, Deserialize)]
2305#[serde(rename_all = "snake_case")]
2306enum WitnessTrial {
2307 Inapplicable,
2308 Unviable,
2309 Evaluated(Outcome),
2310}
2311
2312struct WitnessSurvivor<'a> {
2313 candidate: &'a witness::Candidate,
2314 at: report::Location,
2315 existing: Option<usize>,
2316 scenarios: Vec<(&'a witness::Scenario, &'a TestBinary)>,
2317}
2318
2319struct SharedWitness {
2320 value: String,
2321 name: String,
2322 tests: std::rc::Rc<[witness::Edit]>,
2323}
2324
2325fn shared_witnesses(
2326 source: &str,
2327 survivors: &[WitnessSurvivor<'_>],
2328 wrapper: Option<&Path>,
2329 compile: impl Fn(&[witness::Edit]) -> Result<Option<PathBuf>>,
2330 note: impl Fn(&str),
2331) -> Result<Vec<Option<SharedWitness>>> {
2332 let mut originals: Vec<_> = (0..survivors.len()).map(|_| None).collect();
2333 if wrapper.is_some() {
2335 return Ok(originals);
2336 }
2337 let inputs: Vec<_> = survivors
2340 .iter()
2341 .enumerate()
2342 .filter_map(|(index, survivor)| {
2343 let (scenario, runner) = *survivor.scenarios.first()?;
2344 Some((
2345 index,
2346 scenario,
2347 runner,
2348 format!("{}_{index}", witness::TEST_NAME),
2349 ))
2350 })
2351 .collect();
2352 for batch in inputs.chunks(32).filter(|batch| batch.len() > 1) {
2353 note(&format!(
2354 "sharing a build for {} original witness inputs",
2355 batch.len()
2356 ));
2357 let tests: Vec<_> = batch
2358 .iter()
2359 .map(|(_, scenario, _, name)| scenario.test_edit(source, name, None))
2360 .collect();
2361 let Some(exe) = compile(&tests)? else {
2362 note("shared witness build failed, trying inputs individually");
2363 continue;
2364 };
2365 let observed: Vec<_> = batch
2366 .iter()
2367 .filter_map(|(index, scenario, runner, name)| {
2368 let value = observe_witness(runner, exe.clone(), wrapper, scenario, name, false)
2369 .ok()??
2370 .value;
2371 witness::is_expected_literal(&value)
2372 .then_some((*index, *scenario, *runner, name, value))
2373 })
2374 .collect();
2375 if observed.is_empty() {
2376 continue;
2377 }
2378 let tests: std::rc::Rc<[_]> = observed
2379 .iter()
2380 .map(|(_, scenario, _, name, value)| scenario.test_edit(source, name, Some(value)))
2381 .collect();
2382 let Some(exe) = compile(&tests)? else {
2383 note("shared witness build failed, trying inputs individually");
2384 continue;
2385 };
2386 for (index, scenario, runner, name, value) in observed {
2387 let checked = observe_witness(runner, exe.clone(), wrapper, scenario, name, true);
2388 if checked.is_ok_and(|value_read| {
2389 value_read
2390 .is_some_and(|read| read.equals_expected == Some(true) && read.value == value)
2391 }) {
2392 originals[index] = Some(SharedWitness {
2393 value,
2394 name: name.clone(),
2395 tests: tests.clone(),
2396 });
2397 }
2398 }
2399 }
2400 Ok(originals)
2401}
2402
2403fn release_mark(mark: &Path) -> Result<bool> {
2407 match fs::remove_file(mark) {
2408 Ok(()) => Ok(false),
2409 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(true),
2410 Err(err) => Err(err).with_context(|| {
2411 format!(
2412 "removing {}: cannot tell whether the tests ran the mutant to the end",
2413 mark.display()
2414 )
2415 }),
2416 }
2417}
2418
2419fn is_failure_line(line: &str) -> bool {
2421 line.starts_with("test ") && line.ends_with(" ... FAILED")
2422}
2423
2424fn requested_scope(
2427 options: &Options,
2428 workspace: &Path,
2429 package_dir: &Path,
2430 copy: &Path,
2431) -> Result<Option<Scope>> {
2432 if options.since.is_none() && options.lines.is_empty() {
2433 return Ok(None);
2434 }
2435 let prefix = package_dir.strip_prefix(copy).unwrap_or(Path::new(""));
2437 let lines: Vec<String> = options
2438 .lines
2439 .iter()
2440 .map(|spec| normalize(&prefix.join(spec)).to_string_lossy().into_owned())
2441 .collect();
2442 let mut scope = Scope::parse_lines(&lines)?;
2443 if let Some(revision) = &options.since {
2444 let git = |args: &[&str]| -> Result<String> {
2445 let output = Command::new("git")
2446 .arg("-C")
2447 .arg(workspace)
2448 .args(args)
2449 .output()
2450 .context("running git")?;
2451 if !output.status.success() {
2452 bail!(
2453 "git {} failed: {}",
2454 args.join(" "),
2455 String::from_utf8_lossy(&output.stderr).trim()
2456 );
2457 }
2458 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
2459 };
2460 scope.merge(Scope::from_diff(&git(&[
2462 "diff",
2463 "-U0",
2464 "--no-color",
2465 "--no-ext-diff",
2466 "--relative",
2467 "--src-prefix=a/",
2468 "--dst-prefix=b/",
2469 revision,
2470 "--",
2471 ])?));
2472 for file in git(&["ls-files", "--others", "--exclude-standard"])?.lines() {
2473 scope.add_whole_file(file);
2474 }
2475 }
2476 Ok(Some(scope))
2477}
2478
2479fn blame_error(
2483 error: &CompileError,
2484 files: &[SourceFile],
2485 copy: &Path,
2486 disabled: &HashSet<u32>,
2487) -> Vec<u32> {
2488 let enabled = |id: u32| !disabled.contains(&id);
2489 let file_of = |span: &ErrorSpan| {
2490 let path = copy.join(&span.file);
2491 files.iter().find(|f| f.path == path)
2492 };
2493 let innermost = |spans: &[ErrorSpan]| -> Vec<u32> {
2494 let mut ids = vec![];
2495 for span in spans {
2496 if let Some(file) = file_of(span) {
2497 let rendered = file.rendered.as_ref().expect("rendered before building");
2498 match rendered
2500 .inserted_by(span.byte_start)
2501 .filter(|id| enabled(*id))
2502 {
2503 Some(id) => ids.push(id),
2504 None => ids.extend(instrument::blame(
2505 &file.sites,
2506 &enabled,
2507 rendered.to_original(span.byte_start),
2508 )),
2509 }
2510 }
2511 }
2512 ids
2513 };
2514 let widen = |lines: usize| -> Vec<u32> {
2515 let mut ids = vec![];
2516 for span in &error.primary {
2517 if let Some(file) = file_of(span) {
2518 ids.extend(
2519 file.sites
2520 .iter()
2521 .filter(|s| enabled(s.id) && s.line.abs_diff(span.line) <= lines)
2522 .map(|s| s.id),
2523 );
2524 }
2525 }
2526 ids
2527 };
2528 [&error.primary, &error.secondary]
2529 .into_iter()
2530 .map(|spans| innermost(spans))
2531 .chain([0, NEARBY_LINES, usize::MAX].into_iter().map(widen))
2532 .find(|ids| !ids.is_empty())
2533 .unwrap_or_default()
2534}
2535
2536fn domain_of(
2538 literal: LiteralSide,
2539 bounds: Option<&crate::trace::TypeBounds>,
2540) -> Option<(i128, i128)> {
2541 let bounds = bounds?;
2542 match literal {
2543 LiteralSide::Rhs(k) => Some((bounds.lhs.0.checked_sub(k)?, bounds.lhs.1.checked_sub(k)?)),
2544 LiteralSide::Lhs(k) => Some((k.checked_sub(bounds.rhs.1)?, k.checked_sub(bounds.rhs.0)?)),
2545 LiteralSide::None => None,
2546 }
2547}
2548
2549struct Session {
2550 progress: bool,
2551 serial_timeout_rechecks: bool,
2552 package_dir: PathBuf,
2553 binaries: Vec<TestBinary>,
2554}
2555
2556struct Job {
2558 site: u32,
2559 mutation: Mutation,
2560 tests: Vec<(usize, Option<Vec<String>>)>,
2562}
2563
2564fn jobs_for_site(jobs: &[Job], site: u32) -> std::ops::Range<usize> {
2566 let first = jobs.partition_point(|job| job.site < site);
2567 let count = jobs[first..].partition_point(|job| job.site == site);
2568 first..first + count
2569}
2570
2571#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2572struct JobResult {
2573 first_pass_timeout: bool,
2574 unconfirmed_timeout: bool,
2575 survived: Option<Vec<String>>,
2577 timed_out: bool,
2578 unable: bool,
2580}
2581
2582impl report::TimeoutRechecks {
2583 fn include(&mut self, result: &JobResult) {
2584 if result.first_pass_timeout {
2585 self.first_pass += 1;
2586 if result.unconfirmed_timeout || result.unable {
2587 self.unconfirmed += 1;
2588 } else if result.timed_out {
2589 self.confirmed += 1;
2590 } else {
2591 self.recovered += 1;
2592 }
2593 }
2594 }
2595}
2596
2597impl JobResult {
2598 fn progress_outcome(&self) -> progress::Outcome {
2599 if self.unable {
2600 progress::Outcome::Unable
2601 } else if self.timed_out {
2602 progress::Outcome::TimedOut
2603 } else if self.survived.is_some() {
2604 progress::Outcome::Survived
2605 } else {
2606 progress::Outcome::Failed
2607 }
2608 }
2609}
2610
2611fn tests_where<T>(
2613 per_test: Option<&BTreeMap<String, T>>,
2614 pick: impl Fn(&T) -> bool,
2615) -> BTreeSet<String> {
2616 per_test
2617 .into_iter()
2618 .flatten()
2619 .filter(|(_, obs)| pick(obs))
2620 .map(|(test, _)| test.clone())
2621 .collect()
2622}
2623
2624type InfectedTests<'a> = Box<dyn Fn(&TestBinary, Mutation) -> BTreeSet<String> + 'a>;
2625type ReachingTests<'a> = Box<dyn Fn(&TestBinary) -> BTreeSet<String> + 'a>;
2626
2627struct PlannedGap {
2629 finding: Finding,
2630 survivors: Vec<Mutation>,
2632 constant_expr: Option<(usize, usize)>,
2636}
2637
2638fn core_range(start: usize, text: &str) -> (usize, usize) {
2640 let (mut from, mut to) = (0, text.len());
2641 loop {
2642 let inner = &text[from..to];
2643 let trimmed = inner.trim();
2644 from += inner.len() - inner.trim_start().len();
2645 to = from + trimmed.len();
2646 let wrapped = trimmed.starts_with('(') && trimmed.ends_with(')') && {
2647 let mut depth = 0usize;
2649 trimmed.char_indices().all(|(i, c)| {
2650 match c {
2651 '(' => depth += 1,
2652 ')' => depth -= 1,
2653 _ => {}
2654 }
2655 depth > 0 || i == trimmed.len() - 1
2656 })
2657 };
2658 if !wrapped {
2659 return (start + from, start + to);
2660 }
2661 from += 1;
2662 to -= 1;
2663 }
2664}
2665
2666struct SitePlan<'a> {
2668 gaps: Vec<PlannedGap>,
2670 cannot_differ: bool,
2673 constant: bool,
2675 run: Vec<Mutation>,
2677 infected: InfectedTests<'a>,
2679 reaching: ReachingTests<'a>,
2681}
2682
2683enum Planned<'a> {
2684 Unreached,
2685 NotEvaluated,
2687 Nothing,
2689 Plan(SitePlan<'a>),
2690}
2691
2692type ConfirmedGap = (Finding, Vec<usize>, Option<(usize, usize)>);
2694
2695struct SiteWork<'a> {
2697 file: &'a str,
2698 site: &'a Site,
2699 gaps: Vec<ConfirmedGap>,
2700 constant: bool,
2701 cannot_differ: bool,
2702 runs: Vec<(Mutation, usize)>,
2703}
2704
2705impl Session {
2706 fn note(&self, text: &str) {
2707 if self.progress {
2708 eprintln!("tmt: {text}");
2709 }
2710 }
2711
2712 fn merged<T: Default + Copy>(
2713 &self,
2714 select: impl Fn(&Trace) -> Option<&BTreeMap<String, T>>,
2715 merge: impl Fn(&mut T, &T),
2716 ) -> T {
2717 let mut all = T::default();
2718 for obs in self
2719 .binaries
2720 .iter()
2721 .filter_map(|b| select(&b.trace))
2722 .flat_map(|t| t.values())
2723 {
2724 merge(&mut all, obs);
2725 }
2726 all
2727 }
2728
2729 fn plan<'a>(&'a self, file: &str, site: &'a Site, verify: bool) -> Planned<'a> {
2730 let id = site.id;
2731 let reach_plan = |mutation: Mutation| SitePlan {
2732 gaps: vec![],
2733 constant: false,
2734 cannot_differ: false,
2735 run: vec![mutation],
2736 infected: Box::new(move |bin, _| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
2737 reaching: Box::new(move |bin| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
2738 };
2739 let reached = || {
2740 self.binaries
2741 .iter()
2742 .any(|b| b.trace.reach.contains_key(&id))
2743 };
2744 Planned::Plan(match &site.kind {
2745 SiteKind::Stmt
2746 | SiteKind::Neg { .. }
2747 | SiteKind::Field { .. }
2748 | SiteKind::Body { .. }
2749 if reached() =>
2750 {
2751 reach_plan(Mutation::Delete)
2752 }
2753 SiteKind::Stmt
2754 | SiteKind::Neg { .. }
2755 | SiteKind::Field { .. }
2756 | SiteKind::Body { .. } => return Planned::Unreached,
2757 SiteKind::Guard { can_be_false } => {
2758 let can_be_false = *can_be_false;
2759 let allowed = move |m: &Mutation| can_be_false || *m != Mutation::Const(false);
2760 let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
2761 let guard_plan = plan::plan_return(&merged);
2762 if guard_plan.unreached {
2763 return Planned::Unreached;
2764 }
2765 let gaps = guard_plan
2766 .always
2767 .filter(|always| allowed(&Mutation::Const(*always)))
2768 .map(|always| PlannedGap {
2769 finding: report::guard_gap_finding(file, site, always, verify),
2770 survivors: vec![Mutation::Const(always)],
2771 constant_expr: Some((site.start, site.end)),
2773 })
2774 .into_iter()
2775 .collect();
2776 SitePlan {
2777 constant: false,
2778 cannot_differ: false,
2779 gaps,
2780 run: guard_plan.run.into_iter().filter(allowed).collect(),
2781 infected: Box::new(move |bin, m| {
2782 tests_where(bin.trace.returns.get(&id), |obs| match m {
2783 Mutation::Const(value) => obs.infected_by_const(value),
2784 _ => obs.reached(),
2785 })
2786 }),
2787 reaching: Box::new(move |bin| {
2788 tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
2789 }),
2790 }
2791 }
2792 SiteKind::Arm { .. } if reached() => reach_plan(Mutation::Delete),
2793 SiteKind::Arm { .. } => return Planned::Unreached,
2794 SiteKind::Not { .. } if reached() => reach_plan(Mutation::DropNot),
2795 SiteKind::Range { .. } if reached() => {
2798 if self
2799 .binaries
2800 .iter()
2801 .any(|b| b.trace.ranges_at_top.contains(&id))
2802 {
2803 return Planned::NotEvaluated;
2804 }
2805 reach_plan(Mutation::RangeEnd)
2806 }
2807 SiteKind::Not { .. } | SiteKind::Range { .. } => {
2810 if self
2811 .merged(|t| t.arith.get(&id), plan::ArithObs::merge)
2812 .opaque
2813 {
2814 return Planned::Nothing;
2815 }
2816 return Planned::Unreached;
2817 }
2818 SiteKind::Cmp { op, literal, .. } => {
2819 let op = *op;
2820 let mut merged = Obs::default();
2821 for bin in &self.binaries {
2822 merged.merge(&bin.trace.merged(id));
2823 }
2824 let bounds = self.binaries.iter().find_map(|b| b.trace.bounds.get(&id));
2825 let cmp_plan = plan::plan_cmp(op, &merged, domain_of(*literal, bounds));
2826 let mut gaps = vec![];
2827 let mut constant = false;
2828 match &cmp_plan.gap {
2829 Some(plan::InputGap::Unreached) => return Planned::Unreached,
2830 Some(gap) => {
2831 constant = matches!(gap, plan::InputGap::OneSided { .. });
2832 if let Some(finding) =
2833 report::input_gap_finding(file, site, gap, &merged, verify)
2834 {
2835 gaps.push(PlannedGap {
2836 finding,
2837 survivors: gap.survivors(),
2838 constant_expr: None,
2839 });
2840 }
2841 }
2842 None => {}
2843 }
2844 SitePlan {
2845 gaps,
2846 constant,
2847 cannot_differ: cmp_plan.cannot_differ,
2848 run: cmp_plan.run,
2849 infected: Box::new(move |bin, m| {
2850 tests_where(bin.trace.cmp.get(&id), |obs| plan::infects(op, m, obs))
2851 }),
2852 reaching: Box::new(move |bin| {
2853 tests_where(bin.trace.cmp.get(&id), Obs::reached)
2854 }),
2855 }
2856 }
2857 SiteKind::Logic {
2858 and,
2859 lhs,
2860 rhs,
2861 gap: op_gap,
2862 } => {
2863 let and = *and;
2864 let lhs_range = core_range(site.start, lhs);
2865 let rhs_range = core_range(op_gap.1, rhs);
2866 let merged = self.merged(|t| t.logic.get(&id), plan::LogicObs::merge);
2867 let logic_plan = plan::plan_logic(and, &merged);
2868 if logic_plan.gaps.contains(&plan::LogicGap::Unreached) {
2869 return Planned::Unreached;
2870 }
2871 let gaps: Vec<_> = logic_plan
2872 .gaps
2873 .iter()
2874 .filter_map(|gap| {
2875 let (mutation, operand) = match gap {
2878 plan::LogicGap::RhsNeverDecides => (Mutation::LogicDropRhs, rhs_range),
2879 _ => (Mutation::LogicDropLhs, lhs_range),
2880 };
2881 Some(PlannedGap {
2882 finding: report::logic_gap_finding(file, site, *gap, verify)?,
2883 survivors: vec![mutation],
2884 constant_expr: Some(operand),
2885 })
2886 })
2887 .collect();
2888 SitePlan {
2889 constant: merged.constant_value(and).is_some(),
2890 cannot_differ: false,
2891 gaps,
2892 run: logic_plan.run,
2893 infected: Box::new(move |bin, m| {
2894 tests_where(bin.trace.logic.get(&id), |obs| {
2895 plan::logic_infects(and, m, obs)
2896 })
2897 }),
2898 reaching: Box::new(move |bin| {
2899 tests_where(bin.trace.logic.get(&id), plan::LogicObs::reached)
2900 }),
2901 }
2902 }
2903 SiteKind::Arith { .. } | SiteKind::MinMax { .. } => {
2904 let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
2907 let mutations: Vec<(Mutation, plan::ArithObs)> = match &site.kind {
2908 SiteKind::MinMax { .. } => vec![(Mutation::MinMax, merged)],
2909 SiteKind::Arith { op, assign, .. } if op.second(*assign).is_some() => vec![
2910 (Mutation::ArithSwap, merged),
2911 (Mutation::ArithSwap2, merged.second()),
2912 ],
2913 _ => vec![(Mutation::ArithSwap, merged)],
2914 };
2915 let (mut gaps, mut run) = (vec![], vec![]);
2916 for (mutation, seen) in mutations {
2917 match plan::plan_arith(&seen) {
2918 plan::ArithPlan::Unreached => return Planned::Unreached,
2919 plan::ArithPlan::Opaque => return Planned::Nothing,
2921 plan::ArithPlan::NeverDiffers => {
2922 let finding = if mutation == Mutation::MinMax {
2923 report::min_max_gap_finding(file, site, verify)
2924 } else {
2925 report::arith_gap_finding(file, site, mutation, verify)
2926 };
2927 gaps.extend(finding.map(|finding| PlannedGap {
2928 finding,
2929 survivors: vec![mutation],
2930 constant_expr: None,
2931 }));
2932 }
2933 plan::ArithPlan::Run => run.push(mutation),
2934 }
2935 }
2936 SitePlan {
2937 gaps,
2938 constant: false,
2939 cannot_differ: false,
2940 run,
2941 infected: Box::new(move |bin, m| {
2942 tests_where(bin.trace.arith.get(&id), |obs| obs.infected_by(m))
2943 }),
2944 reaching: Box::new(move |bin| {
2945 tests_where(bin.trace.arith.get(&id), |obs| obs.same || obs.differs)
2946 }),
2947 }
2948 }
2949 SiteKind::Return {
2950 sole_expr, option, ..
2951 } => {
2952 let sole_expr = *sole_expr;
2953 let is_option = option.is_some();
2954 let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
2955 let return_plan = if is_option {
2956 plan::plan_option_return(&merged)
2957 } else {
2958 plan::plan_return(&merged)
2959 };
2960 if return_plan.unreached {
2961 return Planned::Unreached;
2962 }
2963 let gaps: Vec<_> = return_plan
2964 .always
2965 .and_then(|always| {
2966 Some(PlannedGap {
2967 finding: report::return_gap_finding(file, site, always, verify)?,
2968 survivors: vec![Mutation::Const(always)],
2969 constant_expr: sole_expr,
2971 })
2972 })
2973 .into_iter()
2974 .collect();
2975 SitePlan {
2976 constant: false,
2977 cannot_differ: false,
2978 gaps,
2979 run: return_plan.run,
2980 infected: Box::new(move |bin, m| {
2981 tests_where(bin.trace.returns.get(&id), |obs| match m {
2982 Mutation::Const(value) => obs.infected_by_const(value),
2983 _ => obs.reached(),
2984 })
2985 }),
2986 reaching: Box::new(move |bin| {
2987 tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
2988 }),
2989 }
2990 }
2991 })
2992 }
2993
2994 fn job(
2995 &self,
2996 site: u32,
2997 mutation: Mutation,
2998 tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>,
2999 ) -> Job {
3000 let tests = self
3001 .binaries
3002 .iter()
3003 .enumerate()
3004 .filter_map(|(index, bin)| {
3005 let tests = tests_of(bin);
3006 if tests.is_empty() {
3007 return None;
3008 }
3009 let filter = match bin.runner {
3010 Runner::Exe(_) => test_filter(&tests, &bin.tests),
3011 Runner::Doc { .. } | Runner::Isolated { .. } | Runner::Nextest { .. } => None,
3012 };
3013 Some((index, filter))
3014 })
3015 .collect();
3016 Job {
3017 site,
3018 mutation,
3019 tests,
3020 }
3021 }
3022
3023 fn run_job(&self, job: &Job, sharing: usize) -> Result<JobResult> {
3026 let spec = format!("{}:{}", job.site, job.mutation.encode());
3027 let mut passed = vec![];
3028 let mut tests: Vec<&(usize, Option<Vec<String>>)> = job.tests.iter().collect();
3030 tests.sort_by_key(|(index, _)| self.binaries[*index].baseline);
3031 for (index, filter) in tests {
3032 let bin = &self.binaries[*index];
3033 let outcome = run_binary(
3034 bin,
3035 filter.as_deref(),
3036 &[("TMT_MUTANT", &spec)],
3037 bin.filtered_limit(filter.as_deref(), false),
3038 RunOutput::FirstFailure,
3039 sharing,
3040 )?;
3041 if outcome != Outcome::Pass {
3042 return Ok(JobResult {
3043 first_pass_timeout: false,
3044 unconfirmed_timeout: false,
3045 survived: None,
3046 timed_out: outcome == Outcome::Timeout,
3047 unable: outcome == Outcome::Unable,
3048 });
3049 }
3050 match filter {
3051 Some(names) => passed.extend(names.iter().cloned()),
3052 None if matches!(bin.runner, Runner::Isolated { .. }) => {
3053 passed.push(bin.name.clone())
3054 }
3055 None => passed.push(format!("all tests of `{}`", bin.name)),
3056 }
3057 }
3058 Ok(JobResult {
3059 first_pass_timeout: false,
3060 unconfirmed_timeout: false,
3061 survived: Some(passed),
3062 timed_out: false,
3063 unable: false,
3064 })
3065 }
3066
3067 fn trace_job(
3070 &self,
3071 job: &Job,
3072 scratch: &Path,
3073 sharing: usize,
3074 ) -> Result<BTreeMap<String, BTreeSet<Change>>> {
3075 let spec = format!("{}:{}", job.site, job.mutation.encode());
3076 let mut all: BTreeMap<String, BTreeSet<Change>> = BTreeMap::new();
3077 for (index, filter) in &job.tests {
3078 let bin = &self.binaries[*index];
3079 let path = scratch.join(format!("effects-{}-{index}.tsv", job.site));
3080 let _ = fs::remove_file(&path);
3081 let trace_env = path.to_string_lossy().into_owned();
3082 let outcome = run_binary(
3083 bin,
3084 filter.as_deref(),
3085 &[("TMT_MUTANT", &spec), ("TMT_TRACE", &trace_env)],
3086 bin.filtered_limit(filter.as_deref(), true),
3087 RunOutput::Quiet,
3088 sharing,
3089 )?;
3090 let text = fs::read_to_string(&path).unwrap_or_default();
3091 let _ = fs::remove_file(&path);
3092 if outcome != Outcome::Pass {
3093 continue; }
3095 let mutated = Trace::parse(&text);
3096 let ran: Option<BTreeSet<String>> =
3097 filter.as_ref().map(|names| names.iter().cloned().collect());
3098 let baseline = bin
3099 .effects_baseline
3100 .get_or_init(|| propagation::BaselineIndex::new(&bin.trace));
3101 for (test, found) in baseline.changes(&mutated, ran.as_ref(), job.site) {
3102 all.entry(test).or_default().extend(found);
3103 }
3104 }
3105 Ok(all)
3106 }
3107
3108 fn run_jobs(
3114 &self,
3115 jobs: &[Job],
3116 workers: usize,
3117 label: &str,
3118 checkpoint: Option<&Phase<'_>>,
3119 ) -> Result<Vec<JobResult>> {
3120 if self
3121 .binaries
3122 .first()
3123 .is_some_and(|bin| bin.timeout.is_some())
3124 {
3125 for (index, filter) in jobs.iter().flat_map(|job| &job.tests) {
3126 self.binaries[*index].warn_timeout_conflict(filter.as_deref());
3127 }
3128 }
3129 let run = |index: usize, sharing| self.run_job(&jobs[index], sharing);
3130 evaluate_jobs(
3131 jobs.len(),
3132 workers,
3133 self.serial_timeout_rechecks,
3134 self.progress,
3135 label,
3136 checkpoint,
3137 &run,
3138 )
3139 }
3140}
3141
3142fn evaluate_jobs(
3143 count: usize,
3144 workers: usize,
3145 serial_rechecks: bool,
3146 progress_enabled: bool,
3147 label: &str,
3148 checkpoint: Option<&Phase<'_>>,
3149 run: &(impl Fn(usize, usize) -> Result<JobResult> + Sync),
3150) -> Result<Vec<JobResult>> {
3151 let sharing = workers.clamp(1, count.max(1));
3152 let mut results = progress::track(progress_enabled, label, count, |progress| {
3153 run_pool(count, workers, |index| {
3154 if let Some(cached) = checkpoint
3155 .map(|phase| phase.get::<JobResult>(index))
3156 .transpose()?
3157 .flatten()
3158 {
3159 progress.complete(cached.progress_outcome());
3160 return Ok((cached, false));
3161 }
3162 let mut result = run(index, sharing)?;
3163 if sharing > 1 && result.timed_out {
3164 result.first_pass_timeout = true;
3165 result.unconfirmed_timeout = true;
3166 }
3167 let pending = result.unconfirmed_timeout && serial_rechecks;
3168 if !pending {
3169 if let Some(phase) = checkpoint {
3170 phase.record(index, &result)?;
3171 }
3172 progress.complete(result.progress_outcome());
3173 }
3174 Ok((result, pending))
3175 })
3176 })?;
3177 let pending: Vec<_> = results
3178 .iter()
3179 .enumerate()
3180 .filter_map(|(index, (_, pending))| pending.then_some(index))
3181 .collect();
3182 if !pending.is_empty() && progress_enabled {
3183 eprintln!(
3184 "tmt: {label}: {} first-pass timeouts, {} pending serial rechecks",
3185 pending.len(),
3186 if serial_rechecks { pending.len() } else { 0 }
3187 );
3188 }
3189 if serial_rechecks {
3190 progress::track_timeout_rechecks(progress_enabled, pending.len(), |progress| {
3191 for index in pending {
3192 let mut confirmed = run(index, 1)?;
3193 confirmed.first_pass_timeout = true;
3194 let outcome = if confirmed.timed_out {
3195 progress::Outcome::TimedOut
3196 } else if confirmed.unable {
3197 progress::Outcome::Unable
3198 } else {
3199 progress::Outcome::Survived
3200 };
3201 if let Some(phase) = checkpoint {
3202 phase.record(index, &confirmed)?;
3203 }
3204 results[index] = (confirmed, false);
3205 progress.complete(outcome);
3206 }
3207 Ok::<_, anyhow::Error>(())
3208 })?;
3209 }
3210 if let Some(phase) = checkpoint {
3211 phase.finish()?;
3212 }
3213 Ok(results.into_iter().map(|(result, _)| result).collect())
3214}
3215
3216fn run_pool<T: Send>(
3219 count: usize,
3220 workers: usize,
3221 work: impl Fn(usize) -> Result<T> + Sync,
3222) -> Result<Vec<T>> {
3223 if count == 0 {
3224 return Ok(vec![]);
3225 }
3226 if workers <= 1 || count == 1 {
3227 return std::thread::scope(|scope| {
3228 scope
3229 .spawn(|| (0..count).map(&work).collect())
3230 .join()
3231 .expect("worker panicked")
3232 });
3233 }
3234 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
3235 let next = AtomicUsize::new(0);
3236 let stop = AtomicBool::new(false);
3237 let done: Vec<Vec<(usize, Result<T>)>> = std::thread::scope(|scope| {
3238 let handles: Vec<_> = (0..workers.min(count))
3239 .map(|_| {
3240 scope.spawn(|| {
3241 let mut mine = vec![];
3242 while !stop.load(Ordering::Acquire) {
3243 let index = next.fetch_add(1, Ordering::Relaxed);
3244 if index >= count {
3245 break;
3246 }
3247 let result = work(index);
3248 if result.is_err() {
3249 stop.store(true, Ordering::Release);
3250 }
3251 mine.push((index, result));
3252 }
3253 mine
3254 })
3255 })
3256 .collect();
3257 handles
3258 .into_iter()
3259 .map(|handle| handle.join().expect("worker panicked"))
3260 .collect()
3261 });
3262 let mut ordered: Vec<Option<Result<T>>> = (0..count).map(|_| None).collect();
3263 for (index, result) in done.into_iter().flatten() {
3264 ordered[index] = Some(result);
3265 }
3266 ordered.into_iter().flatten().collect()
3267}
3268
3269impl std::str::FromStr for report::Shard {
3270 type Err = anyhow::Error;
3271
3272 fn from_str(text: &str) -> Result<Self> {
3273 let (index, count) = text.split_once('/').context("expected a shard index K/N")?;
3274 let index: usize = index.parse().context("invalid shard index")?;
3275 let count: usize = count.parse().context("invalid shard count")?;
3276 if index >= count {
3277 bail!("shard index must be less than the shard count");
3278 }
3279 Ok(Self {
3280 index,
3281 count,
3282 round_robin: false,
3283 })
3284 }
3285}
3286
3287impl report::Shard {
3288 fn contains(self, candidate: usize, candidates: usize) -> bool {
3289 candidate < candidates
3290 && (if self.round_robin {
3291 candidate % self.count
3292 } else {
3293 candidate / candidates.div_ceil(self.count)
3294 }) == self.index
3295 }
3296}
3297
3298fn cargo_metadata(dir: &Path, cargo: &CargoConfig) -> Result<Metadata> {
3299 let output = Command::new("cargo")
3300 .args(["metadata", "--no-deps", "--format-version", "1"])
3301 .args(cargo.flags())
3302 .current_dir(dir)
3303 .output()
3304 .context("running cargo metadata")?;
3305 if !output.status.success() {
3306 bail!(
3307 "cargo metadata failed:\n{}",
3308 String::from_utf8_lossy(&output.stderr)
3309 );
3310 }
3311 serde_json::from_slice(&output.stdout).context("parsing cargo metadata")
3312}
3313
3314#[derive(Clone, Copy)]
3315struct WorkspaceShard {
3316 offset: usize,
3317 total: usize,
3318 member_total: usize,
3319}
3320
3321struct CatalogueSnapshot {
3322 path: PathBuf,
3323 ready: std::cell::Cell<bool>,
3324 _lock: WorkLock,
3325}
3326
3327struct WorkspaceBatch<'a> {
3328 metadata: &'a Metadata,
3329 work: &'a Path,
3330 catalogue: Option<CatalogueSnapshot>,
3331}
3332
3333pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
3335 let mut reports = vec![];
3336 run_packages_each(options, names, |name, result| {
3337 reports.push((name, result));
3338 Ok(())
3339 })?;
3340 Ok(reports)
3341}
3342
3343pub fn run_packages_each(
3345 options: &Options,
3346 names: &[String],
3347 mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
3348) -> Result<()> {
3349 if options.baseline.is_some() || options.write_baseline.is_some() {
3350 bail!("baseline files require a single package");
3351 }
3352 let metadata = cargo_metadata(&options.dir, &options.cargo)?;
3353 let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
3354 let selected = if names.is_empty() {
3355 all.clone()
3356 } else {
3357 names.iter().cloned().collect()
3358 };
3359 if let Some(unknown) = selected.difference(&all).next() {
3360 bail!("no package `{unknown}` in the workspace");
3361 }
3362 let base = options
3363 .work_dir
3364 .clone()
3365 .unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
3366 fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
3367 let base = base.canonicalize()?;
3368 if metadata.workspace_root.canonicalize()?.starts_with(&base) {
3369 bail!(
3370 "the work directory {} contains the workspace",
3371 base.display()
3372 );
3373 }
3374 let catalogue = if options.list || options.shard.is_some() {
3375 let path = work_directory(&base, ".catalogue")?;
3376 Some(CatalogueSnapshot {
3377 _lock: WorkLock::take(&path)?,
3378 path,
3379 ready: std::cell::Cell::new(false),
3380 })
3381 } else {
3382 None
3383 };
3384 let batch = WorkspaceBatch {
3385 metadata: &metadata,
3386 work: &base,
3387 catalogue,
3388 };
3389 let member_options = selected.into_iter().map(|name| {
3390 let mut member = options.clone();
3391 member.package = Some(name.clone());
3392 member.work_dir = Some(base.join(&name));
3393 (name, member)
3394 });
3395 let Some(shard) = options.shard else {
3396 for (name, member) in member_options {
3397 let result = run_package(&member, Some(&batch), None);
3398 completed(name, result)?;
3399 }
3400 return Ok(());
3401 };
3402 if !options.source_only || shard.index >= shard.count {
3403 bail!("shards require --source-only and a valid shard index");
3404 }
3405 let catalogues: Vec<_> = member_options
3408 .map(|(name, member)| {
3409 let mut preview = member.clone();
3410 preview.list = true;
3411 preview.shard = None;
3412 preview.progress = false;
3413 let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
3414 let count = report.mutants.as_ref().map_or(0, Vec::len);
3415 if !member.list {
3416 report.mutants = None;
3417 }
3418 (count, report)
3419 });
3420 (name, member, catalogue)
3421 })
3422 .collect();
3423 let total = catalogues
3424 .iter()
3425 .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
3426 .map(|(count, _)| count)
3427 .sum();
3428 let mut offset = 0;
3429 for (name, member, catalogue) in catalogues {
3430 let result = catalogue.and_then(|(member_total, mut report)| {
3431 let range = WorkspaceShard {
3432 offset,
3433 total,
3434 member_total,
3435 };
3436 offset += member_total;
3437 if member.list {
3438 report.analysis.shard = Some(shard);
3439 let mut index = range.offset;
3440 report
3441 .mutants
3442 .as_mut()
3443 .expect("source catalogue")
3444 .retain(|_| {
3445 let keep = shard.contains(index, total);
3446 index += 1;
3447 keep
3448 });
3449 Ok(report)
3450 } else {
3451 run_package(&member, Some(&batch), Some(range))
3452 }
3453 });
3454 completed(name, result)?;
3455 }
3456 Ok(())
3457}
3458
3459pub fn run(options: &Options) -> Result<Report> {
3460 run_package(options, None, None)
3461}
3462
3463fn run_package(
3464 options: &Options,
3465 batch: Option<&WorkspaceBatch<'_>>,
3466 workspace_shard: Option<WorkspaceShard>,
3467) -> Result<Report> {
3468 if let Some(shard) = options.shard
3469 && (!options.source_only || shard.index >= shard.count)
3470 {
3471 bail!("shards require --source-only and a valid shard index");
3472 }
3473 let mut seen_errors = HashSet::new();
3474 let mut error_values = vec![];
3475 for expression in &options.error_values {
3476 let expression = expression.trim();
3477 if expression.chars().any(char::is_control) {
3480 bail!(
3481 "invalid --error expression {expression:?}: it has to be on one line, \
3482 without control characters"
3483 );
3484 }
3485 let parsed = syn::parse_str::<syn::Expr>(expression)
3486 .with_context(|| format!("invalid --error expression {expression:?}"))?;
3487 if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3488 error_values.push(expression);
3489 }
3490 }
3491 let selection = &options.test_selection;
3492 if options.nextest.is_some() {
3493 if !cfg!(unix) {
3494 bail!("the nextest runner is available on Unix");
3495 }
3496 if !options.source_only || options.doc || selection.enabled() {
3497 bail!(
3498 "--test-tool nextest requires --source-only; select tests through the nextest profile"
3499 );
3500 }
3501 }
3502 if options.baseline_jobs > 1 && !selection.enabled() {
3503 bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3504 }
3505 if options.doc && selection.enabled() {
3506 bail!("--doc cannot be combined with isolated test selection");
3507 }
3508 let note = |text: &str| {
3509 if options.progress {
3510 eprintln!("tmt: {text}");
3511 }
3512 };
3513 let dir = options
3514 .dir
3515 .canonicalize()
3516 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
3517
3518 let local_metadata;
3519 let metadata = if let Some(batch) = batch {
3520 batch.metadata
3521 } else {
3522 local_metadata = cargo_metadata(&dir, &options.cargo)?;
3523 &local_metadata
3524 };
3525 let catalogue = batch
3526 .and_then(|batch| batch.catalogue.as_ref())
3527 .filter(|_| options.list);
3528 let package = match &options.package {
3529 Some(name) => metadata.packages.iter().find(|p| &p.name == name),
3530 None => metadata
3531 .packages
3532 .iter()
3533 .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
3534 .or(match &metadata.packages[..] {
3535 [only] => Some(only),
3536 _ => None,
3537 }),
3538 }
3539 .ok_or_else(|| anyhow!("cannot tell which package to analyse; pass --package <name>"))?;
3540 let mut test_packages: Vec<&Package> = vec![package];
3543 for name in &options.also_test {
3544 let other = metadata
3545 .packages
3546 .iter()
3547 .find(|p| &p.name == name)
3548 .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
3549 if !test_packages.iter().any(|p| p.name == other.name) {
3550 test_packages.push(other);
3551 }
3552 }
3553 if options.test_workspace {
3554 test_packages.extend(
3555 metadata
3556 .packages
3557 .iter()
3558 .filter(|other| {
3559 !test_packages
3560 .iter()
3561 .any(|selected| selected.name == other.name)
3562 })
3563 .collect::<Vec<_>>(),
3564 );
3565 }
3566 if options.dependents {
3567 for name in dependents_of(&package.name, &metadata.packages) {
3568 if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
3569 && !test_packages.iter().any(|p| p.name == other.name)
3570 {
3571 test_packages.push(other);
3572 }
3573 }
3574 }
3575 let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
3576 let root_target = package
3577 .targets
3578 .iter()
3579 .find(|t| {
3580 is_kind(
3581 t,
3582 &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
3583 )
3584 })
3585 .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
3586 .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
3587
3588 let workspace = metadata.workspace_root.canonicalize()?;
3590 let requested_work = catalogue
3591 .map(|catalogue| &catalogue.path)
3592 .or(options.work_dir.as_ref());
3593 let work = match requested_work {
3594 Some(dir) => {
3595 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3596 dir.canonicalize()?
3597 }
3598 None => metadata.target_directory.join("tmt"),
3599 };
3600 if workspace.starts_with(&work) {
3603 bail!(
3604 "the work directory {} contains the workspace; choose a directory of its own",
3605 work.display()
3606 );
3607 }
3608 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
3609 let work = work.canonicalize()?;
3610 let work_lock = if catalogue.is_none() {
3611 Some(Arc::new(WorkLock::take(&work)?))
3612 } else {
3613 None
3614 };
3615 let copy = work.join("src");
3616 let marker = work.join(WORK_MARKER);
3617 if copy.exists() && !marker.exists() {
3618 bail!(
3619 "{} exists and was not created by tmt; refusing to delete it. \
3620 Choose another --work-dir or remove it yourself.",
3621 copy.display()
3622 );
3623 }
3624 fs::write(
3625 &marker,
3626 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
3627 )?;
3628 let target_dir = metadata.target_directory.clone();
3629 let forbidden = |path: &Path| {
3630 path == target_dir
3631 || path == work
3632 || batch.is_some_and(|batch| path == batch.work)
3633 || path.file_name().is_some_and(|n| n == ".git")
3634 || (path.parent() == Some(workspace.as_path())
3635 && path.file_name().is_some_and(|n| n == "target"))
3636 };
3637 let state = WorkCopy::open(&work, ©);
3638 let fixtures = options
3639 .copy_fixtures
3640 .iter()
3641 .map(|path| fixture_relative(path))
3642 .collect::<Result<Vec<_>>>()?;
3643 let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
3644 let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
3645 let skip = |path: &Path| {
3646 fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
3647 };
3648 if options.progress && !options.list {
3649 for path in &excluded {
3650 note(&format!(
3651 "excluded fixture {}",
3652 path.strip_prefix(&workspace).unwrap_or(path).display()
3653 ));
3654 }
3655 }
3656 if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
3657 work_directory(&work, "src")?;
3658 let visible = if options.all_files {
3659 None
3660 } else {
3661 git_visible_files(&workspace)?
3662 };
3663 match visible {
3664 Some(files) => {
3667 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
3668 note(&format!(
3669 "copied {copied} files (ignored files are left out)"
3670 ));
3671 }
3672 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
3673 }
3674 for relative in &fixtures {
3675 copy_fixture_entry(
3676 &workspace.join(relative),
3677 ©.join(relative),
3678 &workspace,
3679 &fixture_forbidden,
3680 &state,
3681 &mut BTreeSet::new(),
3682 )?;
3683 }
3684 prune(©, &state)?;
3685 if options.git_index {
3686 git_index::snapshot(&workspace, ©)?;
3687 }
3688 if !options.list {
3689 let mut manifests: Vec<&Path> = metadata
3691 .packages
3692 .iter()
3693 .map(|p| p.manifest_path.as_path())
3694 .collect();
3695 let root_manifest = metadata.workspace_root.join("Cargo.toml");
3696 manifests.push(&root_manifest);
3697 for manifest in manifests {
3698 let Ok(canonical) = manifest.canonicalize() else {
3699 continue;
3700 };
3701 let (Some(manifest_dir), Ok(relative)) =
3702 (canonical.parent(), canonical.strip_prefix(&workspace))
3703 else {
3704 continue;
3705 };
3706 let text = fs::read_to_string(&canonical)?;
3707 if let Some(rewritten) =
3708 absolutize_path_dependencies(&text, manifest_dir, &workspace, ©)?
3709 {
3710 state.write(©.join(relative), &rewritten)?;
3711 }
3712 }
3713 }
3714 if let Some(catalogue) = catalogue {
3715 state.settle(&workspace)?;
3716 catalogue.ready.set(true);
3717 }
3718 }
3719
3720 let in_copy = |path: &Path| -> Result<PathBuf> {
3721 let canonical = path.canonicalize()?;
3722 let relative = canonical
3723 .strip_prefix(&workspace)
3724 .with_context(|| format!("{} is outside the workspace", path.display()))?;
3725 Ok(copy.join(relative))
3726 };
3727 let package_dir = in_copy(
3728 package
3729 .manifest_path
3730 .parent()
3731 .expect("manifest has a parent"),
3732 )?;
3733 let root_file = in_copy(&root_target.src_path)?;
3734 let source_dir = root_file
3735 .parent()
3736 .expect("source file has a parent")
3737 .to_path_buf();
3738
3739 let mut roots = BTreeMap::new();
3742 for owner in &metadata.packages {
3743 for target in &owner.targets {
3744 let production = owner.name == package.name && target.is_production();
3745 if let Ok(path) = in_copy(&target.src_path)
3746 && path.is_file()
3747 {
3748 let selected = roots.entry(path).or_insert(false);
3749 *selected |= production;
3750 }
3751 }
3752 }
3753 let paths = source_graph(roots, ©, |path| state.original(path, &workspace))?;
3754 let scope = requested_scope(options, &workspace, &package_dir, ©)?;
3755 let mut skipped = vec![];
3756 let mut files = vec![];
3757 let mut next_id = 0u32;
3758 let want_witnesses = (options.list || options.rebuild || options.source_only)
3759 && root_target.test_build_arg() == Some(("--lib", None));
3760 let mut witness_candidates = vec![];
3761 for (path, owners) in paths {
3762 let Some(original) = state.original(&path, &workspace)? else {
3763 continue; };
3765 let selected_file = scope.as_ref().is_none_or(|scope| {
3766 let relative = path.strip_prefix(©).unwrap_or(&path).to_string_lossy();
3767 scope.touches(&relative, 1, usize::MAX)
3768 });
3769 if !selected_file && path != root_file {
3770 continue;
3771 }
3772 let display = relative_source(&path, &package_dir).display().to_string();
3773 match instrument::parse_source(&original) {
3774 Ok(parsed) => {
3775 let mut found =
3776 instrument::discover_parsed(&original, &parsed, next_id, &error_values);
3777 if want_witnesses && selected_file && path == root_file {
3778 witness_candidates =
3779 witness::discover_parsed(&original, &parsed, !options.list);
3780 }
3781 next_id += found.sites.len() as u32;
3782 if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
3783 found.rebuild_sites.append(&mut found.sites);
3784 }
3785 let places = if options.list {
3786 vec![]
3787 } else {
3788 found
3789 .sites
3790 .iter()
3791 .chain(&found.rebuild_sites)
3792 .map(|site| (site.line, site.column, report::one_line(&site.text)))
3793 .collect()
3794 };
3795 files.push(SourceFile {
3796 display,
3797 path,
3798 owners: owners.production,
3799 lines: scope::LineIndex::new(&original),
3800 original,
3801 places,
3802 sites: found.sites,
3803 rebuild_sites: found.rebuild_sites,
3804 rendered: None,
3805 });
3806 }
3807 Err(err) => {
3808 if selected_file {
3809 let diagnostic = format!("{err:#}");
3810 note(&format!("skipping {display}: {diagnostic}"));
3811 let end_line = scope::line_of(&original, original.len());
3812 let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
3813 skipped.push(report::SkippedSite::new(
3814 report::Location {
3815 file: display,
3816 line: 1,
3817 column: 1,
3818 ..Default::default()
3819 },
3820 (end_line, end_column),
3821 report::SkipReason::UnparseableSource,
3822 Some(diagnostic),
3823 ));
3824 }
3825 }
3826 }
3827 }
3828
3829 if let Some(scope) = &scope {
3831 for file in &mut files {
3832 let relative = file
3833 .path
3834 .strip_prefix(©)
3835 .unwrap_or(&file.path)
3836 .to_string_lossy()
3837 .into_owned();
3838 let in_scope = |site: &Site| {
3839 scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
3840 || scope.touches(&relative, site.line, site.line)
3842 };
3843 file.sites.retain(in_scope);
3844 file.rebuild_sites.retain(in_scope);
3845 }
3846 files.retain(|f| !f.sites.is_empty() || !f.rebuild_sites.is_empty() || f.path == root_file);
3847 }
3848 if !witness_candidates.is_empty()
3849 && let Some(file) = files.iter_mut().find(|file| file.path == root_file)
3850 {
3851 let relative = file
3852 .path
3853 .strip_prefix(©)
3854 .unwrap_or(&file.path)
3855 .to_string_lossy();
3856 if !options.list {
3857 let locations: Vec<_> = witness_candidates
3858 .iter()
3859 .filter(|candidate| !candidate.existing)
3860 .map(|candidate| {
3861 let at = witness_location(file, candidate);
3862 (at.line, at.column, at.code)
3863 })
3864 .collect();
3865 file.places.extend(locations);
3866 }
3867 witness_candidates.retain(|candidate| {
3868 scope.as_ref().is_none_or(|scope| {
3869 let site_in_scope = if candidate.edits.len() == 1 {
3870 scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
3871 } else {
3872 candidate.edits.iter().any(|edit| {
3873 scope.touches(
3874 &relative,
3875 file.lines.line_of(edit.span.start),
3876 file.lines.line_of(edit.span.end),
3877 )
3878 })
3879 };
3880 site_in_scope
3881 || candidate
3882 .signature_lines
3883 .iter()
3884 .any(|&line| scope.touches(&relative, line, line))
3885 })
3886 });
3887 }
3888 let total_sites: usize = files
3889 .iter()
3890 .map(|f| f.sites.len() + f.rebuild_sites.len())
3891 .sum::<usize>()
3892 + witness_candidates
3893 .iter()
3894 .filter(|candidate| !candidate.existing)
3895 .count();
3896 note(&format!("{} sites in {} files", total_sites, files.len()));
3897 if options.source_only {
3898 for file in &mut files {
3899 file.rebuild_sites.append(&mut file.sites);
3900 }
3901 }
3902
3903 let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
3904 let mut mutants = instrument::source_mutants(site);
3905 if include_boundary {
3906 mutants.extend(instrument::source_boundary_mutant(site));
3907 }
3908 if options.literal_operators {
3909 instrument::literal_operator_mutants(&file.original, site, &mut mutants);
3910 }
3911 mutants
3912 };
3913 let counts = options.shard.map(|_| {
3914 let regular: usize = files
3915 .iter()
3916 .map(|file| {
3917 file.rebuild_sites
3918 .iter()
3919 .map(|site| source_mutants(file, site, true).len())
3920 .sum::<usize>()
3921 })
3922 .sum();
3923 let total = regular
3924 + witness_candidates
3925 .iter()
3926 .filter(|candidate| !candidate.existing)
3927 .count();
3928 (regular, total)
3929 });
3930 if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
3931 && range.member_total != local_total
3932 {
3933 bail!("package catalogue changed while preparing its workspace shard");
3934 }
3935 let in_shard = |index| match (options.shard, counts, workspace_shard) {
3936 (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
3937 (Some(shard), Some((_, total)), _) => shard.contains(index, total),
3938 _ => true,
3939 };
3940 if let Some((mut index, _)) = counts {
3941 witness_candidates.retain(|candidate| {
3942 if candidate.existing {
3943 return true;
3944 }
3945 let selected = in_shard(index);
3946 index += 1;
3947 selected
3948 });
3949 }
3950 let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
3951
3952 let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
3953 let mut report_path = repository_prefix(package_path);
3954 if report_path.is_empty()
3955 && batch.is_some()
3956 && let Ok(relative) = package_path.strip_prefix(&workspace)
3957 && !relative.as_os_str().is_empty()
3958 {
3959 report_path = format!("{}/", relative.to_string_lossy().replace('\\', "/"));
3960 }
3961 let mut report = Report {
3962 package: package.name.clone(),
3963 sites: if empty_shard { 0 } else { total_sites },
3964 analysis: report::Analysis {
3965 package_path: report_path,
3966 since: options.since.clone(),
3967 lines: options.lines.clone(),
3968 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
3969 cargo: options.cargo.clone(),
3970 opt_level: options.opt_level,
3971 timeout_seconds: options.timeout_seconds,
3972 baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
3973 timeout_recheck: if options.serial_timeout_rechecks {
3974 "serial"
3975 } else {
3976 "none"
3977 },
3978 wrapper_grace_seconds: selection
3979 .wrapper
3980 .as_ref()
3981 .map(|_| options.wrapper_grace.as_secs()),
3982 rebuild: options.rebuild || options.source_only,
3983 verified: options.verify && !options.source_only,
3984 doc_tests: options.doc,
3985 source_only: options.source_only,
3986 literal_operators: options.literal_operators,
3987 shard: options.shard,
3988 nextest: options.nextest.clone(),
3989 error_values: error_values
3990 .iter()
3991 .map(|value| (*value).to_owned())
3992 .collect(),
3993 test_selection: None,
3994 git_index: options.git_index,
3995 copy_fixtures: options.copy_fixtures.clone(),
3996 copy_fixture_excludes: options.copy_fixture_excludes.clone(),
3997 output_fixtures: options.output_fixtures.clone(),
3998 checkpoint: (options.checkpoint && !options.list)
3999 .then(|| work.join("checkpoint.jsonl")),
4000 },
4001 skipped,
4002 ..Report::default()
4003 };
4004 if options.list {
4005 if catalogue.is_none() {
4006 state.settle(&workspace)?;
4007 }
4008 let mut candidates = vec![];
4009 let mut index = 0;
4010 for file in &files {
4011 let sites = file
4012 .sites
4013 .iter()
4014 .map(|site| (site, false))
4015 .chain(file.rebuild_sites.iter().map(|site| (site, true)));
4016 for (site, requires_rebuild) in sites {
4017 for mutant in source_mutants(file, site, true) {
4018 if in_shard(index) {
4019 candidates.push(report::Candidate {
4020 what: mutant.what,
4021 into: mutant.into,
4022 requires_rebuild,
4023 edits: vec![candidate_edit(
4024 file,
4025 mutant.start,
4026 mutant.end,
4027 mutant.replacement,
4028 )],
4029 });
4030 }
4031 index += 1;
4032 }
4033 }
4034 }
4035 if let Some(root) = files.iter().find(|file| file.path == root_file) {
4036 candidates.extend(
4037 witness_candidates
4038 .iter()
4039 .filter(|candidate| !candidate.existing)
4040 .map(|candidate| report::Candidate {
4041 what: "witness".into(),
4042 into: candidate.description.clone(),
4043 requires_rebuild: true,
4044 edits: candidate
4045 .edits
4046 .iter()
4047 .map(|edit| {
4048 candidate_edit(
4049 root,
4050 edit.span.start,
4051 edit.span.end,
4052 edit.replacement.clone(),
4053 )
4054 })
4055 .collect(),
4056 }),
4057 );
4058 }
4059 report.mutants = Some(candidates);
4060 return Ok(report);
4061 }
4062 if empty_shard || (scope.is_some() && total_sites == 0) {
4063 state.settle(&workspace)?;
4065 if let Some(path) = &options.baseline {
4066 crate::baseline::load(path)?;
4067 }
4068 if let Some(path) = &options.write_baseline {
4069 crate::baseline::write(path, &[])?;
4070 }
4071 report.record_evaluation();
4072 if let Some(path) = report.analysis.checkpoint.as_deref() {
4073 let checkpoint = Checkpoint::open(path)?;
4074 let settings =
4075 serde_json::json!({"analysis": &report.analysis, "package": &package.name});
4076 let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
4077 checkpoint.start(&identity, settings)?;
4078 checkpoint.finish()?;
4079 }
4080 return Ok(report);
4081 }
4082
4083 for (id, site) in files
4086 .iter_mut()
4087 .flat_map(|file| &mut file.sites)
4088 .enumerate()
4089 {
4090 site.id = id as u32;
4091 }
4092
4093 let root_source = state
4094 .original(&root_file, &workspace)?
4095 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
4096 let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
4097 String::new()
4098 } else {
4099 state.write(
4100 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
4101 crate::RUNTIME_SOURCE,
4102 )?;
4103 let std_alias = format!("extern crate std as {STD_ALIAS};");
4104 if root_source.contains(&std_alias) {
4105 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
4106 } else {
4107 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
4108 }
4109 };
4110
4111 let mut disabled: HashSet<u32> = HashSet::new();
4113 let mut repairs = BTreeMap::new();
4114 let build_target = work_directory(&work, "target")?;
4115 let target_flags = test_build_flags(
4116 &test_packages,
4117 &selection.targets,
4118 &workspace,
4119 &options.cargo,
4120 );
4121 let build_scope = if target_flags.is_some() {
4122 report::TestBuildScope::SelectedTargets
4123 } else {
4124 report::TestBuildScope::PackageWide
4125 };
4126 let build_note = if !selection.targets.is_empty() && target_flags.is_none() {
4127 "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
4128 } else {
4129 ""
4130 };
4131 if !build_note.is_empty() {
4132 note(build_note.trim_end());
4133 }
4134 let can_build_only_observer = !options.doc
4137 && target_flags.is_none()
4138 && test_packages.len() == 1
4139 && package.targets.len() == 1
4140 && root_target.test
4141 && root_target.test_build_arg() == Some(("--lib", None));
4142 let build_test_binaries = |observer: bool| {
4143 let mut command = Command::new("cargo");
4144 isolate_copy_command(&mut command, &work);
4145 if let Some(lock) = &work_lock {
4146 lock.retain_for(&mut command);
4147 }
4148 command
4149 .args(["test", "--no-run", "--message-format=json"])
4150 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
4151 .args(target_flags.as_deref().unwrap_or_default())
4152 .args((observer && can_build_only_observer).then_some("--lib"))
4153 .args(options.cargo.flags())
4154 .current_dir(©)
4155 .env("CARGO_TARGET_DIR", &build_target)
4156 .env("CARGO_BUILD_BUILD_DIR", &build_target)
4157 .envs(profile_env(options.opt_level))
4158 .stderr(Stdio::piped())
4159 .output()
4160 .context("running cargo test --no-run")
4161 };
4162 let cargo_build = || build_test_binaries(false);
4163 let mut rounds = 0;
4164 let mut newly_disabled = HashSet::new();
4165 let build = loop {
4166 for file in &mut files {
4167 let suffix = if file.path == root_file {
4168 root_suffix.as_str()
4169 } else {
4170 ""
4171 };
4172 write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
4173 }
4174 if !files.iter().any(|f| f.path == root_file) {
4175 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
4176 }
4177 if rounds == 0 {
4178 state.settle(&workspace)?;
4179 }
4180 note(if rounds == 0 {
4181 "building the instrumented crate"
4182 } else {
4183 "rebuilding without the sites that failed to compile"
4184 });
4185 let output = cargo_build()?;
4186 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
4187 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
4188 if output.status.success() {
4189 break build;
4190 }
4191 let diagnostics = || {
4192 [
4193 build.diagnostics.join("\n"),
4194 String::from_utf8_lossy(&output.stderr).into_owned(),
4195 ]
4196 .into_iter()
4197 .filter(|part| !part.trim().is_empty())
4198 .collect::<Vec<_>>()
4199 .join("\n")
4200 };
4201 if build.errors.is_empty() {
4202 bail!("the build failed:\n{build_note}{}", diagnostics());
4203 }
4204 rounds += 1;
4205 let before = disabled.len();
4206 let mut blamed_now: HashSet<u32> = HashSet::new();
4207 for error in &build.errors {
4208 let blamed = blame_error(error, &files, ©, &disabled);
4209 if std::env::var_os("TMT_DEBUG").is_some() {
4210 eprintln!("tmt: debug: blaming {blamed:?} for\n{}", error.rendered);
4211 }
4212 for id in blamed {
4213 repairs
4214 .entry(id)
4215 .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
4216 blamed_now.insert(id);
4217 }
4218 }
4219 disabled.extend(blamed_now.iter().copied());
4220 newly_disabled = blamed_now;
4221 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
4222 bail!(
4223 "the crate does not build after instrumentation.\n\
4224 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
4225 diagnostics()
4226 );
4227 }
4228 };
4229 let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
4230 BuiltSources::from_artifacts(&build.artifacts, ©)
4231 } else {
4232 BuiltSources::default()
4233 };
4234 output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
4235 let checkpoint_path = report.analysis.checkpoint.as_deref();
4236 let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
4237 let doc_packages = test_packages
4238 .iter()
4239 .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
4240 if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
4241 bail!("{build_note}`{}` has no test binaries", package.name);
4242 }
4243
4244 let mut session = Session {
4246 progress: options.progress,
4247 serial_timeout_rechecks: options.serial_timeout_rechecks,
4248 package_dir,
4249 binaries: vec![],
4250 };
4251 let wrapper = selection
4252 .wrapper
4253 .as_ref()
4254 .map(|path| {
4255 if path.is_absolute()
4256 || path
4257 .components()
4258 .any(|c| matches!(c, std::path::Component::ParentDir))
4259 {
4260 bail!(
4261 "--test-wrapper must be a path inside the workspace: {}",
4262 path.display()
4263 );
4264 }
4265 let copied = copy.join(path);
4266 if !copied.is_file() {
4267 bail!(
4268 "test wrapper is missing from the work copy: {}",
4269 copied.display()
4270 );
4271 }
4272 Ok(copied)
4273 })
4274 .transpose()?;
4275 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
4276 let root_test_exe = |built: &BuildOutput| {
4277 built
4278 .test_binaries
4279 .iter()
4280 .find(|(name, _, owner, kind)| {
4281 *name == root_target.name && *owner == package.name && *kind == root_target.kind
4282 })
4283 .map(|(_, exe, _, _)| exe.clone())
4284 };
4285 let root_exe = (!witness_candidates.is_empty())
4286 .then(|| root_test_exe(&build))
4287 .flatten();
4288 if let Some(nextest) = &options.nextest {
4289 let mut flags: Vec<_> = test_packages
4290 .iter()
4291 .flat_map(|p| ["-p".to_owned(), p.name.clone()])
4292 .collect();
4293 flags.extend(options.cargo.flags());
4294 runners.push((
4295 "nextest".to_owned(),
4296 Runner::Nextest {
4297 copy: copy.clone(),
4298 target_dir: build_target.clone(),
4299 profile: nextest.profile.clone(),
4300 opt_level: options.opt_level,
4301 flags,
4302 },
4303 session.package_dir.clone(),
4304 ));
4305 } else {
4306 for (name, exe, owner, kind) in build.test_binaries {
4307 if !selection.targets.is_empty() && !selection.targets.contains(&name) {
4308 continue;
4309 }
4310 let owner_package = test_packages
4311 .iter()
4312 .find(|p| p.name == owner)
4313 .expect("binaries are filtered by these packages");
4314 let cwd = in_copy(
4315 owner_package
4316 .manifest_path
4317 .parent()
4318 .expect("manifest has a parent"),
4319 )?;
4320 if selection.enabled() {
4321 let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
4322 let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
4323 for test in all {
4324 let was_ignored = ignored.contains(&test);
4325 if (was_ignored && !selection.include_ignored)
4326 || (!selection.include.is_empty() && !selection.include.contains(&test))
4327 || selection.exclude.contains(&test)
4328 {
4329 continue;
4330 }
4331 runners.push((
4332 format!("{owner}::{}::{name}::{test}", kind.join("+")),
4333 Runner::Isolated {
4334 exe: exe.clone(),
4335 test,
4336 ignored: was_ignored,
4337 wrapper: wrapper.clone(),
4338 },
4339 cwd.clone(),
4340 ));
4341 }
4342 continue;
4343 }
4344 let name = if owner == package.name {
4346 name
4347 } else {
4348 format!("{owner}::{name}")
4349 };
4350 runners.push((name, Runner::Exe(exe), cwd));
4351 }
4352 }
4353 if selection.enabled() && runners.is_empty() {
4354 bail!("{build_note}no tests matched the requested selection");
4355 }
4356 let selected_tests = selection.enabled().then(|| report::TestSelection {
4357 build_scope,
4358 wrapper: selection
4359 .wrapper
4360 .as_ref()
4361 .map(|path| path.display().to_string()),
4362 tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
4363 });
4364 for owner in doc_packages {
4365 let doc = Runner::Doc {
4366 copy: copy.clone(),
4367 target_dir: build_target.clone(),
4368 package: owner.name.clone(),
4369 opt_level: options.opt_level,
4370 flags: options.cargo.flags(),
4371 };
4372 let name = if owner.name == package.name {
4373 "doc tests".to_owned()
4374 } else {
4375 format!("{}::doc tests", owner.name)
4376 };
4377 let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
4378 runners.push((name, doc, cwd));
4379 }
4380 report.analysis.test_selection = selected_tests;
4381 let identity = if checkpoint.is_some() {
4382 let mut build_inputs: Vec<_> = build
4383 .build_scripts
4384 .iter()
4385 .map(serde_json::Value::to_string)
4386 .collect();
4387 build_inputs.sort();
4388 let settings = serde_json::json!({
4391 "build_scripts": build_inputs,
4392 "analysis": &report.analysis, "package": &package.name, "jobs": options.jobs,
4393 "verify": options.verify, "audit": options.audit, "effects": options.effects,
4394 "all_files": options.all_files, "build_scope": build_scope,
4395 "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
4396 });
4397 let mut inputs = BTreeSet::new();
4398 for (root, artifacts) in &build.artifacts {
4399 inputs.insert(root.clone());
4400 if let Some(dependencies) = artifacts
4401 .iter()
4402 .map(|artifact| artifact_inputs(artifact, root, ©))
4403 .find(|deps| !deps.is_empty())
4404 {
4405 inputs.extend(dependencies);
4406 } else {
4407 inputs.extend(artifacts.iter().cloned());
4410 }
4411 }
4412 inputs.extend(
4413 build
4414 .build_scripts
4415 .iter()
4416 .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
4417 );
4418 inputs.retain(|path| !path.starts_with(©));
4421 inputs.extend(
4422 options
4423 .output_fixtures
4424 .iter()
4425 .map(|fixture| build_target.join(&fixture.to)),
4426 );
4427 Some(crate::campaign_identity::compute(
4428 ©,
4429 &settings,
4430 inputs,
4431 options.nextest.is_some(),
4432 )?)
4433 } else {
4434 None
4435 };
4436 let marks = marks_dir(&work)?;
4441 let baseline_jobs = if selection.enabled() {
4442 options.baseline_jobs
4443 } else {
4444 1
4445 };
4446 if options.progress {
4447 eprintln!(
4448 "tmt: baselines: 0/{} completed ({} workers)",
4449 runners.len(),
4450 baseline_jobs
4451 );
4452 }
4453
4454 session.binaries = progress::track_baselines(options.progress, runners.len(), |progress| {
4455 run_pool(runners.len(), baseline_jobs, |slot| {
4456 let index = slot;
4457 let (name, runner, cwd) = runners[index].clone();
4458 let result = (|| {
4459 let trace_path = work.join(format!("trace-{index}.tsv"));
4460 let _ = fs::remove_file(&trace_path);
4461 let mut bin = TestBinary {
4462 name,
4463 cwd,
4464 marks: marks.clone(),
4465 git_ceiling: work.clone(),
4466 work_lock: work_lock.clone(),
4467 tests: BTreeSet::new(),
4468 runner,
4469 baseline: Duration::ZERO,
4470 untraced_baseline: None,
4471 timeout_diagnostic: std::sync::Once::new(),
4472 traced: Duration::ZERO,
4473 timeout: options.timeout_seconds.map(Duration::from_secs),
4474 wrapper_grace: options.wrapper_grace,
4475 report_slow: options.progress,
4476 filtered_timings: Default::default(),
4477 trace: Trace::default(),
4478 effects_baseline: std::sync::OnceLock::new(),
4479 };
4480 session.note(&format!("tracing `{}`", bin.name));
4481 let started = Instant::now();
4482 let trace_env = trace_path.to_string_lossy().into_owned();
4483 let trace = [("TMT_TRACE", trace_env.as_str())];
4484 run_baseline(
4485 &bin,
4486 if options.source_only { &[] } else { &trace },
4487 Duration::from_secs(3600),
4488 &work.join(format!("baseline-{index}.log")),
4489 false,
4490 )?;
4491 bin.traced = started.elapsed();
4492 bin.baseline = bin.traced;
4493 if options.source_only {
4494 bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
4495 }
4496 if !options.source_only && bin.traced > SLOW_TRACE {
4499 let started = Instant::now();
4500 let passed = run_baseline(
4501 &bin,
4502 &[],
4503 bin.traced,
4504 &work.join(format!("baseline-{index}-untraced.log")),
4505 true,
4506 )?;
4507 let elapsed = started.elapsed();
4508 if passed {
4509 bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
4510 bin.baseline = elapsed;
4511 } else {
4512 bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
4513 }
4514 }
4515 let text = match fs::read_to_string(&trace_path) {
4518 Ok(text) => text,
4519 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
4520 Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
4521 };
4522 bin.trace = Trace::parse(&text);
4523 if bin.trace.malformed_lines > 0 {
4524 bail!(
4525 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
4526 bin.name,
4527 bin.trace.malformed_lines
4528 );
4529 }
4530 if let Runner::Exe(exe) = &bin.runner {
4531 bin.tests =
4532 list_tests(exe, &bin.cwd, &work, false, false, work_lock.as_deref())?;
4533 }
4534 Ok(bin)
4535 })();
4536 progress.complete(if result.is_ok() {
4537 progress::Outcome::Survived
4538 } else {
4539 progress::Outcome::Failed
4540 });
4541 result
4542 })
4543 })?;
4544
4545 for file in &files {
4547 for site in &file.sites {
4548 if disabled.contains(&site.id) {
4549 let fallback = options.rebuild
4550 && !matches!(site.kind, SiteKind::Body { .. })
4551 && !instrument::source_mutants(site).is_empty();
4552 match site.kind {
4553 SiteKind::Body { .. } => report.unviable_mutants += 1,
4554 _ if fallback => {}
4555 _ => report.skipped_sites += 1,
4556 }
4557 report.skipped.push(report::SkippedSite::new(
4558 report::location(&file.display, site),
4559 file.lines.position(&file.original, site.end),
4560 if fallback {
4561 report::SkipReason::ProbeReplacedBySourceRebuild
4562 } else {
4563 report::SkipReason::ProbeCompileError
4564 },
4565 repairs.get(&site.id).cloned(),
4566 ));
4567 }
4568 }
4569 if !options.rebuild && !options.source_only {
4570 report.skipped.extend(file.rebuild_sites.iter().map(|site| {
4571 report::SkippedSite::new(
4572 report::location(&file.display, site),
4573 file.lines.position(&file.original, site.end),
4574 report::SkipReason::RequiresSourceRebuild,
4575 None,
4576 )
4577 }));
4578 }
4579 }
4580 if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
4581 checkpoint.start(
4582 identity,
4583 serde_json::json!({
4584 "package": &package.name, "analysis": &report.analysis,
4585 "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
4586 "jobs": options.jobs, "tool_version": env!("CARGO_PKG_VERSION")
4587 }),
4588 )?;
4589 }
4590 let phase = |name: &str, keys: Vec<String>| {
4591 checkpoint
4592 .as_ref()
4593 .zip(identity.as_deref())
4594 .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
4595 .transpose()
4596 };
4597 let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
4598 if checkpoint.is_none() {
4599 return Ok(None);
4600 }
4601 let locations: BTreeMap<_, _> = files
4602 .iter()
4603 .flat_map(|file| {
4604 file.sites
4605 .iter()
4606 .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
4607 })
4608 .collect();
4609 let keys = jobs
4610 .iter()
4611 .map(|job| {
4612 let tests = job
4613 .tests
4614 .iter()
4615 .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
4616 .collect::<Vec<_>>();
4617 serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
4618 })
4619 .collect::<std::result::Result<Vec<_>, _>>()?;
4620 phase(name, keys)
4621 };
4622 let scratch = work.clone();
4623 let mut jobs: Vec<Job> = vec![];
4624 let mut not_evaluated: HashSet<u32> = HashSet::new();
4627 let mut work: Vec<SiteWork> = vec![];
4628 let mut effect_jobs: Vec<(usize, usize)> = vec![];
4630 for file in &files {
4631 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
4632 let plan = match session.plan(&file.display, site, options.verify) {
4633 Planned::Unreached => {
4634 let at = report::location(&file.display, site);
4636 if report.unreached.last() != Some(&at) {
4637 report.unreached.push(at);
4638 }
4639 continue;
4640 }
4641 Planned::Nothing => continue,
4642 Planned::NotEvaluated => {
4643 not_evaluated.insert(site.id);
4644 continue;
4645 }
4646 Planned::Plan(plan) => plan,
4647 };
4648 let mut add =
4649 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
4650 jobs.push(session.job(site.id, mutation, tests_of));
4651 jobs.len() - 1
4652 };
4653 let gaps = plan
4654 .gaps
4655 .into_iter()
4656 .map(
4657 |PlannedGap {
4658 finding,
4659 survivors,
4660 constant_expr,
4661 }| {
4662 let confirm = if options.verify {
4665 survivors
4666 .into_iter()
4667 .map(|m| add(m, &*plan.reaching))
4668 .collect()
4669 } else {
4670 vec![]
4671 };
4672 (finding, confirm, constant_expr)
4673 },
4674 )
4675 .collect();
4676 let infected = &plan.infected;
4677 let runs = plan
4678 .run
4679 .iter()
4680 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
4681 .collect();
4682 work.push(SiteWork {
4683 file: &file.display,
4684 site,
4685 gaps,
4686 constant: plan.constant,
4687 cannot_differ: plan.cannot_differ,
4688 runs,
4689 });
4690 }
4691 }
4692 session.note(&format!(
4693 "running {} mutants on {} thread(s)",
4694 jobs.len(),
4695 options.jobs.max(1)
4696 ));
4697 let probe_checkpoint = probe_phase("probe", &jobs)?;
4698 let mut results =
4699 session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
4700 for result in &results {
4701 report.timeout_rechecks.include(result);
4702 }
4703
4704 if let Some(wanted) = options.audit {
4707 let survivors: Vec<usize> = (0..jobs.len())
4708 .filter(|job| results[*job].survived.is_some())
4709 .collect();
4710 let chosen: Vec<usize> = spread(survivors.len(), wanted)
4711 .into_iter()
4712 .map(|nth| survivors[nth])
4713 .collect();
4714 session.note(&format!(
4715 "audit: running {} of {} surviving mutants against all tests",
4716 chosen.len(),
4717 survivors.len()
4718 ));
4719 let against_all: Vec<Job> = chosen
4720 .iter()
4721 .map(|job| Job {
4722 site: jobs[*job].site,
4723 mutation: jobs[*job].mutation,
4724 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
4725 })
4726 .collect();
4727 let mut audit = report::Audit {
4728 sampled: chosen.len(),
4729 survivors: survivors.len(),
4730 ..report::Audit::default()
4731 };
4732 let audit_checkpoint = probe_phase("audit", &against_all)?;
4733 for (job, again) in chosen.iter().zip(session.run_jobs(
4734 &against_all,
4735 options.jobs,
4736 "audit mutants",
4737 audit_checkpoint.as_ref(),
4738 )?) {
4739 report.timeout_rechecks.include(&again);
4740 if again.survived.is_none() {
4741 results[*job] = again;
4743 let site = files
4744 .iter()
4745 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
4746 if let Some((file, site)) = site {
4747 audit
4748 .disagreements
4749 .push(report::location(&file.display, site));
4750 }
4751 }
4752 }
4753 session.note("audit: recording the tests once more");
4754 for (index, bin) in session.binaries.iter().enumerate() {
4755 let path = scratch.join(format!("trace-{index}-audit.tsv"));
4756 let _ = fs::remove_file(&path);
4757 let trace_env = path.to_string_lossy().into_owned();
4758 let limit = Duration::from_secs(3600);
4759 let outcome = run_binary(
4760 bin,
4761 None,
4762 &[("TMT_TRACE", &trace_env)],
4763 limit,
4764 RunOutput::Quiet,
4765 1,
4766 )?;
4767 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
4768 let _ = fs::remove_file(&path);
4769 let records = bin.trace.differences(&again);
4770 if outcome != Outcome::Pass || records > 0 {
4771 audit.trace_differences.push(report::TraceDifference {
4772 binary: bin.name.clone(),
4773 records,
4774 });
4775 }
4776 }
4777 report.audit = Some(audit);
4778 }
4779 let unable = results
4780 .iter()
4781 .filter(|r| r.unable || r.unconfirmed_timeout)
4782 .count();
4783 not_evaluated.extend(
4784 jobs.iter()
4785 .zip(&results)
4786 .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
4787 .map(|(job, _)| job.site),
4788 );
4789 if !options.rebuild {
4790 report.mutants_not_evaluated = not_evaluated.len();
4791 }
4792 report.mutants_run = results.len() - unable;
4793 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
4794 report.mutants_timed_out = results
4795 .iter()
4796 .filter(|r| r.timed_out && !r.unconfirmed_timeout)
4797 .count();
4798
4799 let confirmed = |w: &SiteWork| {
4802 w.gaps
4803 .iter()
4804 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
4805 };
4806 let constants: BTreeSet<(&str, usize, usize)> = work
4807 .iter()
4808 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
4809 .map(|w| (w.file, w.site.start, w.site.end))
4810 .collect();
4811 for item in &work {
4812 let at = report::location(item.file, item.site);
4813 for (finding, confirm, constant_expr) in &item.gaps {
4814 let repeats = constant_expr
4817 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
4818 if confirm.iter().any(|j| results[*j].survived.is_none()) {
4819 report.unstable.push(at.clone());
4820 } else if !repeats {
4821 report.findings.push(finding.clone());
4822 }
4823 }
4824 if let SiteKind::Body {
4827 sole_expr: Some((start, end)),
4828 ..
4829 } = item.site.kind
4830 && constants.contains(&(item.file, start, end))
4831 {
4832 continue;
4833 }
4834 let mut survivors = vec![];
4835 let mut passing_tests = BTreeSet::new();
4836 for (mutation, job) in &item.runs {
4837 if let Some(tests) = &results[*job].survived {
4838 survivors.push(report::describe(item.site, *mutation));
4839 passing_tests.extend(tests.iter().cloned());
4840 }
4841 }
4842 if !survivors.is_empty() {
4843 let first = item
4845 .runs
4846 .iter()
4847 .find(|(_, job)| results[*job].survived.is_some());
4848 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
4849 report.findings.push(Finding::AssertionGap {
4850 at,
4851 survivors,
4852 tests: passing_tests.into_iter().collect(),
4853 effects: vec![],
4854 effects_of: None,
4855 witness: None,
4856 });
4857 }
4858 }
4859
4860 if options.effects && !effect_jobs.is_empty() {
4862 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
4863 let sites: BTreeMap<u32, (&str, &Site)> = files
4864 .iter()
4865 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
4866 .collect();
4867 let traced = run_pool(effect_jobs.len(), options.jobs, |index| {
4868 session.trace_job(
4869 &jobs[effect_jobs[index].1],
4870 &scratch,
4871 options.jobs.clamp(1, effect_jobs.len()),
4872 )
4873 })?;
4874 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
4875 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
4878 for found in changes.values_mut() {
4879 found.retain(|change| {
4880 sites.get(&change.site()).is_none_or(|(file, site)| {
4881 file != mutated_file
4882 || site.end <= mutated.start
4883 || mutated.end <= site.start
4884 })
4885 });
4886 }
4887 changes.retain(|_, found| !found.is_empty());
4888 }
4889 if let Finding::AssertionGap {
4890 effects,
4891 effects_of,
4892 ..
4893 } = &mut report.findings[*finding]
4894 {
4895 *effects = describe_effects(&changes, &sites);
4896 *effects_of = sites
4897 .get(&jobs[*job].site)
4898 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
4899 }
4900 }
4901 }
4902
4903 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
4907 let build_regular_mutants = options.rebuild || options.source_only;
4908 let mut index = 0;
4909 for file in &files {
4910 let retried = file.sites.iter().filter(|site| {
4913 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
4914 || not_evaluated.contains(&site.id)
4915 });
4916 for site in file.rebuild_sites.iter().chain(retried) {
4917 let mutants = source_mutants(file, site, options.source_only);
4918 if build_regular_mutants {
4919 built.extend(mutants.into_iter().filter_map(|mutant| {
4920 let selected = in_shard(index);
4921 index += 1;
4922 selected.then_some((file, site, mutant, None))
4923 }));
4924 } else {
4925 report.mutants_not_built += mutants.len();
4926 }
4927 }
4928 }
4929 if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
4932 let mut twins = vec![];
4933 for file in &files {
4934 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
4935 let integers = session.binaries.iter().all(|bin| {
4937 let seen = bin.trace.merged(site.id);
4938 !seen.reached() || seen.valued()
4939 });
4940 let candidates = jobs_for_site(&jobs, site.id);
4941 let job_of = |mutation: Mutation| {
4942 candidates
4943 .clone()
4944 .find(|&index| jobs[index].mutation == mutation)
4945 };
4946 let mut compared = vec![];
4947 for mutant in instrument::source_mutants(site) {
4948 let job = mutations_like(site, &mutant, integers)
4950 .into_iter()
4951 .find_map(job_of);
4952 if let Some(job) = job {
4953 compared.push(job);
4954 twins.push((file, site, mutant, Some(job)));
4955 }
4956 }
4957 if let (SiteKind::Cmp { op, .. }, Some(job)) =
4960 (&site.kind, job_of(Mutation::Negate))
4961 && !compared.contains(&job)
4962 {
4963 let negated = instrument::SourceMutant {
4964 start: site.start,
4965 end: site.end,
4966 replacement: format!("!({})", site.text),
4967 what: op.symbol().to_string(),
4968 into: "!".to_string(),
4969 };
4970 twins.push((file, site, negated, Some(job)));
4971 }
4972 }
4973 }
4974 let chosen = spread(twins.len(), wanted);
4975 audit.rebuilt = chosen.len();
4976 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
4977 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
4978 }
4979 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
4980 by_speed.sort_by_key(|bin| bin.baseline);
4981 let root_mutant_suffix = if files.iter().any(|file| {
4983 file.path != root_file
4984 && file
4985 .rendered
4986 .as_ref()
4987 .is_some_and(|rendered| rendered.text != file.original)
4988 }) {
4989 root_suffix.as_str()
4990 } else {
4991 ""
4992 };
4993 if !built.is_empty() {
4994 if options.timeout_seconds.is_some()
4995 && built
4996 .iter()
4997 .any(|(file, _, _, _)| built_sources.contains(file))
4998 {
4999 for bin in &by_speed {
5000 bin.warn_timeout_conflict(None);
5001 }
5002 }
5003 let source_checkpoint = if checkpoint.is_some() {
5004 let keys = built
5005 .iter()
5006 .map(|(file, _, mutation, twin)| {
5007 serde_json::to_string(&(
5008 &file.display,
5009 mutation.start,
5010 mutation.end,
5011 &mutation.replacement,
5012 twin,
5013 ))
5014 })
5015 .collect::<std::result::Result<Vec<_>, _>>()?;
5016 phase("source", keys)?
5017 } else {
5018 None
5019 };
5020 session.note(&format!(
5021 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
5022 built.len()
5023 ));
5024 let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
5025 if file.path == root_file {
5026 format!("{text}{suffix}")
5027 } else {
5028 text.to_string()
5029 }
5030 };
5031 let mut skipped_targets = BTreeSet::new();
5034 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
5035 progress::track(
5036 options.progress,
5037 "source mutants",
5038 built.len(),
5039 |progress| -> Result<()> {
5040 for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
5041 let cached = source_checkpoint
5042 .as_ref()
5043 .map(|phase| phase.get::<Option<Outcome>>(index))
5044 .transpose()?
5045 .flatten();
5046 if !built_sources.contains(file) {
5047 if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
5048 {
5049 phase.record(index, &Some(Outcome::Unable))?;
5050 }
5051 if twin.is_none() {
5052 report.mutants_not_evaluated += 1;
5053 if skipped_targets.insert((&file.path, site.start, site.end)) {
5054 report.skipped.push(report::SkippedSite::new(
5055 report::location(&file.display, site),
5056 file.lines.position(&file.original, site.end),
5057 report::SkipReason::SourceNotBuilt,
5058 None,
5059 ));
5060 }
5061 } else if let Some(audit) = report.audit.as_mut() {
5062 audit.not_compared += 1;
5063 }
5064 progress.complete(progress::Outcome::Unable);
5065 continue;
5066 }
5067 let outcome = if let Some(cached) = cached {
5068 cached
5069 } else {
5070 let mutated = format!(
5071 "{}{}{}",
5072 &file.original[..mutant.start],
5073 mutant.replacement,
5074 &file.original[mutant.end..]
5075 );
5076 let attempt = || -> Result<Option<Outcome>> {
5078 state.write(
5079 &file.path,
5080 &instrumented(file, &mutated, root_mutant_suffix),
5081 )?;
5082 match source_build(&cargo_build()?) {
5083 SourceBuild::Built => run_source_tests(&by_speed).map(Some),
5084 SourceBuild::Refused => Ok(None),
5085 SourceBuild::Failed(why) => {
5088 session.note(&format!(
5089 "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
5090 ));
5091 Ok(Some(Outcome::Unable))
5092 }
5093 }
5094 };
5095 let attempted = attempt();
5096 let rendered = file.rendered.as_ref().expect("rendered before building");
5098 state.write(
5099 &file.path,
5100 &instrumented(file, &rendered.text, &root_suffix),
5101 )?;
5102 let outcome = attempted?;
5103 if let Some(phase) = &source_checkpoint
5106 && outcome != Some(Outcome::Unable)
5107 {
5108 phase.record(index, &outcome)?;
5109 }
5110 outcome
5111 };
5112 progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
5113 if let Some(job) = twin {
5114 let as_probe = results[*job].survived.is_some();
5116 let Some(audit) = report.audit.as_mut() else {
5117 continue;
5118 };
5119 let comparable = outcome.filter(|_| !results[*job].unable);
5121 match comparable {
5122 Some(_) => audit.compared += 1,
5123 None => audit.not_compared += 1,
5124 }
5125 if comparable.is_some_and(|built| (built == Outcome::Pass) != as_probe) {
5126 let verdict = |passes: bool| if passes { "passes" } else { "fails" };
5127 audit.source_disagreements.push(report::SourceDisagreement {
5128 at: report::location(&file.display, site),
5129 mutant: report::describe(site, mutation_of(site, mutant)),
5130 as_probe: verdict(as_probe).to_string(),
5131 built: verdict(!as_probe).to_string(),
5132 });
5133 }
5134 continue;
5135 }
5136 match outcome {
5137 None => report.unviable_mutants += 1,
5138 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
5139 Some(outcome) => {
5140 report.mutants_run += 1;
5141 report.mutants_killed += (outcome != Outcome::Pass) as usize;
5142 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
5143 }
5144 }
5145 let survived = outcome == Some(Outcome::Pass);
5146 if survived {
5147 let at = report::location(&file.display, site);
5148 let text = match (&site.kind, mutant.replacement.is_empty()) {
5149 (SiteKind::Field { .. }, true) => {
5150 format!("without the field `{}`", report::one_line(&site.text))
5151 }
5152 _ => report::describe(site, mutation_of(site, mutant)),
5153 };
5154 match survivors.last_mut() {
5155 Some((last, texts)) if *last == at => texts.push(text),
5156 _ => survivors.push((at, vec![text])),
5157 }
5158 }
5159 }
5160 Ok(())
5161 },
5162 )?;
5163 if let Some(phase) = &source_checkpoint {
5164 phase.finish()?;
5165 }
5166 report.findings.extend(
5167 survivors
5168 .into_iter()
5169 .map(|(at, survivors)| Finding::Survivor {
5170 at,
5171 survivors,
5172 witness: None,
5173 }),
5174 );
5175 }
5176
5177 if !witness_candidates.is_empty() {
5178 let file = files
5179 .iter()
5180 .find(|file| file.path == root_file)
5181 .expect("witness candidates in the root file");
5182 let rendered = file.rendered.as_ref().expect("rendered before building");
5183 let restore = format!("{}{root_suffix}", rendered.text);
5184 let library_runners: Vec<_> = session
5185 .binaries
5186 .iter()
5187 .filter(|bin| {
5188 root_exe
5189 .as_deref()
5190 .is_some_and(|exe| bin.runner.executable() == Some(exe))
5191 })
5192 .collect();
5193 let ignored = library_runners
5194 .iter()
5195 .find_map(|bin| match &bin.runner {
5196 Runner::Exe(exe) => Some(list_tests(
5197 exe,
5198 &bin.cwd,
5199 &bin.git_ceiling,
5200 true,
5201 false,
5202 bin.work_lock.as_deref(),
5203 )),
5204 _ => None,
5205 })
5206 .transpose()?
5207 .unwrap_or_default();
5208 let runner_for = |scenario: &witness::Scenario| {
5209 library_runners.iter().copied().find(|bin| {
5210 scenario
5211 .source_test
5212 .as_ref()
5213 .is_none_or(|required| match &bin.runner {
5214 Runner::Exe(_) => {
5215 bin.tests.contains(required) && !ignored.contains(required)
5216 }
5217 Runner::Isolated { test, .. } => test == required,
5218 Runner::Doc { .. } | Runner::Nextest { .. } => false,
5219 })
5220 })
5221 };
5222 let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
5223 let Some(source) = witness::render_edits(&file.original, edits, None) else {
5224 return Ok(false);
5225 };
5226 state.write(&root_file, &format!("{source}{root_mutant_suffix}"))?;
5227 Ok(true)
5228 };
5229 let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
5230 if !write_edits(edits)? || !cargo_build()?.status.success() {
5231 return Ok(None);
5232 }
5233 run_source_tests(&by_speed).map(Some)
5234 };
5235 let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
5236 if !write_edits(edits)? {
5237 return Ok(None);
5238 }
5239 let build = build_test_binaries(true)?;
5240 if !build.status.success() {
5241 return Ok(None);
5242 }
5243 let artifacts = parse_build_output(
5244 &String::from_utf8_lossy(&build.stdout),
5245 &[package.name.as_str()],
5246 );
5247 Ok(root_test_exe(&artifacts))
5248 };
5249 let observe = |scenario: &witness::Scenario,
5250 baseline: &TestBinary,
5251 edits: &[witness::Edit],
5252 expected: Option<&str>|
5253 -> Result<Option<witness::Observation>> {
5254 let test = scenario.test_edit(&file.original, witness::TEST_NAME, expected);
5255 let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
5256 let Some(exe) = compile_observer(&edits)? else {
5257 return Ok(None);
5258 };
5259 observe_witness(
5260 baseline,
5261 exe,
5262 wrapper.as_deref(),
5263 scenario,
5264 witness::TEST_NAME,
5265 expected.is_some(),
5266 )
5267 };
5268 let witness_checkpoint = if checkpoint.is_some() {
5269 let keys = witness_candidates
5270 .iter()
5271 .map(|candidate| {
5272 let edits = candidate
5273 .edits
5274 .iter()
5275 .map(|edit| (&edit.span, &edit.replacement))
5276 .collect::<Vec<_>>();
5277 serde_json::to_string(&(&candidate.description, edits))
5278 })
5279 .collect::<std::result::Result<Vec<_>, _>>()?;
5280 phase("witness", keys)?
5281 } else {
5282 None
5283 };
5284 let mut survivors = vec![];
5285 progress::track(
5286 options.progress,
5287 "source witness mutants",
5288 witness_candidates.len(),
5289 |progress| -> Result<()> {
5290 for (index, candidate) in witness_candidates.iter().enumerate() {
5291 let cached = witness_checkpoint
5292 .as_ref()
5293 .map(|phase| phase.get::<WitnessTrial>(index))
5294 .transpose()?
5295 .flatten();
5296 let at = witness_location(file, candidate);
5297 let existing = candidate
5298 .existing
5299 .then(|| {
5300 report.findings.iter().position(|finding| {
5301 let location = finding.at();
5302 location.file == at.file
5303 && location.line == at.line
5304 && location.column == at.column
5305 && finding.survivors().contains(&candidate.description)
5306 })
5307 })
5308 .flatten();
5309 let scenarios: Vec<_> = candidate
5310 .scenarios
5311 .iter()
5312 .filter_map(|scenario| {
5313 runner_for(scenario).map(|runner| (scenario, runner))
5314 })
5315 .take(4)
5316 .collect();
5317 let paired = candidate.edits.len() > 1;
5318 if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
5319 || (paired && scenarios.is_empty())
5320 {
5321 if let Some(phase) =
5322 witness_checkpoint.as_ref().filter(|_| cached.is_none())
5323 {
5324 phase.record(index, &WitnessTrial::Inapplicable)?;
5325 }
5326 progress.complete(progress::Outcome::Unable);
5327 continue;
5328 }
5329 let trial = if let Some(cached) = cached {
5332 cached
5333 } else {
5334 let attempted = (|| -> Result<WitnessTrial> {
5335 if paired {
5336 for edit in &candidate.edits {
5337 if suite(std::slice::from_ref(edit))? != Some(Outcome::Fail) {
5338 return Ok(WitnessTrial::Inapplicable);
5339 }
5340 }
5341 }
5342 Ok(suite(&candidate.edits)?
5343 .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
5344 })();
5345 state.write(&root_file, &restore)?;
5346 let trial = attempted?;
5347 if let Some(phase) = &witness_checkpoint {
5348 phase.record(index, &trial)?;
5349 }
5350 trial
5351 };
5352 let outcome = match trial {
5353 WitnessTrial::Inapplicable => {
5354 progress.complete(progress::Outcome::Unable);
5355 continue;
5356 }
5357 WitnessTrial::Unviable => {
5358 progress.complete(progress::Outcome::Unable);
5359 report.unviable_mutants += usize::from(!candidate.existing);
5360 continue;
5361 }
5362 WitnessTrial::Evaluated(outcome) => outcome,
5363 };
5364 progress.complete(outcome.into());
5365 if !candidate.existing {
5366 report.mutants_run += 1;
5367 report.mutants_killed += usize::from(outcome != Outcome::Pass);
5368 report.mutants_timed_out += usize::from(outcome == Outcome::Timeout);
5369 }
5370 if outcome == Outcome::Pass {
5371 survivors.push(WitnessSurvivor {
5372 candidate,
5373 at,
5374 existing,
5375 scenarios,
5376 });
5377 }
5378 }
5379 Ok(())
5380 },
5381 )?;
5382
5383 if let Some(phase) = &witness_checkpoint {
5384 phase.finish()?;
5385 }
5386 let originals = shared_witnesses(
5387 &file.original,
5388 &survivors,
5389 wrapper.as_deref(),
5390 compile_observer,
5391 note,
5392 );
5393 if !survivors.is_empty() {
5394 state.write(&root_file, &restore)?;
5395 }
5396 let originals = originals?;
5397
5398 progress::track(
5399 options.progress,
5400 "distinguishing tests",
5401 survivors.len(),
5402 |progress| -> Result<()> {
5403 for (survivor, original) in survivors.into_iter().zip(originals) {
5404 let mut evidence = None;
5405 let mut original = original;
5406 for (scenario, baseline) in survivor.scenarios {
5407 let shared = original.take();
5408 let distinction = (|| -> Result<_> {
5409 if let Some(shared) = shared {
5410 let edits: Vec<_> = survivor
5412 .candidate
5413 .edits
5414 .iter()
5415 .chain(shared.tests.iter())
5416 .cloned()
5417 .collect();
5418 if let Some(exe) = compile_observer(&edits)?
5419 && let Some(mutant) = observe_witness(
5420 baseline,
5421 exe,
5422 wrapper.as_deref(),
5423 scenario,
5424 &shared.name,
5425 true,
5426 )
5427 .ok()
5428 .flatten()
5429 && mutant.equals_expected == Some(false)
5430 && let Some(verified) =
5431 scenario.verified(shared.value, mutant.value)
5432 {
5433 return Ok(Some(verified));
5434 }
5435 }
5438 let Some(original) = observe(scenario, baseline, &[], None)? else {
5439 return Ok(None);
5440 };
5441 let value = original.value;
5442 if !witness::is_expected_literal(&value) {
5443 return Ok(None);
5444 }
5445 let Some(mutant) = observe(
5446 scenario,
5447 baseline,
5448 &survivor.candidate.edits,
5449 Some(&value),
5450 )?
5451 else {
5452 return Ok(None);
5453 };
5454 if mutant.equals_expected != Some(false) || value == mutant.value {
5455 return Ok(None);
5456 }
5457 let Some(checked) = observe(scenario, baseline, &[], Some(&value))?
5458 else {
5459 return Ok(None);
5460 };
5461 if checked.equals_expected != Some(true) || checked.value != value {
5462 return Ok(None);
5463 }
5464 Ok(scenario.verified(value, mutant.value))
5465 })();
5466 match distinction {
5467 Ok(Some(mut verified)) => {
5468 let edits = survivor.candidate.edits.len();
5469 verified.individually_killed = (edits > 1).then_some(edits);
5470 evidence = Some(verified);
5471 break;
5472 }
5473 Ok(None) => {}
5474 Err(err) => note(&format!(
5475 "could not check a distinguishing test for {}: {err:#}",
5476 scenario.expression,
5477 )),
5478 }
5479 }
5480 state.write(&root_file, &restore)?;
5481 progress.complete(Outcome::Pass.into());
5482 if let Some(index) = survivor.existing {
5483 if let Some(evidence) = evidence {
5484 report.findings[index].set_witness(evidence);
5485 }
5486 } else {
5487 report.findings.push(Finding::Survivor {
5488 at: survivor.at,
5489 survivors: vec![survivor.candidate.description.clone()],
5490 witness: evidence,
5491 });
5492 }
5493 }
5494 Ok(())
5495 },
5496 )?;
5497 }
5498
5499 report.record_evaluation();
5500 report.sort_findings();
5501 let places: Vec<FilePlaces> = files
5502 .iter()
5503 .map(|file| FilePlaces {
5504 display: &file.display,
5505 source: &file.original,
5506 lines: &file.lines,
5507 places: &file.places,
5508 })
5509 .collect();
5510 name_findings(&mut report.findings, &places);
5511
5512 let files_with_findings: BTreeSet<&str> = report
5514 .findings
5515 .iter()
5516 .map(|finding| finding.at().file.as_str())
5517 .collect();
5518 let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
5519 .iter()
5520 .filter(|file| files_with_findings.contains(file.display.as_str()))
5521 .map(|f| {
5522 (
5523 f.display.as_str(),
5524 crate::baseline::ignored_lines(&f.original),
5525 )
5526 })
5527 .collect();
5528 let known = match &options.baseline {
5529 Some(path) => Some(crate::baseline::load(path)?),
5530 None => None,
5531 };
5532 let before = report.findings.len();
5533 report.findings.retain(|finding| {
5534 let at = finding.at();
5535 !ignored
5536 .get(at.file.as_str())
5537 .is_some_and(|lines| lines.contains_key(&at.line))
5538 });
5539 if let Some(path) = &options.write_baseline {
5540 crate::baseline::write(path, &report.findings)?;
5541 }
5542 report
5543 .findings
5544 .retain(|finding| !known.as_ref().is_some_and(|known| known.knows(finding)));
5545 report.suppressed = before - report.findings.len();
5546 if let Some(checkpoint) = &checkpoint {
5547 checkpoint.finish()?;
5548 }
5549 Ok(report)
5550}
5551
5552fn repository_prefix(dir: &Path) -> String {
5556 let shown = Command::new("git")
5557 .arg("-C")
5558 .arg(dir)
5559 .args(["rev-parse", "--show-prefix"])
5560 .stderr(Stdio::null())
5561 .output();
5562 match shown {
5563 Ok(output) if output.status.success() => {
5564 String::from_utf8_lossy(&output.stdout).trim().to_string()
5565 }
5566 _ => String::new(),
5567 }
5568}
5569
5570fn spread(count: usize, wanted: usize) -> Vec<usize> {
5573 let wanted = wanted.min(count);
5574 (0..wanted).map(|nth| nth * count / wanted).collect()
5575}
5576
5577struct FilePlaces<'a> {
5579 display: &'a str,
5580 source: &'a str,
5581 lines: &'a scope::LineIndex,
5582 places: &'a [(usize, usize, String)],
5584}
5585
5586fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
5591 let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
5592 for finding in findings {
5593 by_file
5594 .entry(finding.at().file.clone())
5595 .or_default()
5596 .push(finding);
5597 }
5598 for file in files {
5599 let Some(findings) = by_file.remove(file.display) else {
5600 continue;
5601 };
5602 let items = instrument::named_items(file.source);
5603 let index = instrument::ItemIndex::new(&items);
5604 let item_at = |line, column| {
5605 file.lines
5606 .offset_of(file.source, line, column)
5607 .map_or("", |offset| index.at(offset))
5608 };
5609 let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
5610 for (line, column, code) in file.places {
5611 positions
5612 .entry((item_at(*line, *column), code))
5613 .or_default()
5614 .push((*line, *column));
5615 }
5616 for places in positions.values_mut() {
5617 places.sort_unstable();
5618 places.dedup();
5619 }
5620 for finding in findings {
5621 let kind = finding.kind();
5622 let at = finding.at_mut();
5623 let item = item_at(at.line, at.column);
5624 let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
5625 places.partition_point(|&place| place < (at.line, at.column))
5626 });
5627 at.item = item.to_string();
5628 at.id = report::finding_id(kind, at, nth);
5629 }
5630 }
5631}
5632
5633fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
5635 match &site.kind {
5636 SiteKind::Cmp { .. } => plan::CmpOp::ALL
5637 .into_iter()
5638 .find(|op| op.symbol() == mutant.into)
5639 .map_or(Mutation::Negate, Mutation::Op),
5640 SiteKind::Arith { op, .. } => {
5641 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
5642 Mutation::ArithSwap
5643 } else {
5644 Mutation::ArithSwap2
5645 }
5646 }
5647 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
5648 SiteKind::Logic { .. } => Mutation::LogicSwap,
5649 SiteKind::Not { .. } => Mutation::DropNot,
5650 SiteKind::Range { .. } => Mutation::RangeEnd,
5651 _ => Mutation::Delete,
5654 }
5655}
5656
5657fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
5666 let mut all = vec![mutation_of(site, mutant)];
5667 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
5668 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
5669 if into == op.negated() && (integers || !an_order_is_needed) {
5670 all.push(Mutation::Negate);
5671 }
5672 match (op, into) {
5673 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
5674 all.push(Mutation::Shift(1))
5675 }
5676 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
5677 all.push(Mutation::Shift(-1))
5678 }
5679 _ => {}
5680 }
5681 }
5682 all
5683}
5684
5685fn describe_effects(
5688 changes: &BTreeMap<String, BTreeSet<Change>>,
5689 sites: &BTreeMap<u32, (&str, &Site)>,
5690) -> Vec<String> {
5691 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
5692 for (test, found) in changes {
5693 for change in found {
5694 by_change.entry(change).or_default().push(test);
5695 }
5696 }
5697 if by_change.is_empty() {
5698 return vec![
5699 "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(),
5700 ];
5701 }
5702 let mut out = vec![];
5703 for (change, tests) in by_change.iter().take(3) {
5704 let Some((file, site)) = sites.get(&change.site()) else {
5705 continue;
5706 };
5707 let code = report::location(file, site).code;
5708 let at = format!("{file}:{}", site.line);
5709 let who = match tests[..] {
5710 ["?"] => "a test".to_string(),
5711 [one] => format!("`{one}`"),
5712 [first, ..] => format!("`{first}` (and {} more)", tests.len() - 1),
5713 [] => continue,
5714 };
5715 out.push(match change {
5716 Change::Returns { value, .. } => {
5717 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
5718 }
5719 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
5720 Change::NoLongerRuns { .. } => {
5721 format!("with the mutant, {who} no longer runs `{code}` ({at})")
5722 }
5723 Change::NewOutcome { .. } => {
5724 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
5725 }
5726 });
5727 }
5728 if by_change.len() > 3 {
5729 out.push(format!("(and {} more such changes)", by_change.len() - 3));
5730 }
5731 out
5732}
5733
5734#[cfg(test)]
5735mod tests {
5736 use super::*;
5737 use crate::trace::UNKNOWN_TEST;
5738
5739 #[test]
5740 fn explicit_timeout_conflict_matches_the_coverage_table() {
5741 for row in include_str!("../tests/data/timeout-baseline.pict.tsv")
5742 .lines()
5743 .skip(1)
5744 {
5745 let columns: Vec<_> = row.split('\t').collect();
5746 let &[limit, baseline, selection] = columns.as_slice() else {
5747 panic!("invalid PICT row: {row}");
5748 };
5749 let timeout = (limit == "explicit").then_some(Duration::from_secs(1));
5750 let measured = Duration::from_millis(match baseline {
5751 "below" => 999,
5752 "equal" => 1_000,
5753 "above" => 1_001,
5754 _ => panic!("invalid baseline: {baseline}"),
5755 });
5756 let selected_count = match selection {
5757 "full" => None,
5758 "all-names" => Some(2),
5759 "filtered" => Some(1),
5760 _ => panic!("invalid selection: {selection}"),
5761 };
5762 let expected = limit == "explicit" && baseline != "below" && selection != "filtered";
5763 assert_eq!(
5764 explicit_timeout_conflict(timeout, measured, selected_count, 2).is_some(),
5765 expected,
5766 "{row}"
5767 );
5768 }
5769 }
5770
5771 #[test]
5772 fn campaign_phase_combinations() {
5773 let rows = include_str!("../tests/data/campaign-phases.pict.tsv");
5774 for line in rows.lines().skip(1) {
5775 let columns: Vec<_> = line.split('\t').collect();
5776 let &[baselines, workers, policy, verdict] = columns.as_slice() else {
5777 panic!("invalid PICT row: {line}");
5778 };
5779 let count = |value| if value == "one" { 1 } else { 2 };
5780 let ready = std::sync::Barrier::new(count(baselines));
5781 let baselines = run_pool(2, count(baselines), |index| {
5782 ready.wait();
5783 Ok(index)
5784 })
5785 .unwrap();
5786 assert_eq!(baselines, [0, 1]);
5787
5788 let serial = policy == "serial";
5789 let workers = count(workers);
5790 let results = evaluate_jobs(
5791 2,
5792 workers,
5793 serial,
5794 false,
5795 "test",
5796 None,
5797 &|index, sharing| {
5798 let time_out =
5799 index == 0 && verdict != "pass" && (sharing > 1 || verdict == "timeout");
5800 let unable = index == 0 && verdict == "unable" && sharing == 1;
5801 Ok(JobResult {
5802 first_pass_timeout: false,
5803 unconfirmed_timeout: false,
5804 survived: (!time_out && !unable).then(|| vec![index.to_string()]),
5805 timed_out: time_out,
5806 unable,
5807 })
5808 },
5809 )
5810 .unwrap();
5811 assert_eq!(results[1].survived.as_deref(), Some(&["1".to_owned()][..]));
5812 let mut stats = report::TimeoutRechecks::default();
5813 stats.include(&results[0]);
5814 let first_pass = usize::from(workers == 2 && verdict != "pass");
5815 assert_eq!(stats.first_pass, first_pass, "{line}");
5816 assert_eq!(
5817 stats.confirmed,
5818 usize::from(first_pass == 1 && serial && verdict == "timeout"),
5819 "{line}"
5820 );
5821 assert_eq!(
5822 stats.recovered,
5823 usize::from(first_pass == 1 && serial && verdict == "recovered"),
5824 "{line}"
5825 );
5826 assert_eq!(
5827 stats.unconfirmed,
5828 usize::from(first_pass == 1 && (!serial || verdict == "unable")),
5829 "{line}"
5830 );
5831 }
5832 }
5833
5834 #[cfg(unix)]
5835 #[test]
5836 fn mutant_timeout_uses_the_measured_filter_and_an_explicit_override_wins() {
5837 use std::os::unix::fs::PermissionsExt;
5838 let dir = scratch("filtered-timeout");
5839 let exe = dir.join("runner");
5840 fs::write(
5841 &exe,
5842 "#!/bin/sh\n[ \"$2\" = --exact ] && [ \"$3\" = fast ]\n",
5843 )
5844 .unwrap();
5845 fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
5846 let mut bin = TestBinary {
5847 name: "tests".into(),
5848 cwd: dir.clone(),
5849 marks: marks_dir(&dir).unwrap(),
5850 git_ceiling: dir.clone(),
5851 work_lock: None,
5852 tests: ["fast".to_string(), "slow".to_string()]
5853 .into_iter()
5854 .collect(),
5855 runner: Runner::Exe(exe),
5856 baseline: Duration::from_secs(70),
5857 untraced_baseline: None,
5858 timeout_diagnostic: std::sync::Once::new(),
5859 traced: Duration::from_secs(70),
5860 timeout: None,
5861 wrapper_grace: Duration::ZERO,
5862 report_slow: false,
5863 filtered_timings: Default::default(),
5864 trace: Trace::default(),
5865 effects_baseline: std::sync::OnceLock::new(),
5866 };
5867 assert!(bin.filtered_limit(Some(&["fast".to_string()]), false) < Duration::from_secs(7));
5868 assert_eq!(
5869 bin.filtered_limit(Some(&["slow".to_string()]), false),
5870 Duration::from_secs(355)
5871 );
5872 assert_eq!(bin.filtered_limit(None, false), Duration::from_secs(355));
5873 assert_eq!(bin.filtered_timings.lock().unwrap().len(), 2);
5874 bin.timeout = Some(Duration::from_secs(8));
5875 assert_eq!(
5876 bin.filtered_limit(Some(&["fast".to_string()]), false),
5877 Duration::from_secs(8)
5878 );
5879 fs::remove_dir_all(dir).unwrap();
5880 }
5881
5882 #[test]
5883 fn failed_build_retains_spanless_and_source_diagnostics() {
5884 let stdout = r#"
5885{"reason":"compiler-message","message":{"level":"error","message":"linking with cc failed","rendered":"ld: library not found for -liconv","spans":[]}}
5886{"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}]}}
5887"#;
5888 let failed = parse_build_output(stdout, &["p"]);
5889 assert_eq!(failed.errors.len(), 1);
5890 let text = failed.diagnostics.join("\n");
5891 assert!(text.contains("ld: library not found for -liconv"), "{text}");
5892 assert!(text.contains("source error"), "{text}");
5893 }
5894
5895 #[test]
5896 fn test_build_scope_uses_only_known_local_features() {
5897 let package = Package {
5898 name: "pkg".to_owned(),
5899 dependencies: vec![],
5900 features: BTreeMap::from([
5901 ("default".to_owned(), vec!["alias".to_owned()]),
5902 (
5903 "alias".to_owned(),
5904 vec!["extra".to_owned(), "dep/extra".to_owned()],
5905 ),
5906 ("extra".to_owned(), vec![]),
5907 ("separate".to_owned(), vec![]),
5908 ]),
5909 manifest_path: PathBuf::from("workspace/pkg/Cargo.toml"),
5910 targets: vec![],
5911 };
5912 let enabled = |workspace: &str, features: &str, no_default_features, all_features| {
5913 package.enabled_local_features(
5914 Path::new(workspace),
5915 &CargoConfig {
5916 features: vec![features.to_owned()],
5917 no_default_features,
5918 all_features,
5919 locked: false,
5920 },
5921 )
5922 };
5923 let root = "workspace/pkg";
5924 assert_eq!(
5925 enabled(root, "", false, false),
5926 BTreeSet::from(["default", "alias", "extra"])
5927 );
5928 assert_eq!(
5929 enabled(root, "", true, true),
5930 BTreeSet::from(["default", "alias", "extra", "separate"])
5931 );
5932 assert_eq!(
5933 enabled(root, "alias, separate", true, false),
5934 BTreeSet::from(["alias", "extra", "separate"])
5935 );
5936 assert_eq!(
5937 enabled("workspace", "extra other/separate", true, false),
5938 BTreeSet::new()
5939 );
5940 assert_eq!(
5941 enabled("workspace", "pkg/extra other/separate", true, false),
5942 BTreeSet::from(["extra"])
5943 );
5944 }
5945
5946 #[test]
5947 fn test_build_scope_preserves_cargo_target_eligibility() {
5948 let target = |name, kind, test, required_features: &[&str]| {
5949 serde_json::from_value(serde_json::json!({
5950 "name": name, "kind": [kind], "test": test, "src_path": "ignored.rs",
5951 "required-features": required_features,
5952 }))
5953 .unwrap()
5954 };
5955 let package = |name: &str, targets| Package {
5956 name: name.to_owned(),
5957 dependencies: vec![],
5958 targets,
5959 manifest_path: PathBuf::new(),
5960 features: BTreeMap::from([("extra".to_owned(), vec![])]),
5961 };
5962 let first = package(
5963 "first",
5964 vec![
5965 target("first", "proc-macro", true, &[]),
5966 target("name", "bin", true, &[]),
5967 target("name", "example", true, &[]),
5968 target("name", "bench", true, &[]),
5969 target("name", "test", true, &[]),
5970 target("conditional", "test", true, &["extra"]),
5971 target("dependency_feature", "test", true, &["dep/extra"]),
5972 target("disabled", "test", false, &[]),
5973 target("glob[a]", "test", true, &[]),
5974 target("--leading-dash", "test", true, &[]),
5975 target("build-script-build", "custom-build", false, &[]),
5976 ],
5977 );
5978 let second = package(
5979 "second",
5980 vec![
5981 target("second", "staticlib", true, &[]),
5982 target("name", "test", false, &[]),
5983 ],
5984 );
5985 let flags = |packages: &[&Package], names: &[&str], all| {
5986 test_build_flags(
5987 packages,
5988 &names.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
5989 Path::new("workspace"),
5990 &CargoConfig {
5991 all_features: all,
5992 ..CargoConfig::default()
5993 },
5994 )
5995 };
5996 assert_eq!(
5997 flags(&[&first], &["name", "first", "unknown"], false).unwrap(),
5998 [
5999 "--bench=name",
6000 "--bin=name",
6001 "--example=name",
6002 "--lib",
6003 "--test=name"
6004 ]
6005 );
6006 assert_eq!(flags(&[&first], &[], false), None);
6007 assert_eq!(flags(&[&first], &["unknown", "disabled"], false), None);
6008 assert_eq!(flags(&[&first], &["glob[a]"], false), None);
6009 assert_eq!(
6010 flags(&[&first], &["--leading-dash"], false).unwrap(),
6011 ["--test=--leading-dash"]
6012 );
6013 assert_eq!(flags(&[&first], &["name", "conditional"], false), None);
6014 assert_eq!(flags(&[&first], &["dependency_feature"], true), None);
6015 assert_eq!(
6016 flags(&[&first], &["conditional"], true).unwrap(),
6017 ["--test=conditional"]
6018 );
6019 assert_eq!(flags(&[&first, &second], &["name"], false), None);
6020 assert_eq!(flags(&[&first, &second], &["first"], false), None);
6021 assert_eq!(
6022 flags(&[&first, &second], &["first", "second"], false).unwrap(),
6023 ["--lib"]
6024 );
6025 }
6026
6027 #[test]
6028 fn parses_cargo_json_messages() {
6029 let stdout = concat!(
6030 r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":false},"executable":null}"#,
6031 "\n",
6032 r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":true},"executable":"/t/p-abc"}"#,
6033 "\n",
6034 r#"{"reason":"compiler-artifact","package_id":"dep 1.0.0","target":{"name":"dep","kind":["lib"]},"profile":{"test":true},"executable":"/t/dep-abc"}"#,
6035 "\n",
6036 r#"{"reason":"compiler-message","message":{"level":"warning","rendered":"w","spans":[{"file_name":"src/lib.rs","byte_start":1,"line_start":1,"is_primary":true}]}}"#,
6037 "\n",
6038 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}]}}"#,
6039 "\n",
6040 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}]}}"#,
6041 "\n",
6042 r#"{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}"#,
6043 "\n",
6044 "not json\n",
6045 r#"{"reason":"build-finished","success":false}"#,
6046 "\n",
6047 );
6048 let out = parse_build_output(stdout, &["p", "other"]);
6049 assert_eq!(
6050 out.test_binaries,
6051 [(
6052 "p".to_string(),
6053 PathBuf::from("/t/p-abc"),
6054 "p".to_string(),
6055 vec!["lib".to_string()]
6056 )]
6057 );
6058 let both = parse_build_output(stdout, &["dep", "p"]);
6060 let owners: Vec<&str> = both.test_binaries.iter().map(|b| b.2.as_str()).collect();
6061 assert_eq!(owners, ["dep", "p"]);
6062 assert_eq!(
6063 out.errors,
6064 [CompileError {
6065 primary: vec![ErrorSpan {
6066 file: "src/lib.rs".into(),
6067 byte_start: 40,
6068 line: 3
6069 }],
6070 secondary: vec![ErrorSpan {
6071 file: "src/lib.rs".into(),
6072 byte_start: 2,
6073 line: 1
6074 }],
6075 rendered: "E0308".into(),
6076 }]
6077 );
6078 }
6079
6080 #[test]
6081 fn package_ids_are_matched_by_name() {
6082 assert!(is_package(
6083 "path+file:///w/target/tmt/src#eligibility@0.0.0",
6084 "eligibility"
6085 ));
6086 assert!(is_package(
6087 "path+file:///w/eligibility#0.1.0",
6088 "eligibility"
6089 ));
6090 assert!(is_package(
6091 "eligibility 0.1.0 (path+file:///w)",
6092 "eligibility"
6093 ));
6094 assert!(!is_package(
6095 "path+file:///w/eligibility#other@0.1.0",
6096 "eligibility-core"
6097 ));
6098 assert!(!is_package(
6099 "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.0",
6100 "eligibility"
6101 ));
6102 }
6103
6104 #[test]
6105 fn test_filter_falls_back_to_the_whole_binary() {
6106 let set = |names: &[&str]| {
6107 names
6108 .iter()
6109 .map(|n| n.to_string())
6110 .collect::<BTreeSet<String>>()
6111 };
6112 let known = set(&["tests::a", "tests::b", "tests::c"]);
6113 assert_eq!(
6114 test_filter(&set(&["tests::a", "tests::b"]), &known),
6115 Some(vec!["tests::a".to_string(), "tests::b".to_string()])
6116 );
6117 assert_eq!(test_filter(&set(&["tests::a", UNKNOWN_TEST]), &known), None);
6119 assert_eq!(test_filter(&set(&["tests::a", "worker"]), &known), None);
6121 assert_eq!(test_filter(&set(&["worker"]), &known), None);
6122
6123 let many: BTreeSet<String> = (0..=MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
6124 assert_eq!(test_filter(&many, &many), None);
6125 let limit: BTreeSet<String> = (0..MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
6126 assert!(test_filter(&limit, &limit).is_some());
6127 }
6128
6129 #[test]
6130 fn libtest_listing() {
6131 let listing =
6132 "tests::a: test\ntests::nested::b: test\nbench_it: benchmark\n\n2 tests, 1 benchmark\n";
6133 assert_eq!(
6134 parse_test_list(listing).into_iter().collect::<Vec<_>>(),
6135 ["tests::a", "tests::nested::b"]
6136 );
6137 }
6138
6139 #[test]
6140 fn domains_from_type_bounds() {
6141 let u8s = crate::trace::TypeBounds {
6142 lhs: (0, 255),
6143 rhs: (0, 255),
6144 };
6145 assert_eq!(
6146 domain_of(LiteralSide::Rhs(18), Some(&u8s)),
6147 Some((-18, 237))
6148 );
6149 assert_eq!(
6150 domain_of(LiteralSide::Lhs(18), Some(&u8s)),
6151 Some((-237, 18))
6152 );
6153 assert_eq!(domain_of(LiteralSide::None, Some(&u8s)), None);
6154 assert_eq!(domain_of(LiteralSide::Rhs(18), None), None);
6155 let wide = crate::trace::TypeBounds {
6156 lhs: (i128::MIN, 0),
6157 rhs: (0, 0),
6158 };
6159 assert_eq!(
6160 domain_of(LiteralSide::Rhs(1), Some(&wide)),
6161 None,
6162 "overflow is not a domain"
6163 );
6164 }
6165
6166 #[test]
6167 fn a_primary_blame_does_not_inspect_later_fallbacks() {
6168 let copy = Path::new("/work");
6169 let source = "pub fn f(n: u32) -> bool { n >= 4 }";
6170 let make = |name: &str, rendered: bool| {
6171 let sites = instrument::discover(source, 0).unwrap().sites;
6172 let output = rendered.then(|| instrument::render(source, &sites, &|_| true));
6173 SourceFile {
6174 display: name.to_string(),
6175 path: copy.join(name),
6176 owners: BTreeSet::new(),
6177 lines: scope::LineIndex::new(source),
6178 original: source.to_string(),
6179 places: vec![],
6180 sites,
6181 rebuild_sites: vec![],
6182 rendered: output,
6183 }
6184 };
6185 let files = [make("primary.rs", true), make("secondary.rs", false)];
6186 let rendered = files[0].rendered.as_ref().unwrap();
6187 let probe = rendered.text.find("__tmt_rt::").unwrap();
6188 let span = |file: &str, byte_start| ErrorSpan {
6189 file: file.to_string(),
6190 byte_start,
6191 line: 1,
6192 };
6193 let error = CompileError {
6194 primary: vec![span("primary.rs", probe)],
6195 secondary: vec![span("secondary.rs", 0)],
6196 rendered: String::new(),
6197 };
6198 assert_eq!(
6199 blame_error(&error, &files, copy, &HashSet::new()),
6200 [rendered.inserted_by(probe).unwrap()]
6201 );
6202 }
6203
6204 #[test]
6205 fn repair_reuses_a_render_but_still_corrects_the_working_copy() {
6206 let dir = scratch("render-repair");
6207 let root = dir.join("work/src");
6208 let path = root.join("f.rs");
6209 let state = WorkCopy::open(&dir.join("work"), &root);
6210 let source = "pub fn f(n: u32) -> bool { n >= 4 }";
6211 let suffix = "\n// root suffix\n";
6212 for row in include_str!("../tests/data/repair-reuse.pict.tsv")
6213 .lines()
6214 .skip(1)
6215 {
6216 let columns: Vec<_> = row.split('\t').collect();
6217 let [cache, which, disk] = columns.as_slice() else {
6218 panic!("{row}")
6219 };
6220 let sites = instrument::discover(source, 1).unwrap().sites;
6221 let id = sites
6222 .iter()
6223 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
6224 .unwrap()
6225 .id;
6226 let disabled = match *which {
6227 "here" => HashSet::from([id]),
6228 "elsewhere" => HashSet::from([u32::MAX]),
6229 _ => HashSet::new(),
6230 };
6231 let before = instrument::render(source, &sites, &|_| true);
6232 let expected = instrument::render(source, &sites, &|id| !disabled.contains(&id));
6233 let original_text = format!("{}{suffix}", before.text);
6234 fs::write(
6235 &path,
6236 if *disk == "rendered" {
6237 &original_text
6238 } else {
6239 source
6240 },
6241 )
6242 .unwrap();
6243 let mut file = SourceFile {
6244 display: "f.rs".to_string(),
6245 path: path.clone(),
6246 owners: BTreeSet::new(),
6247 lines: scope::LineIndex::new(source),
6248 original: source.to_string(),
6249 places: vec![],
6250 sites,
6251 rebuild_sites: vec![],
6252 rendered: (*cache == "present").then_some(before),
6253 };
6254 write_rendered(&mut file, &state, suffix, &disabled, &disabled).unwrap();
6255 assert_eq!(
6256 fs::read_to_string(&path).unwrap(),
6257 format!("{}{suffix}", expected.text),
6258 "{row}"
6259 );
6260 let rendered = file.rendered.unwrap();
6261 assert_eq!(rendered.text, expected.text, "{row}");
6262 for offset in 0..rendered.text.len() {
6263 assert_eq!(
6264 rendered.to_original(offset),
6265 expected.to_original(offset),
6266 "{row}"
6267 );
6268 assert_eq!(
6269 rendered.inserted_by(offset),
6270 expected.inserted_by(offset),
6271 "{row}"
6272 );
6273 }
6274 }
6275 fs::remove_dir_all(dir).unwrap();
6276 }
6277
6278 #[test]
6279 fn source_graph_shares_edges_without_sharing_resolution_or_ownership() {
6280 let scratch = scratch("shared-source-graph");
6281 let copy = scratch.join("work/src");
6282 let before = copy.join("before.rs");
6283 let library = copy.join("lib.rs");
6284 let after = copy.join("after.rs");
6285 let shared = copy.join("shared.rs");
6286 let leaf = copy.join("leaf.rs");
6287 let test_helper = copy.join("test_helper.rs");
6288 let nested_leaf = copy.join("shared/leaf.rs");
6289 let sources = BTreeMap::from([
6290 (before.clone(), r#"#[path = "shared.rs"] mod dep;"#),
6291 (
6292 library.clone(),
6293 r#"mod shared; #[path = "shared.rs"] mod dep;"#,
6294 ),
6295 (after.clone(), r#"include!("shared.rs");"#),
6296 (shared.clone(), "mod leaf; #[cfg(test)] mod test_helper;"),
6297 (leaf.clone(), "fn top() {}"),
6298 (test_helper.clone(), "fn testing() {}"),
6299 (nested_leaf.clone(), "fn nested() {}"),
6300 ]);
6301 for path in sources.keys() {
6302 fs::create_dir_all(path.parent().unwrap()).unwrap();
6303 fs::File::create(path).unwrap();
6304 }
6305 let mut reads = BTreeMap::new();
6306 let graph = source_graph(
6307 [
6308 (before.clone(), false),
6309 (library.clone(), true),
6310 (after.clone(), false),
6311 ],
6312 ©,
6313 |path| {
6314 *reads.entry(path.to_path_buf()).or_insert(0) += 1;
6315 Ok(sources.get(path).map(|source| (*source).to_string()))
6316 },
6317 )
6318 .unwrap();
6319 fs::remove_dir_all(scratch).unwrap();
6320
6321 assert_eq!(
6322 reads[&shared], 2,
6323 "one load in each of two resolution contexts"
6324 );
6325 assert_eq!(reads[&leaf], 1);
6326 assert_eq!(reads[&test_helper], 1);
6327 assert!(!graph.contains_key(&test_helper));
6328 assert_eq!(reads[&nested_leaf], 1);
6329 for path in [&leaf, &shared] {
6330 assert_eq!(
6331 graph[path].consumers,
6332 BTreeSet::from([before.clone(), library.clone(), after.clone()])
6333 );
6334 assert_eq!(graph[path].production, BTreeSet::from([library.clone()]));
6335 }
6336 assert_eq!(
6337 graph[&nested_leaf].consumers,
6338 BTreeSet::from([library.clone()])
6339 );
6340 assert_eq!(graph[&nested_leaf].production, BTreeSet::from([library]));
6341 assert!(!graph.contains_key(&before) && !graph.contains_key(&after));
6342 }
6343
6344 #[test]
6345 fn out_of_line_module_locations() {
6346 let file = Path::new("src/cli.rs");
6347 let statements = "mod child; #[path = \"spec/support.rs\"] mod helper;";
6348 let roots = crate::modules::external(statements, file, Path::new("src"));
6349 assert_eq!(
6350 roots[0].paths,
6351 [
6352 PathBuf::from("src/child.rs"),
6353 PathBuf::from("src/child/mod.rs")
6354 ]
6355 );
6356 assert_eq!(roots[1].paths, [PathBuf::from("src/spec/support.rs")]);
6357 let module = crate::modules::external(statements, file, Path::new("src/cli"));
6358 assert_eq!(module[0].paths[0], PathBuf::from("src/cli/child.rs"));
6359 assert_eq!(module[1].paths[0], PathBuf::from("src/spec/support.rs"));
6360 }
6361
6362 #[test]
6363 fn path_dependencies_outside_the_workspace_become_absolute() {
6364 let manifest = r#"[package]
6365name = "app"
6366
6367[dependencies]
6368serde = "1"
6369core = { path = "../core" } # inside the workspace: kept
6370outside = { path = "../../outside", version = "1" }
6371
6372[dev-dependencies.helper]
6373path = "../../../far/helper"
6374
6375[target.'cfg(unix)'.dependencies]
6376unix-only = { path = "../../unix" }
6377
6378[patch.crates-io]
6379serde = { path = "../../serde-fork" }
6380"#;
6381 let out = absolutize_path_dependencies(
6382 manifest,
6383 Path::new("/w/ws/app"),
6384 Path::new("/w/ws"),
6385 Path::new("/copy"),
6386 )
6387 .unwrap()
6388 .expect("something to rewrite");
6389 assert!(
6390 out.contains(r#"core = { path = "../core" } # inside the workspace: kept"#),
6391 "{out}"
6392 );
6393 assert!(
6394 out.contains(r#"outside = { path = "/w/outside", version = "1" }"#),
6395 "{out}"
6396 );
6397 assert!(out.contains("path = \"/far/helper\""), "{out}");
6398 assert!(out.contains(r#"unix-only = { path = "/w/unix" }"#), "{out}");
6399 assert!(
6400 out.contains(r#"serde = { path = "/w/serde-fork" }"#),
6401 "{out}"
6402 );
6403 assert!(out.contains("serde = \"1\""), "{out}");
6404
6405 let inside = "[dependencies]\ncore = { path = \"../core\" }\n[workspace.dependencies]\nx = { path = \"x\" }\n";
6406 assert_eq!(
6407 absolutize_path_dependencies(
6408 inside,
6409 Path::new("/w/ws/app"),
6410 Path::new("/w/ws"),
6411 Path::new("/copy")
6412 )
6413 .unwrap(),
6414 None
6415 );
6416 let ws = "[workspace.dependencies]\nshared = { path = \"../shared\" }\n";
6417 let out = absolutize_path_dependencies(
6418 ws,
6419 Path::new("/w/ws"),
6420 Path::new("/w/ws"),
6421 Path::new("/copy"),
6422 )
6423 .unwrap()
6424 .unwrap();
6425 assert!(out.contains(r#"shared = { path = "/w/shared" }"#), "{out}");
6426 assert!(
6427 absolutize_path_dependencies(
6428 "not [ toml",
6429 Path::new("/w"),
6430 Path::new("/w"),
6431 Path::new("/copy")
6432 )
6433 .is_err()
6434 );
6435 assert_eq!(normalize(Path::new("/a/./b/../c")), PathBuf::from("/a/c"));
6436 let absolute = "[dependencies]\nhelper = { path = \"/w/ws/helper\" }\n";
6438 let out = absolutize_path_dependencies(
6439 absolute,
6440 Path::new("/w/ws/app"),
6441 Path::new("/w/ws"),
6442 Path::new("/copy"),
6443 )
6444 .unwrap()
6445 .unwrap();
6446 assert!(
6447 out.contains(r#"helper = { path = "/copy/helper" }"#),
6448 "{out}"
6449 );
6450 }
6451
6452 #[test]
6453 fn pool_runs_every_job_once_and_keeps_the_order() {
6454 use std::sync::atomic::{AtomicUsize, Ordering};
6455 for workers in [0, 1, 2, 3, 8, 100] {
6456 for count in [0, 1, 2, 7, 50] {
6457 let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
6458 let results = run_pool(count, workers, |i| {
6459 calls[i].fetch_add(1, Ordering::SeqCst);
6460 std::thread::yield_now();
6461 Ok(i * 10)
6462 })
6463 .unwrap();
6464 assert_eq!(
6465 results,
6466 (0..count).map(|i| i * 10).collect::<Vec<_>>(),
6467 "workers={workers}"
6468 );
6469 assert!(
6470 calls.iter().all(|c| c.load(Ordering::SeqCst) == 1),
6471 "workers={workers} count={count}"
6472 );
6473 }
6474 }
6475 let failed = run_pool(5, 3, |i| {
6476 if i == 3 {
6477 Err(anyhow!("job {i} broke"))
6478 } else {
6479 Ok(i)
6480 }
6481 });
6482 assert_eq!(failed.unwrap_err().to_string(), "job 3 broke");
6483 }
6484
6485 #[test]
6486 fn operand_ranges_ignore_wrapping_parentheses() {
6487 assert_eq!(core_range(10, "a > 0"), (10, 15));
6488 assert_eq!(core_range(10, "(a > 0)"), (11, 16));
6489 assert_eq!(core_range(10, " ( (a > 0) ) "), (14, 19));
6490 assert_eq!(core_range(0, "(a) && (b)"), (0, 10));
6492 assert_eq!(core_range(0, "f(a)"), (0, 4));
6493 assert_eq!(core_range(3, "()"), (4, 4));
6494 assert_eq!(core_range(0, "(a"), (0, 2));
6496 assert_eq!(core_range(0, "a)"), (0, 2));
6497 assert_eq!(core_range(0, ")"), (0, 1));
6498 }
6499
6500 #[test]
6501 fn pool_never_uses_more_threads_than_asked() {
6502 for workers in [1, 2] {
6503 let seen = std::sync::Mutex::new(HashSet::new());
6504 run_pool(6, workers, |_| {
6505 seen.lock().unwrap().insert(std::thread::current().id());
6506 std::thread::sleep(Duration::from_millis(30));
6508 Ok(())
6509 })
6510 .unwrap();
6511 assert_eq!(seen.lock().unwrap().len(), workers);
6512 }
6513 }
6514
6515 #[test]
6516 fn workspace_dependents() {
6517 let package = |name: &str, deps: &[&str]| Package {
6518 name: name.to_string(),
6519 features: BTreeMap::new(),
6520 dependencies: deps
6521 .iter()
6522 .map(|d| Dependency {
6523 name: d.to_string(),
6524 })
6525 .collect(),
6526 manifest_path: PathBuf::new(),
6527 targets: vec![],
6528 };
6529 let packages = [
6530 package("core", &["serde"]),
6531 package("mid", &["core"]),
6532 package("app", &["mid", "other"]),
6533 package("other", &[]),
6534 package("cycle", &["app", "core"]),
6535 ];
6536 assert_eq!(dependents_of("core", &packages), ["app", "cycle", "mid"]);
6537 assert_eq!(dependents_of("mid", &packages), ["app", "cycle"]);
6538 assert_eq!(dependents_of("other", &packages), ["app", "cycle"]);
6539 assert!(dependents_of("app", &packages) == ["cycle"]);
6540 assert!(dependents_of("nobody", &packages).is_empty());
6541 let mutual = [package("x", &["y"]), package("y", &["x"])];
6543 assert_eq!(dependents_of("x", &mutual), ["y"]);
6544 }
6545
6546 #[test]
6547 fn failure_lines_of_libtest() {
6548 assert!(is_failure_line("test tests::a ... FAILED"));
6549 assert!(is_failure_line(
6550 "test src/lib.rs - double (line 3) ... FAILED"
6551 ));
6552 assert!(!is_failure_line("test tests::a ... ok"));
6553 assert!(!is_failure_line("test result: FAILED. 1 passed; 1 failed"));
6554 assert!(!is_failure_line("my output says ... FAILED"));
6555 assert!(!is_failure_line(
6556 "test tests::a ... FAILED (but printed by the test)"
6557 ));
6558 }
6559
6560 #[test]
6561 fn effects_in_words() {
6562 let source = "fn f(s: &mut S) -> bool { s.reset(); s.count > 1 }";
6563 let mut found = instrument::discover(source, 0).unwrap().sites;
6564 found.retain(|s| !matches!(s.kind, SiteKind::Body { .. }));
6565 for (id, site) in found.iter_mut().enumerate() {
6566 site.id = id as u32;
6567 }
6568 let sites: BTreeMap<u32, (&str, &Site)> =
6569 found.iter().map(|s| (s.id, ("src/lib.rs", s))).collect();
6570 let texts: Vec<&str> = found.iter().map(|s| s.text.as_str()).collect();
6571 assert_eq!(
6572 texts,
6573 ["fn f(s: &mut S) -> bool", "s.reset();", "s.count > 1"]
6574 );
6575
6576 let set = |list: &[Change]| list.iter().cloned().collect::<BTreeSet<Change>>();
6577 let mut changes = BTreeMap::new();
6578 changes.insert(
6579 "tests::a".to_string(),
6580 set(&[
6581 Change::Returns {
6582 site: 0,
6583 value: true,
6584 },
6585 Change::NowRuns { site: 1 },
6586 ]),
6587 );
6588 changes.insert(
6589 "tests::b".to_string(),
6590 set(&[Change::NowRuns { site: 1 }, Change::NewOutcome { site: 2 }]),
6591 );
6592 changes.insert("?".to_string(), set(&[Change::NoLongerRuns { site: 2 }]));
6593 assert_eq!(
6594 describe_effects(&changes, &sites),
6595 [
6596 "with the mutant, `tests::a` gets `true` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
6597 "with the mutant, `tests::a` (and 1 more) now runs `s.reset();` (src/lib.rs:1)",
6598 "with the mutant, a test no longer runs `s.count > 1` (src/lib.rs:1)",
6599 "(and 1 more such changes)",
6600 ]
6601 );
6602 let mut many = BTreeMap::new();
6604 many.insert(
6605 "tests::a".to_string(),
6606 set(&[
6607 Change::NowRuns { site: 0 },
6608 Change::NowRuns { site: 1 },
6609 Change::NowRuns { site: 2 },
6610 Change::NoLongerRuns { site: 0 },
6611 Change::NoLongerRuns { site: 1 },
6612 Change::NoLongerRuns { site: 2 },
6613 ]),
6614 );
6615 assert_eq!(
6616 describe_effects(&many, &sites).last().map(String::as_str),
6617 Some("(and 3 more such changes)")
6618 );
6619 let mut few = BTreeMap::new();
6621 few.insert(
6622 "tests::a".to_string(),
6623 set(&[
6624 Change::NowRuns { site: 1 },
6625 Change::NewOutcome { site: 2 },
6626 Change::Returns {
6627 site: 0,
6628 value: false,
6629 },
6630 ]),
6631 );
6632 assert_eq!(
6633 describe_effects(&few, &sites),
6634 [
6635 "with the mutant, `tests::a` gets `false` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
6636 "with the mutant, `tests::a` now runs `s.reset();` (src/lib.rs:1)",
6637 "with the mutant, `tests::a` takes `s.count > 1` (src/lib.rs:1) a way it did not before",
6638 ]
6639 );
6640 assert_eq!(
6641 describe_effects(&BTreeMap::new(), &sites),
6642 [
6643 "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"
6644 ]
6645 );
6646 }
6647
6648 #[test]
6649 fn mutant_timeout_scales_with_the_baseline() {
6650 assert_eq!(mutant_timeout(Duration::ZERO), Duration::from_secs(5));
6651 assert_eq!(
6652 mutant_timeout(Duration::from_secs(2)),
6653 Duration::from_secs(15)
6654 );
6655 }
6656
6657 #[cfg(unix)]
6658 #[test]
6659 fn stopping_nextest_reaps_a_runner_that_ignores_termination() {
6660 use std::io::Read as _;
6661 use std::os::unix::process::CommandExt as _;
6662
6663 let mut child = Command::new("sh")
6664 .args(["-c", "trap '' TERM; printf X; while :; do sleep 1; done"])
6665 .process_group(0)
6666 .stdout(Stdio::piped())
6667 .spawn()
6668 .unwrap();
6669 child.stdout.take().unwrap().read_exact(&mut [0]).unwrap();
6670
6671 stop_nextest(&mut child, Duration::from_millis(10));
6672 let status = child.try_wait().unwrap().expect("runner was reaped");
6673 assert!(!status.success());
6674 }
6675
6676 #[test]
6677 fn nextest_counts_only_a_test_failure_as_a_kill() {
6678 assert_eq!(nextest_outcome(Some(0)).unwrap(), Outcome::Pass);
6679 assert_eq!(nextest_outcome(Some(100)).unwrap(), Outcome::Fail);
6680 for code in [Some(4), Some(101), Some(102), Some(105), None] {
6681 assert!(nextest_outcome(code).is_err(), "{code:?}");
6682 }
6683 }
6684
6685 #[test]
6686 fn test_polling_backs_off_and_respects_the_remaining_time() {
6687 let mut delay = TEST_POLL_INITIAL;
6688 for micros in [250, 500, 1_000, 2_000, 4_000, 5_000, 5_000] {
6689 assert_eq!(
6690 next_test_poll(&mut delay, Duration::from_secs(1)),
6691 Duration::from_micros(micros)
6692 );
6693 }
6694 let remaining = Duration::from_micros(120);
6695 assert_eq!(next_test_poll(&mut delay, remaining), remaining);
6696 assert_eq!(next_test_poll(&mut delay, Duration::ZERO), Duration::ZERO);
6697 assert_eq!(delay, Duration::from_millis(5));
6698 }
6699 fn scratch(name: &str) -> PathBuf {
6701 let dir = std::env::temp_dir().join(format!("tmt-{name}-{}", std::process::id()));
6702 let _ = fs::remove_dir_all(&dir);
6703 fs::create_dir_all(dir.join("ws/src")).unwrap();
6704 fs::create_dir_all(dir.join("work/src")).unwrap();
6705 dir.canonicalize().unwrap()
6706 }
6707
6708 #[cfg(unix)]
6709 #[test]
6710 fn a_descendant_cannot_keep_the_completed_runner_output_open() {
6711 use std::os::unix::fs::PermissionsExt as _;
6712
6713 let dir = scratch("descendant-output");
6714 let work = dir.join("work");
6715 let exe = work.join("runner");
6716 fs::write(&exe, "#!/bin/sh\nsleep 8 &\nexit 0\n").unwrap();
6717 fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
6718 let bin = TestBinary {
6719 name: "runner".into(),
6720 cwd: work.join("src"),
6721 marks: marks_dir(&work).unwrap(),
6722 git_ceiling: work,
6723 work_lock: None,
6724 tests: BTreeSet::new(),
6725 runner: Runner::Exe(exe),
6726 baseline: Duration::ZERO,
6727 untraced_baseline: None,
6728 timeout_diagnostic: std::sync::Once::new(),
6729 traced: Duration::ZERO,
6730 timeout: None,
6731 wrapper_grace: Duration::ZERO,
6732 report_slow: false,
6733 filtered_timings: Default::default(),
6734 trace: Trace::default(),
6735 effects_baseline: std::sync::OnceLock::new(),
6736 };
6737 let started = Instant::now();
6738 assert_eq!(
6739 run_binary(
6740 &bin,
6741 None,
6742 &[],
6743 Duration::from_secs(2),
6744 RunOutput::FirstFailure,
6745 1
6746 )
6747 .unwrap(),
6748 Outcome::Pass
6749 );
6750 assert!(
6751 started.elapsed() < Duration::from_secs(6),
6752 "a descendant held the output pipe open"
6753 );
6754 fs::remove_dir_all(dir).unwrap();
6755 }
6756
6757 #[cfg(unix)]
6758 #[test]
6759 fn a_detached_descendant_does_not_hold_the_runner_open() {
6760 let dir = scratch("detached-output");
6761 let work = dir.join("work");
6762 let source = work.join("runner.rs");
6763 let exe = work.join("runner");
6764 fs::write(
6765 &source,
6766 r#"
6767use std::os::unix::process::CommandExt;
6768fn main() {
6769 let child = std::process::Command::new("sleep").arg("8").process_group(0).spawn().unwrap();
6770 std::fs::write("child.pid", child.id().to_string()).unwrap();
6771}
6772"#,
6773 )
6774 .unwrap();
6775 let output = Command::new("rustc")
6776 .arg(&source)
6777 .arg("-o")
6778 .arg(&exe)
6779 .output()
6780 .unwrap();
6781 assert!(
6782 output.status.success(),
6783 "{}",
6784 String::from_utf8_lossy(&output.stderr)
6785 );
6786 let bin = TestBinary {
6787 name: "runner".into(),
6788 cwd: work.join("src"),
6789 marks: marks_dir(&work).unwrap(),
6790 git_ceiling: work,
6791 work_lock: None,
6792 tests: BTreeSet::new(),
6793 runner: Runner::Exe(exe),
6794 baseline: Duration::ZERO,
6795 untraced_baseline: None,
6796 timeout_diagnostic: std::sync::Once::new(),
6797 traced: Duration::ZERO,
6798 timeout: None,
6799 wrapper_grace: Duration::ZERO,
6800 report_slow: false,
6801 filtered_timings: Default::default(),
6802 trace: Trace::default(),
6803 effects_baseline: std::sync::OnceLock::new(),
6804 };
6805 let started = Instant::now();
6806 let outcome = run_binary(
6807 &bin,
6808 None,
6809 &[],
6810 Duration::from_secs(2),
6811 RunOutput::FirstFailure,
6812 1,
6813 );
6814 let elapsed = started.elapsed();
6815 let pid = fs::read_to_string(bin.cwd.join("child.pid"))
6817 .unwrap()
6818 .parse()
6819 .unwrap();
6820 kill_test_group(pid);
6821 fs::remove_dir_all(dir).unwrap();
6822 assert_eq!(outcome.unwrap(), Outcome::Pass);
6823 assert!(
6824 elapsed < Duration::from_secs(6),
6825 "a detached descendant held the output pipe open"
6826 );
6827 }
6828
6829 fn set_modified(path: &Path, time: std::time::SystemTime) {
6830 fs::File::options()
6831 .write(true)
6832 .open(path)
6833 .unwrap()
6834 .set_modified(time)
6835 .unwrap();
6836 }
6837
6838 fn modified(path: &Path) -> std::time::SystemTime {
6839 fs::metadata(path).unwrap().modified().unwrap()
6840 }
6841
6842 fn copy_run(dir: &Path, selected: &[&str], write: bool) -> WorkCopy {
6845 let (workspace, work) = (dir.join("ws"), dir.join("work"));
6846 let copy = work.join("src");
6847 let state = WorkCopy::open(&work, ©);
6848 copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
6849 prune(©, &state).unwrap();
6850 for name in selected {
6851 let path = copy.join(name);
6852 let original = state.original(&path, &workspace).unwrap().unwrap();
6853 assert_eq!(original, fs::read_to_string(workspace.join(name)).unwrap());
6854 if write {
6855 state
6856 .write(&path, &format!("instrumented {original}"))
6857 .unwrap();
6858 } else {
6859 state.record(&path).unwrap(); }
6861 }
6862 if write {
6863 state.settle(&workspace).unwrap();
6864 }
6865 state
6866 }
6867
6868 #[test]
6870 fn work_copy_table() {
6871 let table = include_str!("../tests/data/workcopy.pict.tsv");
6872 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
6873 let mut rows = 0;
6874 for (index, line) in table.lines().skip(1).enumerate() {
6875 let [earlier, source, selected] = line.split('\t').collect::<Vec<_>>()[..] else {
6876 panic!("bad row: {line}");
6877 };
6878 let dir = scratch(&format!("copy-table-{index}"));
6879 let (file, copied) = (dir.join("ws/src/a.rs"), dir.join("work/src/src/a.rs"));
6880 let log = dir.join("work").join(WRITTEN_LOG);
6881 fs::write(&file, "v1").unwrap();
6882 set_modified(&file, hour_ago);
6883 match earlier {
6884 "none" => {}
6885 "plain" => drop(copy_run(&dir, &[], true)),
6886 "written" => drop(copy_run(&dir, &["src/a.rs"], true)),
6887 "logged_only" => drop(copy_run(&dir, &["src/a.rs"], false)),
6888 _ => panic!("{line}"),
6889 }
6890 if copied.exists() {
6891 set_modified(&copied, hour_ago);
6892 }
6893 let before = fs::read_to_string(&copied).ok();
6894 match source {
6895 "same" => {}
6896 "edited" => fs::write(&file, "version 2").unwrap(),
6897 "deleted" => fs::remove_file(&file).unwrap(),
6898 _ => panic!("{line}"),
6899 }
6900 let selected = selected == "yes";
6901 copy_run(&dir, if selected { &["src/a.rs"] } else { &[] }, true);
6902
6903 let wanted = match (source, selected) {
6904 ("deleted", _) => None,
6905 ("same", true) => Some("instrumented v1".to_string()),
6906 ("same", false) => Some("v1".to_string()),
6907 (_, true) => Some("instrumented version 2".to_string()),
6908 (_, false) => Some("version 2".to_string()),
6909 };
6910 assert_eq!(fs::read_to_string(&copied).ok(), wanted, "{line}");
6911 assert_eq!(
6912 fs::read_to_string(&log).unwrap_or_default(),
6913 if selected { "src/a.rs\n" } else { "" },
6914 "{line}"
6915 );
6916 if before == wanted && wanted.is_some() && earlier != "logged_only" {
6919 assert_eq!(modified(&copied), hour_ago, "{line}");
6920 }
6921 if before != wanted && wanted.is_some() {
6924 assert!(
6925 modified(&copied) > hour_ago + Duration::from_secs(1800),
6926 "{line}"
6927 );
6928 }
6929 copy_run(&dir, &[], true);
6931 assert_eq!(
6932 fs::read_to_string(&copied).ok(),
6933 fs::read_to_string(&file).ok(),
6934 "{line}"
6935 );
6936 assert_eq!(fs::read_to_string(&log).unwrap(), "", "{line}");
6937 fs::remove_dir_all(&dir).unwrap();
6938 rows += 1;
6939 }
6940 assert_eq!(rows, 20);
6941 }
6942
6943 #[test]
6944 fn streaming_copy_comparison_matches_bytes() {
6945 use std::io::{self, Read};
6946
6947 struct Chunks<'a> {
6948 rest: &'a [u8],
6949 chunk: usize,
6950 interrupt: bool,
6951 fail: bool,
6952 }
6953
6954 impl Read for Chunks<'_> {
6955 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
6956 if self.interrupt {
6957 self.interrupt = false;
6958 return Err(io::ErrorKind::Interrupted.into());
6959 }
6960 if self.fail {
6961 self.fail = false;
6962 return Err(io::ErrorKind::PermissionDenied.into());
6963 }
6964 let limit = out.len().min(self.chunk);
6965 self.rest.read(&mut out[..limit])
6966 }
6967 }
6968
6969 for row in include_str!("../tests/data/workcopy-compare.pict.tsv")
6970 .lines()
6971 .skip(1)
6972 {
6973 let fields: Vec<_> = row.split('\t').collect();
6974 let [size, relation, reads] = fields.as_slice() else {
6975 panic!("{row}")
6976 };
6977 let size = match *size {
6978 "empty" => 0,
6979 "before" => 65535,
6980 "boundary" => 65536,
6981 "after" => 65537,
6982 "multi" => 131079,
6983 _ => panic!("{row}"),
6984 };
6985 let left: Vec<_> = (0..size).map(|i| (i % 251) as u8).collect();
6986 let mut right = left.clone();
6987 match *relation {
6988 "equal" => (),
6989 "early" => right[0] ^= 1,
6990 "late" => right[size - 1] ^= 1,
6991 "suffix" => right.push(1),
6992 "shorter" => {
6993 right.pop();
6994 }
6995 _ => panic!("{row}"),
6996 }
6997 let make_reader = |first, rest, fail_first| Chunks {
6998 rest,
6999 chunk: if *reads == "regular" {
7000 usize::MAX
7001 } else if first {
7002 1031
7003 } else {
7004 2063
7005 },
7006 interrupt: *reads == "interrupted",
7007 fail: first == fail_first && *reads == "failed",
7008 };
7009 for (a, b, fail_first) in [
7010 (&left[..], &right[..], true),
7011 (&right[..], &left[..], false),
7012 ] {
7013 let compared = compare_streams(
7014 make_reader(true, a, fail_first),
7015 make_reader(false, b, fail_first),
7016 );
7017 if *reads == "failed" {
7018 assert_eq!(
7019 compared.unwrap_err().kind(),
7020 io::ErrorKind::PermissionDenied,
7021 "{row}"
7022 );
7023 } else {
7024 assert_eq!(compared.unwrap(), a == b, "{row}");
7025 }
7026 }
7027 }
7028 }
7029
7030 #[test]
7031 fn work_copy_keeps_modification_times() {
7032 let dir = scratch("copy-times");
7033 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
7034 let names = ["src/lib.rs", "src/plain.rs", "src/edited.rs"];
7035 for name in names {
7036 fs::write(dir.join("ws").join(name), format!("// {name}")).unwrap();
7037 set_modified(&dir.join("ws").join(name), hour_ago);
7038 }
7039 let copy = dir.join("work/src");
7040 let runtime = copy.join("src/__tmt_rt.rs");
7041 let run = || {
7042 let state = copy_run(&dir, &[], false);
7043 for name in ["src/lib.rs", "src/edited.rs"] {
7044 let original = state.original(©.join(name), &dir.join("ws")).unwrap();
7045 state
7046 .write(©.join(name), &format!("probe {}", original.unwrap()))
7047 .unwrap();
7048 }
7049 assert_eq!(state.original(&runtime, &dir.join("ws")).ok(), {
7051 if runtime.exists() { Some(None) } else { None }
7052 });
7053 state.write(&runtime, "runtime").unwrap();
7054 state.settle(&dir.join("ws")).unwrap();
7055 };
7056 run();
7057 for name in names.iter().map(|n| copy.join(n)).chain([runtime.clone()]) {
7058 set_modified(&name, hour_ago);
7059 }
7060 fs::write(dir.join("ws/src/edited.rs"), "// edited since").unwrap();
7061 run();
7062 for name in ["src/lib.rs", "src/plain.rs", "src/__tmt_rt.rs"] {
7064 assert_eq!(modified(©.join(name)), hour_ago, "{name}");
7065 }
7066 assert_ne!(modified(©.join("src/edited.rs")), hour_ago);
7067 assert_eq!(
7068 fs::read_to_string(copy.join("src/edited.rs")).unwrap(),
7069 "probe // edited since"
7070 );
7071 assert_eq!(
7072 fs::read_to_string(copy.join("src/lib.rs")).unwrap(),
7073 "probe // src/lib.rs"
7074 );
7075 assert_eq!(
7076 fs::read_to_string(dir.join("work").join(WRITTEN_LOG)).unwrap(),
7077 "src/__tmt_rt.rs\nsrc/edited.rs\nsrc/lib.rs\n"
7078 );
7079 let later = hour_ago + Duration::from_secs(60);
7081 set_modified(&dir.join("ws/src/plain.rs"), later);
7082 run();
7083 assert_eq!(modified(©.join("src/plain.rs")), hour_ago);
7084 let plain = fs::read_to_string(dir.join("ws/src/plain.rs")).unwrap();
7087 fs::write(dir.join("ws/src/plain.rs"), plain.to_uppercase()).unwrap();
7088 set_modified(
7089 &dir.join("ws/src/plain.rs"),
7090 hour_ago - Duration::from_secs(60),
7091 );
7092 run();
7093 assert_eq!(
7094 fs::read_to_string(copy.join("src/plain.rs")).unwrap(),
7095 plain.to_uppercase()
7096 );
7097 assert!(modified(©.join("src/plain.rs")) > later);
7098 fs::remove_dir_all(&dir).unwrap();
7099 }
7100
7101 #[test]
7102 fn work_copy_log_is_not_trusted() {
7103 let dir = scratch("copy-log");
7104 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7105 let copy = work.join("src");
7106 let outside = dir.join("outside.txt");
7107 fs::write(&outside, "keep").unwrap();
7108 fs::write(workspace.join("src/a.rs"), "a").unwrap();
7109 fs::write(
7111 work.join(WRITTEN_LOG),
7112 format!(
7113 "../../outside.txt\n{}\n\nsrc/../../../outside.txt\nsrc/a.rs\n",
7114 outside.display()
7115 ),
7116 )
7117 .unwrap();
7118 let state = WorkCopy::open(&work, ©);
7119 assert_eq!(
7120 state.earlier,
7121 [copy.join("src/a.rs")].into_iter().collect::<HashSet<_>>()
7122 );
7123 copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
7124 state.settle(&workspace).unwrap();
7125 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7126 assert_eq!(fs::read_to_string(copy.join("src/a.rs")).unwrap(), "a");
7127
7128 let state = WorkCopy::open(&work, ©);
7130 assert!(state.write(&outside, "x").is_err());
7131 assert!(state.write(©.join("src/a\nb.rs"), "x").is_err());
7132 assert!(!copy.join("src/a\nb.rs").exists());
7133 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7134 fs::remove_dir_all(&dir).unwrap();
7135 }
7136 #[test]
7137 fn work_copy_log_follows_every_write() {
7138 let dir = scratch("copy-log-order");
7139 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7140 let copy = work.join("src");
7141 let log = work.join(WRITTEN_LOG);
7142 let names = ["h", "c", "f", "a", "e", "b", "g", "d"].map(|n| format!("src/{n}.rs"));
7143 for name in &names {
7144 fs::write(workspace.join(name), "x").unwrap();
7145 }
7146 let state = copy_run(&dir, &[], false);
7147 state.record(©.join(&names[0])).unwrap();
7149 state.record(©.join(&names[0])).unwrap();
7150 assert_eq!(fs::read_to_string(&log).unwrap(), "src/h.rs\n");
7151 assert_eq!(fs::read_to_string(copy.join(&names[0])).unwrap(), "x");
7152 for name in &names {
7153 state.write(©.join(name), "probe").unwrap();
7154 }
7155 state.settle(&workspace).unwrap();
7156 let mut sorted = names.to_vec();
7157 sorted.sort();
7158 assert_eq!(
7159 fs::read_to_string(&log).unwrap(),
7160 sorted.iter().map(|n| format!("{n}\n")).collect::<String>()
7161 );
7162
7163 let state = copy_run(&dir, &[], false);
7165 state.settle(&workspace).unwrap();
7166 assert_eq!(fs::read_to_string(&log).unwrap(), "");
7167 state.write(©.join(&names[3]), "probe").unwrap();
7168 assert_eq!(fs::read_to_string(&log).unwrap(), "src/a.rs\n");
7169 fs::remove_dir_all(&dir).unwrap();
7170 }
7171
7172 #[test]
7173 fn sync_copies_what_is_not_up_to_date_and_nothing_else() {
7174 let dir = scratch("copy-sync");
7175 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7176 let copy = work.join("src");
7177 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
7178 for name in [
7179 "same",
7180 "longer",
7181 "newer",
7182 "was_dir",
7183 "was_link",
7184 "short_link",
7185 "twin_link",
7186 "shorter",
7187 ] {
7188 fs::write(workspace.join("src").join(name), "source").unwrap();
7189 set_modified(&workspace.join("src").join(name), hour_ago);
7190 }
7191 let locked = workspace.join("src/locked");
7193 fs::write(&locked, "read only").unwrap();
7194 let mut permissions = fs::metadata(&locked).unwrap().permissions();
7195 permissions.set_readonly(true);
7196 fs::set_permissions(&locked, permissions).unwrap();
7197 fs::create_dir_all(copy.join("src/was_dir/inner")).unwrap();
7198 fs::write(copy.join("src/same"), "SOURCE").unwrap();
7200 fs::write(workspace.join("src/copied"), "as it is").unwrap();
7202 fs::write(copy.join("src/copied"), "as it is").unwrap();
7203 let long_ago = hour_ago - Duration::from_secs(7200);
7204 set_modified(©.join("src/copied"), long_ago);
7205 let elsewhere = dir.join("elsewhere");
7207 fs::create_dir_all(&elsewhere).unwrap();
7208 std::os::unix::fs::symlink(&elsewhere, copy.join("linked")).unwrap();
7209 fs::create_dir_all(workspace.join("linked/deep")).unwrap();
7210 fs::write(workspace.join("linked/deep/z"), "z").unwrap();
7211 fs::write(copy.join("src/longer"), "SOURCE+").unwrap();
7212 fs::write(copy.join("src/newer"), "SOURCE").unwrap();
7213 set_modified(©.join("src/newer"), hour_ago - Duration::from_secs(60));
7214 let outside = dir.join("outside");
7216 fs::write(&outside, "keep").unwrap();
7217 std::os::unix::fs::symlink(&outside, copy.join("src/was_link")).unwrap();
7218 let twin = dir.join("twin");
7220 fs::write(&twin, "source").unwrap();
7221 std::os::unix::fs::symlink(&twin, copy.join("src/twin_link")).unwrap();
7222 fs::write(copy.join("src/shorter"), "sour").unwrap();
7224 std::os::unix::fs::symlink("abcdef", copy.join("src/short_link")).unwrap();
7226 fs::create_dir_all(copy.join("old/deep")).unwrap();
7228 fs::write(copy.join("old/deep/x"), "x").unwrap();
7229 fs::create_dir_all(workspace.join("keep/deep")).unwrap();
7230 fs::write(workspace.join("keep/deep/y"), "y").unwrap();
7231
7232 copy_run(&dir, &[], true);
7233 let read = |name: &str| fs::read_to_string(copy.join(name)).unwrap();
7234 assert_eq!(read("src/locked"), "read only");
7235 assert_eq!(read("src/copied"), "as it is");
7236 assert_eq!(
7237 fs::metadata(copy.join("src/copied"))
7238 .unwrap()
7239 .modified()
7240 .unwrap(),
7241 long_ago
7242 );
7243 assert_eq!(read("linked/deep/z"), "z");
7244 assert!(fs::symlink_metadata(copy.join("linked")).unwrap().is_dir());
7245 assert_eq!(
7246 fs::read_dir(&elsewhere).unwrap().count(),
7247 0,
7248 "nothing written through"
7249 );
7250 for name in [
7251 "src/same",
7252 "src/longer",
7253 "src/newer",
7254 "src/was_dir",
7255 "src/was_link",
7256 "src/short_link",
7257 "src/twin_link",
7258 "src/shorter",
7259 ] {
7260 assert_eq!(read(name), "source", "{name}");
7261 assert!(
7262 fs::symlink_metadata(copy.join(name)).unwrap().is_file(),
7263 "{name}"
7264 );
7265 }
7266 assert!(
7267 fs::symlink_metadata(copy.join("src/was_link"))
7268 .unwrap()
7269 .is_file()
7270 );
7271 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7272 assert!(!copy.join("old").exists());
7273 assert_eq!(read("keep/deep/y"), "y");
7274 fs::remove_dir_all(&dir).unwrap();
7275 }
7276 #[test]
7277 fn a_finding_keeps_its_number_when_the_one_before_it_is_closed() {
7278 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";
7279 let found = instrument::discover(source, 0).unwrap();
7280 let mut all: Vec<(usize, usize, String)> = found
7281 .sites
7282 .iter()
7283 .map(|site| {
7284 let at = report::location("", site);
7285 (at.line, at.column, at.code)
7286 })
7287 .collect();
7288 all.push(
7289 all.iter()
7290 .find(|(line, _, code)| *line == 3 && code == "a > b")
7291 .unwrap()
7292 .clone(),
7293 );
7294 all.reverse();
7295 let places = [FilePlaces {
7296 display: "src/lib.rs",
7297 source,
7298 lines: &scope::LineIndex::new(source),
7299 places: &all,
7300 }];
7301 let gap = |line: usize, column: usize, file: &str| Finding::InputGap {
7302 at: report::Location {
7303 file: file.to_string(),
7304 line,
7305 column,
7306 code: "a > b".to_string(),
7307 ..report::Location::default()
7308 },
7309 survivors: vec![],
7310 survivor_count: 0,
7311 add_tests: vec![],
7312 observed: None,
7313 verified: true,
7314 };
7315 let name = |finding: &Finding| {
7316 let at = finding.at();
7317 (at.item.clone(), at.id.clone())
7318 };
7319 let mut findings = [
7321 gap(4, 20, "src/lib.rs"),
7322 gap(9, 5, "src/lib.rs"),
7323 gap(9, 5, "src/other.rs"),
7324 gap(5, 9, "src/lib.rs"), ];
7326 name_findings(&mut findings, &places);
7327 assert_eq!(
7328 name(&findings[0]),
7329 (
7330 "S::f".to_string(),
7331 "input_gap|src/lib.rs|S::f|a > b|1".to_string()
7332 )
7333 );
7334 assert_eq!(
7335 name(&findings[1]),
7336 (
7337 "g".to_string(),
7338 "input_gap|src/lib.rs|g|a > b|0".to_string()
7339 )
7340 );
7341 assert_eq!(name(&findings[2]), (String::new(), String::new()));
7343 assert_eq!(
7344 name(&findings[3]),
7345 (
7346 "S::f".to_string(),
7347 "input_gap|src/lib.rs|S::f|a > b|2".to_string()
7348 )
7349 );
7350 }
7351
7352 #[test]
7353 fn an_audit_searches_only_the_jobs_for_its_site() {
7354 let jobs: Vec<_> = [1, 1, 3, 8, 8]
7355 .into_iter()
7356 .map(|site| Job {
7357 site,
7358 mutation: Mutation::Negate,
7359 tests: vec![],
7360 })
7361 .collect();
7362 for (site, range) in [
7363 (0, 0..0),
7364 (1, 0..2),
7365 (2, 2..2),
7366 (3, 2..3),
7367 (4, 3..3),
7368 (8, 3..5),
7369 (9, 5..5),
7370 ] {
7371 let found = jobs_for_site(&jobs, site);
7372 assert_eq!(found, range);
7373 assert_eq!(
7374 found
7375 .clone()
7376 .find(|&index| jobs[index].mutation == Mutation::Negate),
7377 jobs.iter()
7378 .position(|job| job.site == site && job.mutation == Mutation::Negate)
7379 );
7380 }
7381 }
7382
7383 #[test]
7384 fn an_audit_takes_its_sample_evenly_and_the_same_every_time() {
7385 assert_eq!(spread(0, 3), Vec::<usize>::new());
7386 assert_eq!(spread(5, 0), Vec::<usize>::new());
7387 assert_eq!(spread(3, 3), [0, 1, 2]);
7388 assert_eq!(spread(3, 10), [0, 1, 2]);
7389 assert_eq!(spread(10, 1), [0]);
7390 assert_eq!(spread(10, 3), [0, 3, 6]);
7391 assert_eq!(spread(10, 5), [0, 2, 4, 6, 8]);
7392 assert_eq!(spread(4, 3), [0, 1, 2]);
7393 assert_eq!(spread(7, 6), [0, 1, 2, 3, 4, 5]);
7394 }
7395
7396 #[test]
7397 fn a_mutant_of_the_source_is_the_mutation_its_probe_runs() {
7398 assert_ne!(crate::tmt_rt::CANNOT_EVALUATE, 0);
7401 let source = "fn f(a: i32, b: i32, ok: bool, k: Option<i32>, base: O) -> O { \
7402 go(); \
7403 let x = match k { Some(n) if n > 1 => !ok && a < b, _ => -a + b > 0 || ok }; \
7404 for _ in a..b {} for _ in a..=b {} \
7405 O { on: x, ..base } }";
7406 let found = instrument::discover(source, 0).unwrap().sites;
7407 let mut seen = BTreeSet::new();
7408 for site in &found {
7409 for mutant in instrument::source_mutants(site) {
7410 let kind = format!("{:?}", site.kind);
7411 let kind = kind.split([' ', '{', '(']).next().unwrap().to_string();
7412 seen.insert((
7413 kind,
7414 mutant.into.clone(),
7415 format!("{:?}", mutation_of(site, &mutant)),
7416 ));
7417 }
7418 }
7419 let expected = [
7420 ("Arith", "*", "ArithSwap2"),
7421 ("Arith", "-", "ArithSwap"),
7422 ("Arm", "Some(n) if n > 1", "Delete"),
7423 ("Body", "Default::default()", "Delete"),
7424 ("Cmp", "<", "Op(Lt)"),
7425 ("Cmp", "<=", "Op(Le)"),
7426 ("Cmp", "==", "Op(Eq)"),
7427 ("Cmp", ">", "Op(Gt)"),
7428 ("Cmp", ">=", "Op(Ge)"),
7429 ("Field", "on", "Delete"),
7430 ("Guard", "true", "Const(true)"),
7431 ("Logic", "&&", "LogicSwap"),
7432 ("Logic", "||", "LogicSwap"),
7433 ("Neg", "", "Delete"),
7434 ("Not", "", "DropNot"),
7435 ("Range", "..", "RangeEnd"),
7436 ("Range", "..=", "RangeEnd"),
7437 ("Stmt", "", "Delete"),
7438 ];
7439 let like = |source: &str, into: &str| -> Vec<Mutation> {
7442 let sites = instrument::discover(source, 0).unwrap().sites;
7443 let site = sites
7444 .iter()
7445 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
7446 .unwrap();
7447 let mutant = instrument::source_mutants(site)
7448 .into_iter()
7449 .find(|mutant| mutant.into == into)
7450 .unwrap();
7451 mutations_like(site, &mutant, true)
7452 };
7453 use plan::CmpOp::*;
7454 for (op, into, expected) in [
7455 ("==", "!=", vec![Mutation::Op(Ne), Mutation::Negate]),
7456 ("!=", "==", vec![Mutation::Op(Eq), Mutation::Negate]),
7457 ("<=", ">", vec![Mutation::Op(Gt), Mutation::Negate]),
7458 (">=", "<", vec![Mutation::Op(Lt), Mutation::Negate]),
7459 ("<", "<=", vec![Mutation::Op(Le), Mutation::Shift(1)]),
7460 (">", ">=", vec![Mutation::Op(Ge), Mutation::Shift(-1)]),
7461 ("<", "==", vec![Mutation::Op(Eq)]),
7462 ("<", ">", vec![Mutation::Op(Gt)]),
7463 (">", "==", vec![Mutation::Op(Eq)]),
7464 (">", "<", vec![Mutation::Op(Lt)]),
7465 ] {
7466 let source = format!("fn f(a: i32, b: i32) -> bool {{ a {op} b }}");
7467 assert_eq!(like(&source, into), expected, "{op} as {into}");
7468 }
7469 let unordered = |op: &str, into: &str| -> Vec<Mutation> {
7472 let source = format!("fn f(a: f64, b: f64) -> bool {{ a {op} b }}");
7473 let sites = instrument::discover(&source, 0).unwrap().sites;
7474 let site = sites
7475 .iter()
7476 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
7477 .unwrap();
7478 let mutant = instrument::source_mutants(site)
7479 .into_iter()
7480 .find(|mutant| mutant.into == into)
7481 .unwrap();
7482 mutations_like(site, &mutant, false)
7483 };
7484 assert_eq!(unordered(">=", "<"), [Mutation::Op(Lt)]);
7485 assert_eq!(unordered("<=", ">"), [Mutation::Op(Gt)]);
7486 assert_eq!(unordered("==", "!="), [Mutation::Op(Ne), Mutation::Negate]);
7487 for d in -3..=3 {
7489 assert_eq!(
7490 plan::eval_mutated_d(Lt, Mutation::Shift(1), d),
7491 Le.eval_d(d)
7492 );
7493 assert_eq!(
7494 plan::eval_mutated_d(Gt, Mutation::Shift(-1), d),
7495 Ge.eval_d(d)
7496 );
7497 }
7498 let seen: Vec<(&str, &str, &str)> = seen
7499 .iter()
7500 .map(|(kind, into, mutation)| (kind.as_str(), into.as_str(), mutation.as_str()))
7501 .collect();
7502 assert_eq!(seen, expected);
7503 }
7504
7505 #[test]
7506 fn the_mark_of_a_run_is_a_new_file_and_says_one_of_three_things() {
7507 let dir = scratch("unable-mark");
7508 fs::create_dir_all(&dir).unwrap();
7509 let runs = std::sync::atomic::AtomicUsize::new(0);
7510 let name = |n: usize| dir.join(format!("tmt-unable-{}-{n}", std::process::id()));
7511 fs::write(name(0), "not ours").unwrap();
7514 fs::write(name(1), "nor this").unwrap();
7515 let mark = reserve_file(&dir, "unable", &runs).unwrap();
7516 assert_eq!(mark, name(2));
7517 assert!(mark.is_absolute());
7518 assert_eq!(fs::read_to_string(&mark).unwrap(), "");
7519 assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
7520 assert_eq!(fs::read_to_string(name(1)).unwrap(), "nor this");
7521 assert!(!release_mark(&mark).unwrap());
7523 assert!(!mark.exists());
7524 let mark = reserve_file(&dir, "unable", &runs).unwrap();
7526 assert_eq!(mark, name(3));
7527 fs::remove_file(&mark).unwrap();
7528 assert!(release_mark(&mark).unwrap());
7529 let in_the_way = dir.join("a-directory");
7532 fs::create_dir_all(&in_the_way).unwrap();
7533 let refused = format!("{:#}", release_mark(&in_the_way).unwrap_err());
7534 assert!(refused.contains("cannot tell whether"), "{refused}");
7535 assert!(refused.contains("a-directory"), "{refused}");
7536 assert!(in_the_way.is_dir());
7537 let unmade = format!("{:#}", reserve_file(&name(0), "unable", &runs).unwrap_err());
7539 assert!(unmade.contains("creating"), "{unmade}");
7540 assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
7541 fs::remove_dir_all(&dir).unwrap();
7542 }
7543
7544 #[test]
7545 fn the_directory_of_the_marks_is_made_or_used_and_nothing_is_removed_for_it() {
7546 let dir = scratch("marks-dir");
7547 let work = dir.join("work");
7548 assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
7550 assert!(work.join("marks").is_dir());
7551 fs::write(work.join("marks/left-over"), "x").unwrap();
7552 assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
7553 assert_eq!(
7554 fs::read_to_string(work.join("marks/left-over")).unwrap(),
7555 "x"
7556 );
7557 let taken = dir.join("taken");
7559 fs::create_dir_all(&taken).unwrap();
7560 fs::write(taken.join("marks"), "grades of the class").unwrap();
7561 let said = format!("{:#}", marks_dir(&taken).unwrap_err());
7562 assert!(
7563 said.contains("is in the way") && said.contains("marks"),
7564 "{said}"
7565 );
7566 assert_eq!(
7567 fs::read_to_string(taken.join("marks")).unwrap(),
7568 "grades of the class"
7569 );
7570 #[cfg(unix)]
7572 {
7573 let linked = dir.join("linked");
7574 let elsewhere = dir.join("elsewhere");
7575 fs::create_dir_all(&linked).unwrap();
7576 fs::create_dir_all(&elsewhere).unwrap();
7577 std::os::unix::fs::symlink(&elsewhere, linked.join("marks")).unwrap();
7578 assert!(marks_dir(&linked).is_err());
7579 assert!(
7580 fs::symlink_metadata(linked.join("marks"))
7581 .unwrap()
7582 .is_symlink()
7583 );
7584 assert_eq!(fs::read_dir(&elsewhere).unwrap().count(), 0);
7585 }
7586 fs::remove_dir_all(&dir).unwrap();
7587 }
7588
7589 #[cfg(unix)]
7590 #[test]
7591 fn a_build_that_failed_is_not_code_the_compiler_refused() {
7592 use std::os::unix::process::ExitStatusExt;
7593 let output = |status: i32, stdout: &str, stderr: &str| std::process::Output {
7594 status: std::process::ExitStatus::from_raw(status),
7595 stdout: stdout.as_bytes().to_vec(),
7596 stderr: stderr.as_bytes().to_vec(),
7597 };
7598 let refusal = r#"{"reason":"compiler-message","message":{"level":"error","message":"mismatched types","rendered":"error: mismatched types","spans":[]}}"#;
7599 let warning = r#"{"reason":"compiler-message","message":{"level":"warning","message":"unused","rendered":"warning: unused","spans":[]}}"#;
7600 assert_eq!(source_build(&output(0, warning, "")), SourceBuild::Built);
7602 assert_eq!(
7603 source_build(&output(101 << 8, refusal, "error: could not compile")),
7604 SourceBuild::Refused
7605 );
7606 let killed = source_build(&output(9, warning, "Compiling x\nlast words"));
7608 assert!(
7609 matches!(&killed, SourceBuild::Failed(why) if why.contains("last words")),
7610 "{killed:?}"
7611 );
7612 let cargo = source_build(&output(
7613 101 << 8,
7614 "",
7615 "error: failed to open lock\nno space left on device",
7616 ));
7617 assert!(
7618 matches!(&cargo, SourceBuild::Failed(why) if why.contains("no space left")),
7619 "{cargo:?}"
7620 );
7621 }
7622
7623 #[test]
7624 fn concurrent_runs_share_the_cores() {
7625 assert_eq!(test_threads(16, 1), 16);
7627 assert_eq!(test_threads(16, 4), 4);
7628 assert_eq!(test_threads(18, 4), 4);
7629 assert_eq!(test_threads(16, 8), 2);
7631 assert_eq!(test_threads(16, 9), 2);
7632 assert_eq!(test_threads(4, 16), 2);
7633 assert_eq!(test_threads(1, 1), 2);
7634 assert_eq!(test_threads(8, 0), 8);
7635 }
7636
7637 #[test]
7638 fn cargo_is_told_the_same_everywhere() {
7639 assert!(CargoConfig::default().flags().is_empty());
7640 let some = CargoConfig {
7641 features: vec!["a".to_string(), "dep/b".to_string()],
7642 no_default_features: true,
7643 ..CargoConfig::default()
7644 };
7645 assert_eq!(
7646 some.flags(),
7647 ["--features", "a,dep/b", "--no-default-features"]
7648 );
7649 let all = CargoConfig {
7650 all_features: true,
7651 locked: true,
7652 ..CargoConfig::default()
7653 };
7654 assert_eq!(all.flags(), ["--all-features", "--locked"]);
7655 }
7656
7657 #[test]
7658 fn source_mutants_are_described_like_the_others() {
7659 let source = "fn f(a: i32, b: i32, k: Option<i32>) -> bool { \
7660 match k { Some(n) if n > 1 => !(a < b) || a + b == 0, _ => -a * b > 1 } }";
7661 let found = instrument::discover(source, 0).unwrap().sites;
7662 let described: Vec<String> = found
7663 .iter()
7664 .flat_map(|site| {
7665 instrument::source_mutants(site)
7666 .into_iter()
7667 .map(|mutant| report::describe(site, mutation_of(site, &mutant)))
7668 })
7669 .collect();
7670 assert_eq!(
7671 described,
7672 [
7673 "the body of `f` replaced by `true`",
7674 "the body of `f` replaced by `false`",
7675 "remove the arm `Some(n) if n > 1 => ..`",
7677 "the guard `n > 1` replaced by `true`",
7678 "`n == 1`",
7679 "`n < 1`",
7680 "`n >= 1`",
7681 "`!(a < b) && a + b == 0`",
7682 "`(a < b)`",
7683 "`a == b`",
7684 "`a > b`",
7685 "`a <= b`",
7686 "`a + b != 0`",
7687 "`a - b`",
7688 "`a * b`",
7689 "`-a * b == 1`",
7690 "`-a * b < 1`",
7691 "`-a * b >= 1`",
7692 "`-a / b`",
7693 "`-a + b`",
7694 "`a`",
7695 ]
7696 );
7697 let source = "fn f(k: K) -> u8 { match k { K::A(n) if n > 1 => 1, K::A(_) => 2 } }";
7699 let found = instrument::discover(source, 0).unwrap().sites;
7700 let guard = found
7701 .iter()
7702 .find(|s| matches!(s.kind, SiteKind::Guard { .. }))
7703 .unwrap();
7704 let described: Vec<String> = instrument::source_mutants(guard)
7705 .iter()
7706 .map(|mutant| report::describe(guard, mutation_of(guard, mutant)))
7707 .collect();
7708 assert_eq!(
7709 described,
7710 [
7711 "the guard `n > 1` replaced by `true`",
7712 "the guard `n > 1` replaced by `false`"
7713 ]
7714 );
7715 }
7716}