1use std::cell::RefCell;
8use std::collections::{BTreeMap, BTreeSet, HashSet};
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::process::{Command, Stdio};
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use anyhow::{Context, Result, anyhow, bail};
16use serde::{Deserialize, Serialize};
17
18use crate::checkpoint::{Checkpoint, Phase};
19use crate::instrument::{self, LiteralSide, RUNTIME_MOD, Rendered, Site, SiteKind};
20use crate::output_fixture::{self, Fixture};
21use crate::plan::{self, Mutation, Obs};
22use crate::propagation::{self, Change};
23use crate::report::{self, Finding, Report};
24use crate::scope::{self, Scope};
25use crate::trace::Trace;
26use crate::work_lock::WorkLock;
27use crate::{git_index, leftovers, progress, 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 watch = leftovers::Watch::new(reserve_file(&bin.marks, "held", &RUNS)?);
1796 let mut child = match watch.spawn(&mut cmd) {
1797 Ok(child) => child,
1798 Err(error) => {
1799 watch.finish(true);
1800 let _ = release_mark(&unable_mark);
1801 return Err(error).with_context(|| format!("starting the tests of `{}`", bin.name));
1802 }
1803 };
1804 let group = child.id();
1805 let kill = |child: &mut std::process::Child| {
1806 if nextest {
1807 stop_nextest(child, Duration::from_secs(12));
1810 return;
1811 }
1812 kill_test_group(group);
1813 let _ = child.kill();
1814 let _ = child.wait();
1815 };
1816 let started = Instant::now();
1817 let mut delay = TEST_POLL_INITIAL;
1818 let mut waiting_reported = false;
1819 let running_mutant = env.iter().any(|(key, _)| *key == "TMT_MUTANT")
1820 || matches!(output, RunOutput::FirstFailure);
1821 let result: Result<Outcome> = (|| loop {
1822 if let Some(status) = child.try_wait()? {
1823 if matches!(bin.runner, Runner::Isolated { .. }) || output_to_watch.is_some() {
1824 kill_test_group(group);
1825 }
1826 if nextest {
1827 return nextest_outcome(status.code());
1828 }
1829 return Ok(if status.success() {
1830 Outcome::Pass
1831 } else {
1832 Outcome::Fail
1833 });
1834 }
1835 if output_to_watch
1836 .as_mut()
1837 .map(FailureOutput::failed)
1838 .transpose()?
1839 .unwrap_or(false)
1840 {
1841 kill(&mut child);
1842 return Ok(Outcome::Fail);
1843 }
1844 let elapsed = started.elapsed();
1845 if bin.report_slow
1846 && running_mutant
1847 && !waiting_reported
1848 && elapsed >= Duration::from_secs(5).min(timeout / 2)
1849 {
1850 let selected = tests
1851 .filter(|names| !names.is_empty())
1852 .map(|names| names.join(", "))
1853 .unwrap_or_else(|| bin.name.clone());
1854 eprintln!(
1855 "tmt: waiting for mutant tests `{selected}` (limit {:.2}s)",
1856 timeout.as_secs_f64()
1857 );
1858 waiting_reported = true;
1859 }
1860 if elapsed >= timeout {
1862 if cfg!(unix)
1863 && !bin.wrapper_grace.is_zero()
1864 && matches!(
1865 &bin.runner,
1866 Runner::Isolated {
1867 wrapper: Some(_),
1868 ..
1869 }
1870 )
1871 {
1872 signal_test_group(group, 15);
1873 let began = Instant::now();
1874 while began.elapsed() < bin.wrapper_grace && child.try_wait().ok() == Some(None) {
1875 std::thread::sleep(
1876 Duration::from_millis(10)
1877 .min(bin.wrapper_grace.saturating_sub(began.elapsed())),
1878 );
1879 }
1880 }
1881 kill(&mut child);
1882 return Ok(Outcome::Timeout);
1883 }
1884 std::thread::sleep(next_test_poll(&mut delay, timeout - elapsed));
1886 })();
1887 drop(output_to_watch);
1889 leftovers::count(&watch.finish(leftovers::leave()));
1891 if result.is_err() {
1892 kill(&mut child);
1893 let _ = release_mark(&unable_mark);
1894 }
1895 let outcome = result?;
1896
1897 if release_mark(&unable_mark)? {
1901 return Ok(Outcome::Unable);
1902 }
1903 Ok(outcome)
1904}
1905
1906struct FailureOutput {
1907 file: fs::File,
1908 line: Vec<u8>,
1909 discarded: bool,
1910}
1911
1912impl FailureOutput {
1913 fn new(file: fs::File) -> Self {
1914 Self {
1915 file,
1916 line: Vec::new(),
1917 discarded: false,
1918 }
1919 }
1920
1921 fn failed(&mut self) -> std::io::Result<bool> {
1922 use std::io::Read as _;
1923 const MAX_LINE: usize = 8 * 1024;
1924 let mut chunk = [0; MAX_LINE];
1925 let read = self.file.read(&mut chunk)?;
1926 for part in chunk[..read].split_inclusive(|byte| *byte == b'\n') {
1927 self.discarded |= self.line.len() + part.len() > MAX_LINE;
1928 if !self.discarded {
1929 self.line.extend_from_slice(part);
1930 }
1931 if part.ends_with(b"\n") {
1932 if !self.discarded
1933 && is_failure_line(String::from_utf8_lossy(&self.line).trim_end())
1934 {
1935 return Ok(true);
1936 }
1937 self.discarded = false;
1938 self.line.clear();
1939 }
1940 }
1941 Ok(false)
1942 }
1943}
1944
1945fn stop_nextest(child: &mut std::process::Child, grace: Duration) {
1946 let wait = |child: &mut std::process::Child, limit: Duration| {
1947 let started = Instant::now();
1948 loop {
1949 match child.try_wait() {
1950 Ok(Some(_)) => return true,
1952 Ok(None) if started.elapsed() < limit => {
1954 std::thread::sleep(Duration::from_millis(10));
1956 }
1957 _ => return false,
1958 }
1959 }
1960 };
1961 if wait(child, Duration::ZERO) {
1962 return;
1963 }
1964 let group = child.id();
1965 #[cfg(unix)]
1968 let mut owned = owned_test_processes(group);
1969 signal_test_group(group, 15);
1970 let mut reaped = wait(child, grace);
1971 if !reaped {
1972 signal_test_group(group, 15);
1974 reaped = wait(child, grace.min(Duration::from_secs(1)));
1975 }
1976 #[cfg(unix)]
1977 {
1978 if !reaped {
1980 owned.extend(owned_test_processes(group));
1982 }
1983 for surviving in surviving_groups(&owned, &test_processes()) {
1984 kill_test_group(surviving);
1985 }
1986 }
1987 if !reaped {
1988 kill_test_group(group);
1990 let _ = child.kill();
1991 let _ = child.wait();
1992 }
1993}
1994
1995#[cfg(unix)]
1996#[derive(Debug, PartialEq)]
1997struct TestProcess {
1998 pid: u32,
1999 parent: u32,
2000 group: u32,
2001 started: String,
2002}
2003
2004#[cfg(unix)]
2005fn test_processes() -> Vec<TestProcess> {
2006 let Ok(processes) = Command::new("ps")
2007 .args([
2008 "-e", "-o", "pid=", "-o", "ppid=", "-o", "pgid=", "-o", "lstart=",
2009 ])
2010 .output()
2011 else {
2012 return vec![];
2013 };
2014 String::from_utf8_lossy(&processes.stdout)
2015 .lines()
2016 .filter_map(|line| {
2017 let mut fields = line.split_whitespace();
2018 Some(TestProcess {
2019 pid: fields.next()?.parse().ok()?,
2020 parent: fields.next()?.parse().ok()?,
2021 group: fields.next()?.parse().ok()?,
2022 started: fields.collect::<Vec<_>>().join(" "),
2023 })
2024 })
2025 .collect()
2026}
2027
2028#[cfg(unix)]
2032fn surviving_groups(owned: &[TestProcess], current: &[TestProcess]) -> BTreeSet<u32> {
2033 current
2034 .iter()
2035 .filter(|process| {
2036 owned.iter().any(|before| {
2037 process.pid == before.pid
2038 && process.group == before.group
2039 && process.started == before.started
2040 })
2041 })
2042 .map(|process| process.group)
2043 .collect()
2044}
2045
2046#[cfg(unix)]
2047fn owned_test_processes(root: u32) -> Vec<TestProcess> {
2048 owned_among(test_processes(), root)
2049}
2050
2051#[cfg(unix)]
2054fn owned_among(data: Vec<TestProcess>, root: u32) -> Vec<TestProcess> {
2055 let mut owned = HashSet::from([root]);
2056 loop {
2057 let before = owned.len();
2058 for process in &data {
2059 if owned.contains(&process.parent) {
2060 owned.insert(process.pid);
2061 }
2062 }
2063 if owned.len() == before {
2064 break;
2065 }
2066 }
2067 let groups: HashSet<_> = data
2070 .iter()
2071 .filter(|process| process.pid == process.group && owned.contains(&process.pid))
2072 .map(|process| process.group)
2073 .collect();
2074 data.into_iter()
2075 .filter(|process| owned.contains(&process.pid) && groups.contains(&process.group))
2076 .collect()
2077}
2078
2079fn kill_test_group(id: u32) {
2080 signal_test_group(id, 9);
2081}
2082
2083fn signal_test_group(id: u32, signal: i32) {
2084 #[cfg(any(target_os = "linux", target_os = "macos"))]
2085 {
2086 unsafe extern "C" {
2087 fn killpg(group: std::ffi::c_int, signal: std::ffi::c_int) -> std::ffi::c_int;
2088 }
2089 if let Ok(group) = std::ffi::c_int::try_from(id) {
2090 unsafe { killpg(group, signal) };
2092 }
2093 }
2094 #[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))]
2095 let _ = Command::new("kill")
2096 .args([format!("-{signal}"), "--".to_owned(), format!("-{id}")])
2097 .stdout(Stdio::null())
2098 .stderr(Stdio::null())
2099 .status();
2100 #[cfg(not(unix))]
2101 let _ = (id, signal);
2102}
2103
2104fn run_baseline(
2106 bin: &TestBinary,
2107 env: &[(&str, &str)],
2108 timeout: Duration,
2109 path: &Path,
2110 timing_only: bool,
2111) -> Result<bool> {
2112 use std::io::{Read, Seek, SeekFrom};
2113
2114 let mut suffix = 0;
2115 let (path, mut log) = loop {
2116 let candidate = if suffix == 0 {
2117 path.to_path_buf()
2118 } else {
2119 path.with_extension(format!("{suffix}.log"))
2120 };
2121 match fs::OpenOptions::new()
2122 .create_new(true)
2123 .read(true)
2124 .write(true)
2125 .open(&candidate)
2126 {
2127 Ok(log) => break (candidate, log),
2128 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => suffix += 1,
2129 Err(err) => {
2130 return Err(err)
2131 .with_context(|| format!("creating baseline log {}", candidate.display()));
2132 }
2133 }
2134 };
2135 let result =
2136 run_binary(bin, None, env, timeout, RunOutput::Capture(&log), 1).with_context(|| {
2137 format!(
2138 "running baseline for `{}`; output: {}",
2139 bin.name,
2140 path.display()
2141 )
2142 })?;
2143 if result == Outcome::Pass || (timing_only && result == Outcome::Timeout) {
2144 drop(log);
2145 fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
2146 return Ok(result == Outcome::Pass);
2147 }
2148 let reason = match result {
2149 Outcome::Pass => unreachable!("pass handled above"),
2150 Outcome::Fail => "do not pass on the unmutated code",
2151 Outcome::Timeout => "timed out on the unmutated code",
2152 Outcome::Unable => "could not be evaluated on the unmutated code",
2153 };
2154 const LIMIT: u64 = 16 * 1024;
2155 log.seek(SeekFrom::Start(log.metadata()?.len().saturating_sub(LIMIT)))?;
2156 let mut tail = Vec::new();
2157 log.take(LIMIT).read_to_end(&mut tail)?;
2158 bail!(
2159 "the tests in `{}` {reason}; full output: {}\n{}",
2160 bin.name,
2161 path.display(),
2162 String::from_utf8_lossy(&tail).trim_end()
2163 );
2164}
2165
2166fn marks_dir(work: &Path) -> Result<PathBuf> {
2170 work_directory(work, "marks")
2171}
2172
2173fn work_directory(work: &Path, name: &str) -> Result<PathBuf> {
2174 let path = work.join(name);
2175 match fs::symlink_metadata(&path) {
2176 Ok(found) if found.is_dir() => {}
2177 Ok(_) => bail!(
2178 "{} is in the way: the working directory needs a directory of that name, and \
2179 this is not one. Move it, or choose another --work-dir",
2180 path.display()
2181 ),
2182 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
2183 fs::create_dir(&path).with_context(|| format!("creating {}", path.display()))?
2184 }
2185 Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
2186 }
2187 Ok(path)
2188}
2189
2190fn reserve_file(dir: &Path, label: &str, runs: &std::sync::atomic::AtomicUsize) -> Result<PathBuf> {
2199 let dir = std::path::absolute(dir).unwrap_or(dir.to_path_buf());
2202 loop {
2203 let mark = dir.join(format!(
2204 "tmt-{label}-{}-{}",
2205 std::process::id(),
2206 runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
2207 ));
2208 match fs::OpenOptions::new()
2209 .write(true)
2210 .create_new(true)
2211 .open(&mark)
2212 {
2213 Ok(_) => return Ok(mark),
2214 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
2215 Err(err) => {
2217 return Err(err).with_context(|| format!("creating {}", mark.display()));
2218 }
2219 }
2220 }
2221}
2222
2223fn run_source_tests(binaries: &[&TestBinary]) -> Result<Outcome> {
2224 for bin in binaries {
2225 bin.warn_timeout_conflict(None);
2226 let outcome = run_binary(
2227 bin,
2228 None,
2229 &[],
2230 bin.mutant_limit(bin.baseline),
2231 RunOutput::FirstFailure,
2232 1,
2233 )?;
2234 if outcome != Outcome::Pass {
2235 return Ok(outcome);
2236 }
2237 }
2238 Ok(Outcome::Pass)
2239}
2240
2241fn observe_witness(
2242 baseline: &TestBinary,
2243 exe: PathBuf,
2244 wrapper: Option<&Path>,
2245 scenario: &witness::Scenario,
2246 name: &str,
2247 compares: bool,
2248) -> Result<Option<witness::Observation>> {
2249 use std::io::Read as _;
2250 let test_name = scenario.test_name(name);
2251 let test = TestBinary {
2252 name: test_name.clone(),
2253 cwd: baseline.cwd.clone(),
2254 marks: baseline.marks.clone(),
2255 git_ceiling: baseline.git_ceiling.clone(),
2256 work_lock: baseline.work_lock.clone(),
2257 tests: BTreeSet::new(),
2258 runner: Runner::Isolated {
2259 exe,
2260 test: test_name,
2261 ignored: false,
2262 wrapper: wrapper.map(Path::to_path_buf),
2263 },
2264 baseline: baseline.baseline,
2265 untraced_baseline: None,
2266 timeout_diagnostic: std::sync::Once::new(),
2267 traced: Duration::ZERO,
2268 timeout: baseline.timeout,
2269 wrapper_grace: baseline.wrapper_grace,
2270 report_slow: false,
2271 filtered_timings: Default::default(),
2272 trace: Trace::default(),
2273 effects_baseline: std::sync::OnceLock::new(),
2274 };
2275 static RUNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2276 let path = reserve_file(&test.marks, "witness", &RUNS)?;
2277 let result = (|| {
2278 let Some(output) = path.to_str() else {
2279 return Ok(None);
2280 };
2281 if run_binary(
2282 &test,
2283 None,
2284 &[(witness::OUTPUT_ENV, output)],
2285 test.mutant_limit(test.baseline),
2286 RunOutput::Quiet,
2287 1,
2288 )? != Outcome::Pass
2289 {
2290 return Ok(None);
2291 }
2292 let mut text = String::new();
2293 const MAX_OBSERVATION: u64 = 2048;
2294 fs::File::open(&path)?
2295 .take(MAX_OBSERVATION + 1)
2296 .read_to_string(&mut text)?;
2297 Ok((text.len() <= MAX_OBSERVATION as usize)
2298 .then(|| scenario.observation(&text, compares))
2299 .flatten())
2300 })();
2301 release_mark(&path)?;
2302 result
2303}
2304
2305fn candidate_edit(
2306 file: &SourceFile,
2307 start: usize,
2308 end: usize,
2309 replacement: String,
2310) -> report::CandidateEdit {
2311 let (line, column) = file.lines.position(&file.original, start);
2312 report::CandidateEdit {
2313 file: file.display.clone(),
2314 line,
2315 column,
2316 start,
2317 end,
2318 before: file.original[start..end].to_string(),
2319 replacement,
2320 }
2321}
2322
2323fn witness_location(source: &SourceFile, candidate: &witness::Candidate) -> report::Location {
2324 let span = &candidate.edits[0].span;
2325 let (line, column) = source.lines.position(&source.original, span.start);
2326 report::Location {
2327 file: source.display.clone(),
2328 line,
2329 column,
2330 code: report::one_line(&source.original[span.clone()]),
2331 ..Default::default()
2332 }
2333}
2334
2335#[derive(Serialize, Deserialize)]
2336#[serde(rename_all = "snake_case")]
2337enum WitnessTrial {
2338 Inapplicable,
2339 Unviable,
2340 Evaluated(Outcome),
2341}
2342
2343struct WitnessSurvivor<'a> {
2344 candidate: &'a witness::Candidate,
2345 at: report::Location,
2346 existing: Option<usize>,
2347 scenarios: Vec<(&'a witness::Scenario, &'a TestBinary)>,
2348}
2349
2350struct SharedWitness {
2351 value: String,
2352 name: String,
2353 tests: std::rc::Rc<[witness::Edit]>,
2354}
2355
2356fn shared_witnesses(
2357 source: &str,
2358 survivors: &[WitnessSurvivor<'_>],
2359 wrapper: Option<&Path>,
2360 compile: impl Fn(&[witness::Edit]) -> Result<Option<PathBuf>>,
2361 note: impl Fn(&str),
2362) -> Result<Vec<Option<SharedWitness>>> {
2363 let mut originals: Vec<_> = (0..survivors.len()).map(|_| None).collect();
2364 if wrapper.is_some() {
2366 return Ok(originals);
2367 }
2368 let inputs: Vec<_> = survivors
2371 .iter()
2372 .enumerate()
2373 .filter_map(|(index, survivor)| {
2374 let (scenario, runner) = *survivor.scenarios.first()?;
2375 Some((
2376 index,
2377 scenario,
2378 runner,
2379 format!("{}_{index}", witness::TEST_NAME),
2380 ))
2381 })
2382 .collect();
2383 for batch in inputs.chunks(32).filter(|batch| batch.len() > 1) {
2384 note(&format!(
2385 "sharing a build for {} original witness inputs",
2386 batch.len()
2387 ));
2388 let tests: Vec<_> = batch
2389 .iter()
2390 .map(|(_, scenario, _, name)| scenario.test_edit(source, name, None))
2391 .collect();
2392 let Some(exe) = compile(&tests)? else {
2393 note("shared witness build failed, trying inputs individually");
2394 continue;
2395 };
2396 let observed: Vec<_> = batch
2397 .iter()
2398 .filter_map(|(index, scenario, runner, name)| {
2399 let value = observe_witness(runner, exe.clone(), wrapper, scenario, name, false)
2400 .ok()??
2401 .value;
2402 witness::is_expected_literal(&value)
2403 .then_some((*index, *scenario, *runner, name, value))
2404 })
2405 .collect();
2406 if observed.is_empty() {
2407 continue;
2408 }
2409 let tests: std::rc::Rc<[_]> = observed
2410 .iter()
2411 .map(|(_, scenario, _, name, value)| scenario.test_edit(source, name, Some(value)))
2412 .collect();
2413 let Some(exe) = compile(&tests)? else {
2414 note("shared witness build failed, trying inputs individually");
2415 continue;
2416 };
2417 for (index, scenario, runner, name, value) in observed {
2418 let checked = observe_witness(runner, exe.clone(), wrapper, scenario, name, true);
2419 if checked.is_ok_and(|value_read| {
2420 value_read
2421 .is_some_and(|read| read.equals_expected == Some(true) && read.value == value)
2422 }) {
2423 originals[index] = Some(SharedWitness {
2424 value,
2425 name: name.clone(),
2426 tests: tests.clone(),
2427 });
2428 }
2429 }
2430 }
2431 Ok(originals)
2432}
2433
2434fn release_mark(mark: &Path) -> Result<bool> {
2438 match fs::remove_file(mark) {
2439 Ok(()) => Ok(false),
2440 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(true),
2441 Err(err) => Err(err).with_context(|| {
2442 format!(
2443 "removing {}: cannot tell whether the tests ran the mutant to the end",
2444 mark.display()
2445 )
2446 }),
2447 }
2448}
2449
2450fn is_failure_line(line: &str) -> bool {
2452 line.starts_with("test ") && line.ends_with(" ... FAILED")
2453}
2454
2455fn requested_scope(
2458 options: &Options,
2459 workspace: &Path,
2460 package_dir: &Path,
2461 copy: &Path,
2462) -> Result<Option<Scope>> {
2463 if options.since.is_none() && options.lines.is_empty() {
2464 return Ok(None);
2465 }
2466 let prefix = package_dir.strip_prefix(copy).unwrap_or(Path::new(""));
2468 let lines: Vec<String> = options
2469 .lines
2470 .iter()
2471 .map(|spec| normalize(&prefix.join(spec)).to_string_lossy().into_owned())
2472 .collect();
2473 let mut scope = Scope::parse_lines(&lines)?;
2474 if let Some(revision) = &options.since {
2475 let git = |args: &[&str]| -> Result<String> {
2476 let output = Command::new("git")
2477 .arg("-C")
2478 .arg(workspace)
2479 .args(args)
2480 .output()
2481 .context("running git")?;
2482 if !output.status.success() {
2483 bail!(
2484 "git {} failed: {}",
2485 args.join(" "),
2486 String::from_utf8_lossy(&output.stderr).trim()
2487 );
2488 }
2489 Ok(String::from_utf8_lossy(&output.stdout).into_owned())
2490 };
2491 scope.merge(Scope::from_diff(&git(&[
2493 "diff",
2494 "-U0",
2495 "--no-color",
2496 "--no-ext-diff",
2497 "--relative",
2498 "--src-prefix=a/",
2499 "--dst-prefix=b/",
2500 revision,
2501 "--",
2502 ])?));
2503 for file in git(&["ls-files", "--others", "--exclude-standard"])?.lines() {
2504 scope.add_whole_file(file);
2505 }
2506 }
2507 Ok(Some(scope))
2508}
2509
2510fn blame_error(
2514 error: &CompileError,
2515 files: &[SourceFile],
2516 copy: &Path,
2517 disabled: &HashSet<u32>,
2518) -> Vec<u32> {
2519 let enabled = |id: u32| !disabled.contains(&id);
2520 let file_of = |span: &ErrorSpan| {
2521 let path = copy.join(&span.file);
2522 files.iter().find(|f| f.path == path)
2523 };
2524 let innermost = |spans: &[ErrorSpan]| -> Vec<u32> {
2525 let mut ids = vec![];
2526 for span in spans {
2527 if let Some(file) = file_of(span) {
2528 let rendered = file.rendered.as_ref().expect("rendered before building");
2529 match rendered
2531 .inserted_by(span.byte_start)
2532 .filter(|id| enabled(*id))
2533 {
2534 Some(id) => ids.push(id),
2535 None => ids.extend(instrument::blame(
2536 &file.sites,
2537 &enabled,
2538 rendered.to_original(span.byte_start),
2539 )),
2540 }
2541 }
2542 }
2543 ids
2544 };
2545 let widen = |lines: usize| -> Vec<u32> {
2546 let mut ids = vec![];
2547 for span in &error.primary {
2548 if let Some(file) = file_of(span) {
2549 ids.extend(
2550 file.sites
2551 .iter()
2552 .filter(|s| enabled(s.id) && s.line.abs_diff(span.line) <= lines)
2553 .map(|s| s.id),
2554 );
2555 }
2556 }
2557 ids
2558 };
2559 [&error.primary, &error.secondary]
2560 .into_iter()
2561 .map(|spans| innermost(spans))
2562 .chain([0, NEARBY_LINES, usize::MAX].into_iter().map(widen))
2563 .find(|ids| !ids.is_empty())
2564 .unwrap_or_default()
2565}
2566
2567fn domain_of(
2569 literal: LiteralSide,
2570 bounds: Option<&crate::trace::TypeBounds>,
2571) -> Option<(i128, i128)> {
2572 let bounds = bounds?;
2573 match literal {
2574 LiteralSide::Rhs(k) => Some((bounds.lhs.0.checked_sub(k)?, bounds.lhs.1.checked_sub(k)?)),
2575 LiteralSide::Lhs(k) => Some((k.checked_sub(bounds.rhs.1)?, k.checked_sub(bounds.rhs.0)?)),
2576 LiteralSide::None => None,
2577 }
2578}
2579
2580struct Session {
2581 progress: bool,
2582 serial_timeout_rechecks: bool,
2583 package_dir: PathBuf,
2584 binaries: Vec<TestBinary>,
2585}
2586
2587struct Job {
2589 site: u32,
2590 mutation: Mutation,
2591 tests: Vec<(usize, Option<Vec<String>>)>,
2593}
2594
2595fn jobs_for_site(jobs: &[Job], site: u32) -> std::ops::Range<usize> {
2597 let first = jobs.partition_point(|job| job.site < site);
2598 let count = jobs[first..].partition_point(|job| job.site == site);
2599 first..first + count
2600}
2601
2602#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2603struct JobResult {
2604 first_pass_timeout: bool,
2605 unconfirmed_timeout: bool,
2606 survived: Option<Vec<String>>,
2608 timed_out: bool,
2609 unable: bool,
2611}
2612
2613#[derive(Debug, PartialEq)]
2615enum Prediction {
2616 Confirmed,
2618 Refuted,
2620 Unknown,
2623}
2624
2625impl Prediction {
2626 fn of<'a>(runs: impl Iterator<Item = &'a JobResult>) -> Prediction {
2627 let mut verdict = Prediction::Confirmed;
2628 for run in runs {
2629 if run.unable || run.unconfirmed_timeout {
2630 verdict = Prediction::Unknown;
2631 } else if run.survived.is_none() {
2632 return Prediction::Refuted;
2633 }
2634 }
2635 verdict
2636 }
2637}
2638
2639impl report::TimeoutRechecks {
2640 fn include(&mut self, result: &JobResult) {
2641 if result.first_pass_timeout {
2642 self.first_pass += 1;
2643 if result.unconfirmed_timeout || result.unable {
2644 self.unconfirmed += 1;
2645 } else if result.timed_out {
2646 self.confirmed += 1;
2647 } else {
2648 self.recovered += 1;
2649 }
2650 }
2651 }
2652}
2653
2654impl JobResult {
2655 fn progress_outcome(&self) -> progress::Outcome {
2656 if self.unable {
2657 progress::Outcome::Unable
2658 } else if self.timed_out {
2659 progress::Outcome::TimedOut
2660 } else if self.survived.is_some() {
2661 progress::Outcome::Survived
2662 } else {
2663 progress::Outcome::Failed
2664 }
2665 }
2666}
2667
2668fn tests_where<T>(
2670 per_test: Option<&BTreeMap<String, T>>,
2671 pick: impl Fn(&T) -> bool,
2672) -> BTreeSet<String> {
2673 per_test
2674 .into_iter()
2675 .flatten()
2676 .filter(|(_, obs)| pick(obs))
2677 .map(|(test, _)| test.clone())
2678 .collect()
2679}
2680
2681type InfectedTests<'a> = Box<dyn Fn(&TestBinary, Mutation) -> BTreeSet<String> + 'a>;
2682type ReachingTests<'a> = Box<dyn Fn(&TestBinary) -> BTreeSet<String> + 'a>;
2683
2684struct PlannedGap {
2686 finding: Finding,
2687 survivors: Vec<Mutation>,
2689 constant_expr: Option<(usize, usize)>,
2693}
2694
2695fn core_range(start: usize, text: &str) -> (usize, usize) {
2697 let (mut from, mut to) = (0, text.len());
2698 loop {
2699 let inner = &text[from..to];
2700 let trimmed = inner.trim();
2701 from += inner.len() - inner.trim_start().len();
2702 to = from + trimmed.len();
2703 let wrapped = trimmed.starts_with('(') && trimmed.ends_with(')') && {
2704 let mut depth = 0usize;
2706 trimmed.char_indices().all(|(i, c)| {
2707 match c {
2708 '(' => depth += 1,
2709 ')' => depth -= 1,
2710 _ => {}
2711 }
2712 depth > 0 || i == trimmed.len() - 1
2713 })
2714 };
2715 if !wrapped {
2716 return (start + from, start + to);
2717 }
2718 from += 1;
2719 to -= 1;
2720 }
2721}
2722
2723struct SitePlan<'a> {
2725 gaps: Vec<PlannedGap>,
2727 cannot_differ: bool,
2730 constant: bool,
2732 run: Vec<Mutation>,
2734 infected: InfectedTests<'a>,
2736 reaching: ReachingTests<'a>,
2738}
2739
2740enum Planned<'a> {
2741 Unreached,
2742 NotEvaluated,
2744 Nothing,
2746 Plan(SitePlan<'a>),
2747}
2748
2749type ConfirmedGap = (Finding, Vec<usize>, Option<(usize, usize)>);
2751
2752struct SiteWork<'a> {
2754 file: &'a str,
2755 site: &'a Site,
2756 gaps: Vec<ConfirmedGap>,
2757 constant: bool,
2758 cannot_differ: bool,
2759 runs: Vec<(Mutation, usize)>,
2760}
2761
2762impl Session {
2763 fn note(&self, text: &str) {
2764 if self.progress {
2765 eprintln!("tmt: {text}");
2766 }
2767 }
2768
2769 fn merged<T: Default + Copy>(
2770 &self,
2771 select: impl Fn(&Trace) -> Option<&BTreeMap<String, T>>,
2772 merge: impl Fn(&mut T, &T),
2773 ) -> T {
2774 let mut all = T::default();
2775 for obs in self
2776 .binaries
2777 .iter()
2778 .filter_map(|b| select(&b.trace))
2779 .flat_map(|t| t.values())
2780 {
2781 merge(&mut all, obs);
2782 }
2783 all
2784 }
2785
2786 fn plan<'a>(&'a self, file: &str, site: &'a Site, verify: bool) -> Planned<'a> {
2787 let id = site.id;
2788 let reach_plan = |mutation: Mutation| SitePlan {
2789 gaps: vec![],
2790 constant: false,
2791 cannot_differ: false,
2792 run: vec![mutation],
2793 infected: Box::new(move |bin, _| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
2794 reaching: Box::new(move |bin| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
2795 };
2796 let reached = || {
2797 self.binaries
2798 .iter()
2799 .any(|b| b.trace.reach.contains_key(&id))
2800 };
2801 Planned::Plan(match &site.kind {
2802 SiteKind::Stmt
2803 | SiteKind::Neg { .. }
2804 | SiteKind::Field { .. }
2805 | SiteKind::Body { .. }
2806 if reached() =>
2807 {
2808 reach_plan(Mutation::Delete)
2809 }
2810 SiteKind::Stmt
2811 | SiteKind::Neg { .. }
2812 | SiteKind::Field { .. }
2813 | SiteKind::Body { .. } => return Planned::Unreached,
2814 SiteKind::Guard { can_be_false } => {
2815 let can_be_false = *can_be_false;
2816 let allowed = move |m: &Mutation| can_be_false || *m != Mutation::Const(false);
2817 let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
2818 let guard_plan = plan::plan_return(&merged);
2819 if guard_plan.unreached {
2820 return Planned::Unreached;
2821 }
2822 let gaps = guard_plan
2823 .always
2824 .filter(|always| allowed(&Mutation::Const(*always)))
2825 .map(|always| PlannedGap {
2826 finding: report::guard_gap_finding(file, site, always, verify),
2827 survivors: vec![Mutation::Const(always)],
2828 constant_expr: Some((site.start, site.end)),
2830 })
2831 .into_iter()
2832 .collect();
2833 SitePlan {
2834 constant: false,
2835 cannot_differ: false,
2836 gaps,
2837 run: guard_plan.run.into_iter().filter(allowed).collect(),
2838 infected: Box::new(move |bin, m| {
2839 tests_where(bin.trace.returns.get(&id), |obs| match m {
2840 Mutation::Const(value) => obs.infected_by_const(value),
2841 _ => obs.reached(),
2842 })
2843 }),
2844 reaching: Box::new(move |bin| {
2845 tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
2846 }),
2847 }
2848 }
2849 SiteKind::Arm { .. } if reached() => reach_plan(Mutation::Delete),
2850 SiteKind::Arm { .. } => return Planned::Unreached,
2851 SiteKind::Not { .. } if reached() => reach_plan(Mutation::DropNot),
2852 SiteKind::Range { .. } if reached() => {
2855 if self
2856 .binaries
2857 .iter()
2858 .any(|b| b.trace.ranges_at_top.contains(&id))
2859 {
2860 return Planned::NotEvaluated;
2861 }
2862 reach_plan(Mutation::RangeEnd)
2863 }
2864 SiteKind::Not { .. } | SiteKind::Range { .. } => {
2867 if self
2868 .merged(|t| t.arith.get(&id), plan::ArithObs::merge)
2869 .opaque
2870 {
2871 return Planned::Nothing;
2872 }
2873 return Planned::Unreached;
2874 }
2875 SiteKind::Cmp { op, literal, .. } => {
2876 let op = *op;
2877 let mut merged = Obs::default();
2878 for bin in &self.binaries {
2879 merged.merge(&bin.trace.merged(id));
2880 }
2881 let bounds = self.binaries.iter().find_map(|b| b.trace.bounds.get(&id));
2882 let cmp_plan = plan::plan_cmp(op, &merged, domain_of(*literal, bounds));
2883 let mut gaps = vec![];
2884 let mut constant = false;
2885 match &cmp_plan.gap {
2886 Some(plan::InputGap::Unreached) => return Planned::Unreached,
2887 Some(gap) => {
2888 constant = matches!(gap, plan::InputGap::OneSided { .. });
2889 if let Some(finding) =
2890 report::input_gap_finding(file, site, gap, &merged, verify)
2891 {
2892 gaps.push(PlannedGap {
2893 finding,
2894 survivors: gap.survivors(),
2895 constant_expr: None,
2896 });
2897 }
2898 }
2899 None => {}
2900 }
2901 SitePlan {
2902 gaps,
2903 constant,
2904 cannot_differ: cmp_plan.cannot_differ,
2905 run: cmp_plan.run,
2906 infected: Box::new(move |bin, m| {
2907 tests_where(bin.trace.cmp.get(&id), |obs| plan::infects(op, m, obs))
2908 }),
2909 reaching: Box::new(move |bin| {
2910 tests_where(bin.trace.cmp.get(&id), Obs::reached)
2911 }),
2912 }
2913 }
2914 SiteKind::Logic {
2915 and,
2916 lhs,
2917 rhs,
2918 gap: op_gap,
2919 } => {
2920 let and = *and;
2921 let lhs_range = core_range(site.start, lhs);
2922 let rhs_range = core_range(op_gap.1, rhs);
2923 let merged = self.merged(|t| t.logic.get(&id), plan::LogicObs::merge);
2924 let logic_plan = plan::plan_logic(and, &merged);
2925 if logic_plan.gaps.contains(&plan::LogicGap::Unreached) {
2926 return Planned::Unreached;
2927 }
2928 let gaps: Vec<_> = logic_plan
2929 .gaps
2930 .iter()
2931 .filter_map(|gap| {
2932 let (mutation, operand) = match gap {
2935 plan::LogicGap::RhsNeverDecides => (Mutation::LogicDropRhs, rhs_range),
2936 _ => (Mutation::LogicDropLhs, lhs_range),
2937 };
2938 Some(PlannedGap {
2939 finding: report::logic_gap_finding(file, site, *gap, verify)?,
2940 survivors: vec![mutation],
2941 constant_expr: Some(operand),
2942 })
2943 })
2944 .collect();
2945 SitePlan {
2946 constant: merged.constant_value(and).is_some(),
2947 cannot_differ: false,
2948 gaps,
2949 run: logic_plan.run,
2950 infected: Box::new(move |bin, m| {
2951 tests_where(bin.trace.logic.get(&id), |obs| {
2952 plan::logic_infects(and, m, obs)
2953 })
2954 }),
2955 reaching: Box::new(move |bin| {
2956 tests_where(bin.trace.logic.get(&id), plan::LogicObs::reached)
2957 }),
2958 }
2959 }
2960 SiteKind::Arith { .. } | SiteKind::MinMax { .. } => {
2961 let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
2964 let mutations: Vec<(Mutation, plan::ArithObs)> = match &site.kind {
2965 SiteKind::MinMax { .. } => vec![(Mutation::MinMax, merged)],
2966 SiteKind::Arith { op, assign, .. } if op.second(*assign).is_some() => vec![
2967 (Mutation::ArithSwap, merged),
2968 (Mutation::ArithSwap2, merged.second()),
2969 ],
2970 _ => vec![(Mutation::ArithSwap, merged)],
2971 };
2972 let (mut gaps, mut run) = (vec![], vec![]);
2973 for (mutation, seen) in mutations {
2974 match plan::plan_arith(&seen) {
2975 plan::ArithPlan::Unreached => return Planned::Unreached,
2976 plan::ArithPlan::Opaque => return Planned::Nothing,
2978 plan::ArithPlan::NeverDiffers => {
2979 let finding = if mutation == Mutation::MinMax {
2980 report::min_max_gap_finding(file, site, verify)
2981 } else {
2982 report::arith_gap_finding(file, site, mutation, verify)
2983 };
2984 gaps.extend(finding.map(|finding| PlannedGap {
2985 finding,
2986 survivors: vec![mutation],
2987 constant_expr: None,
2988 }));
2989 }
2990 plan::ArithPlan::Run => run.push(mutation),
2991 }
2992 }
2993 SitePlan {
2994 gaps,
2995 constant: false,
2996 cannot_differ: false,
2997 run,
2998 infected: Box::new(move |bin, m| {
2999 tests_where(bin.trace.arith.get(&id), |obs| obs.infected_by(m))
3000 }),
3001 reaching: Box::new(move |bin| {
3002 tests_where(bin.trace.arith.get(&id), |obs| obs.same || obs.differs)
3003 }),
3004 }
3005 }
3006 SiteKind::Return {
3007 sole_expr, option, ..
3008 } => {
3009 let sole_expr = *sole_expr;
3010 let is_option = option.is_some();
3011 let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
3012 let return_plan = if is_option {
3013 plan::plan_option_return(&merged)
3014 } else {
3015 plan::plan_return(&merged)
3016 };
3017 if return_plan.unreached {
3018 return Planned::Unreached;
3019 }
3020 let gaps: Vec<_> = return_plan
3021 .always
3022 .and_then(|always| {
3023 Some(PlannedGap {
3024 finding: report::return_gap_finding(file, site, always, verify)?,
3025 survivors: vec![Mutation::Const(always)],
3026 constant_expr: sole_expr,
3028 })
3029 })
3030 .into_iter()
3031 .collect();
3032 SitePlan {
3033 constant: false,
3034 cannot_differ: false,
3035 gaps,
3036 run: return_plan.run,
3037 infected: Box::new(move |bin, m| {
3038 tests_where(bin.trace.returns.get(&id), |obs| match m {
3039 Mutation::Const(value) => obs.infected_by_const(value),
3040 _ => obs.reached(),
3041 })
3042 }),
3043 reaching: Box::new(move |bin| {
3044 tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
3045 }),
3046 }
3047 }
3048 })
3049 }
3050
3051 fn job(
3052 &self,
3053 site: u32,
3054 mutation: Mutation,
3055 tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>,
3056 ) -> Job {
3057 let tests = self
3058 .binaries
3059 .iter()
3060 .enumerate()
3061 .filter_map(|(index, bin)| {
3062 let tests = tests_of(bin);
3063 if tests.is_empty() {
3064 return None;
3065 }
3066 let filter = match bin.runner {
3067 Runner::Exe(_) => test_filter(&tests, &bin.tests),
3068 Runner::Doc { .. } | Runner::Isolated { .. } | Runner::Nextest { .. } => None,
3069 };
3070 Some((index, filter))
3071 })
3072 .collect();
3073 Job {
3074 site,
3075 mutation,
3076 tests,
3077 }
3078 }
3079
3080 fn run_job(&self, job: &Job, sharing: usize) -> Result<JobResult> {
3083 let spec = format!("{}:{}", job.site, job.mutation.encode());
3084 let mut passed = vec![];
3085 let mut tests: Vec<&(usize, Option<Vec<String>>)> = job.tests.iter().collect();
3087 tests.sort_by_key(|(index, _)| self.binaries[*index].baseline);
3088 for (index, filter) in tests {
3089 let bin = &self.binaries[*index];
3090 let outcome = run_binary(
3091 bin,
3092 filter.as_deref(),
3093 &[("TMT_MUTANT", &spec)],
3094 bin.filtered_limit(filter.as_deref(), false),
3095 RunOutput::FirstFailure,
3096 sharing,
3097 )?;
3098 if outcome != Outcome::Pass {
3099 return Ok(JobResult {
3100 first_pass_timeout: false,
3101 unconfirmed_timeout: false,
3102 survived: None,
3103 timed_out: outcome == Outcome::Timeout,
3104 unable: outcome == Outcome::Unable,
3105 });
3106 }
3107 match filter {
3108 Some(names) => passed.extend(names.iter().cloned()),
3109 None if matches!(bin.runner, Runner::Isolated { .. }) => {
3110 passed.push(bin.name.clone())
3111 }
3112 None => passed.push(format!("all tests of `{}`", bin.name)),
3113 }
3114 }
3115 Ok(JobResult {
3116 first_pass_timeout: false,
3117 unconfirmed_timeout: false,
3118 survived: Some(passed),
3119 timed_out: false,
3120 unable: false,
3121 })
3122 }
3123
3124 fn trace_job(
3127 &self,
3128 job: &Job,
3129 scratch: &Path,
3130 sharing: usize,
3131 ) -> Result<BTreeMap<String, BTreeSet<Change>>> {
3132 let spec = format!("{}:{}", job.site, job.mutation.encode());
3133 let mut all: BTreeMap<String, BTreeSet<Change>> = BTreeMap::new();
3134 for (index, filter) in &job.tests {
3135 let bin = &self.binaries[*index];
3136 let path = scratch.join(format!("effects-{}-{index}.tsv", job.site));
3137 let _ = fs::remove_file(&path);
3138 let trace_env = path.to_string_lossy().into_owned();
3139 let outcome = run_binary(
3140 bin,
3141 filter.as_deref(),
3142 &[("TMT_MUTANT", &spec), ("TMT_TRACE", &trace_env)],
3143 bin.filtered_limit(filter.as_deref(), true),
3144 RunOutput::Quiet,
3145 sharing,
3146 )?;
3147 let text = fs::read_to_string(&path).unwrap_or_default();
3148 let _ = fs::remove_file(&path);
3149 if outcome != Outcome::Pass {
3150 continue; }
3152 let mutated = Trace::parse(&text);
3153 let ran: Option<BTreeSet<String>> =
3154 filter.as_ref().map(|names| names.iter().cloned().collect());
3155 let baseline = bin
3156 .effects_baseline
3157 .get_or_init(|| propagation::BaselineIndex::new(&bin.trace));
3158 for (test, found) in baseline.changes(&mutated, ran.as_ref(), job.site) {
3159 all.entry(test).or_default().extend(found);
3160 }
3161 }
3162 Ok(all)
3163 }
3164
3165 fn run_jobs(
3171 &self,
3172 jobs: &[Job],
3173 workers: usize,
3174 label: &str,
3175 checkpoint: Option<&Phase<'_>>,
3176 ) -> Result<Vec<JobResult>> {
3177 if self
3178 .binaries
3179 .first()
3180 .is_some_and(|bin| bin.timeout.is_some())
3181 {
3182 for (index, filter) in jobs.iter().flat_map(|job| &job.tests) {
3183 self.binaries[*index].warn_timeout_conflict(filter.as_deref());
3184 }
3185 }
3186 let run = |index: usize, sharing| self.run_job(&jobs[index], sharing);
3187 evaluate_jobs(
3188 jobs.len(),
3189 workers,
3190 self.serial_timeout_rechecks,
3191 self.progress,
3192 label,
3193 checkpoint,
3194 &run,
3195 )
3196 }
3197}
3198
3199fn evaluate_jobs(
3200 count: usize,
3201 workers: usize,
3202 serial_rechecks: bool,
3203 progress_enabled: bool,
3204 label: &str,
3205 checkpoint: Option<&Phase<'_>>,
3206 run: &(impl Fn(usize, usize) -> Result<JobResult> + Sync),
3207) -> Result<Vec<JobResult>> {
3208 let sharing = workers.clamp(1, count.max(1));
3209 let mut results = progress::track(progress_enabled, label, count, |progress| {
3210 run_pool(count, workers, |index| {
3211 if let Some(cached) = checkpoint
3212 .map(|phase| phase.get::<JobResult>(index))
3213 .transpose()?
3214 .flatten()
3215 {
3216 progress.complete(cached.progress_outcome());
3217 return Ok((cached, false));
3218 }
3219 let mut result = run(index, sharing)?;
3220 if sharing > 1 && result.timed_out {
3221 result.first_pass_timeout = true;
3222 result.unconfirmed_timeout = true;
3223 }
3224 let pending = result.unconfirmed_timeout && serial_rechecks;
3225 if !pending {
3226 if let Some(phase) = checkpoint {
3227 phase.record(index, &result)?;
3228 }
3229 progress.complete(result.progress_outcome());
3230 }
3231 Ok((result, pending))
3232 })
3233 })?;
3234 let pending: Vec<_> = results
3235 .iter()
3236 .enumerate()
3237 .filter_map(|(index, (_, pending))| pending.then_some(index))
3238 .collect();
3239 if !pending.is_empty() && progress_enabled {
3240 eprintln!(
3241 "tmt: {label}: {} first-pass timeouts, {} pending serial rechecks",
3242 pending.len(),
3243 if serial_rechecks { pending.len() } else { 0 }
3244 );
3245 }
3246 if serial_rechecks {
3247 progress::track_timeout_rechecks(progress_enabled, pending.len(), |progress| {
3248 for index in pending {
3249 let mut confirmed = run(index, 1)?;
3250 confirmed.first_pass_timeout = true;
3251 let outcome = if confirmed.timed_out {
3252 progress::Outcome::TimedOut
3253 } else if confirmed.unable {
3254 progress::Outcome::Unable
3255 } else {
3256 progress::Outcome::Survived
3257 };
3258 if let Some(phase) = checkpoint {
3259 phase.record(index, &confirmed)?;
3260 }
3261 results[index] = (confirmed, false);
3262 progress.complete(outcome);
3263 }
3264 Ok::<_, anyhow::Error>(())
3265 })?;
3266 }
3267 if let Some(phase) = checkpoint {
3268 phase.finish()?;
3269 }
3270 Ok(results.into_iter().map(|(result, _)| result).collect())
3271}
3272
3273fn run_pool<T: Send>(
3276 count: usize,
3277 workers: usize,
3278 work: impl Fn(usize) -> Result<T> + Sync,
3279) -> Result<Vec<T>> {
3280 if count == 0 {
3281 return Ok(vec![]);
3282 }
3283 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
3284 let next = AtomicUsize::new(0);
3285 let stop = AtomicBool::new(false);
3286 let done: Vec<Vec<(usize, Result<T>)>> = std::thread::scope(|scope| {
3287 let handles: Vec<_> = (0..workers.clamp(1, count))
3288 .map(|_| {
3289 scope.spawn(|| {
3290 let mut mine = vec![];
3291 while !stop.load(Ordering::Acquire) {
3292 let index = next.fetch_add(1, Ordering::Relaxed);
3293 if index >= count {
3294 break;
3295 }
3296 let result = work(index);
3297 if result.is_err() {
3298 stop.store(true, Ordering::Release);
3299 }
3300 mine.push((index, result));
3301 }
3302 mine
3303 })
3304 })
3305 .collect();
3306 handles
3307 .into_iter()
3308 .map(|handle| handle.join().expect("worker panicked"))
3309 .collect()
3310 });
3311 let mut ordered: Vec<Option<Result<T>>> = (0..count).map(|_| None).collect();
3312 for (index, result) in done.into_iter().flatten() {
3313 ordered[index] = Some(result);
3314 }
3315 ordered.into_iter().flatten().collect()
3316}
3317
3318impl std::str::FromStr for report::Shard {
3319 type Err = anyhow::Error;
3320
3321 fn from_str(text: &str) -> Result<Self> {
3322 let (index, count) = text.split_once('/').context("expected a shard index K/N")?;
3323 let index: usize = index.parse().context("invalid shard index")?;
3324 let count: usize = count.parse().context("invalid shard count")?;
3325 if index >= count {
3326 bail!("shard index must be less than the shard count");
3327 }
3328 Ok(Self {
3329 index,
3330 count,
3331 round_robin: false,
3332 })
3333 }
3334}
3335
3336impl report::Shard {
3337 fn contains(self, candidate: usize, candidates: usize) -> bool {
3338 candidate < candidates
3339 && (if self.round_robin {
3340 candidate % self.count
3341 } else {
3342 candidate / candidates.div_ceil(self.count)
3343 }) == self.index
3344 }
3345}
3346
3347fn cargo_metadata(dir: &Path, cargo: &CargoConfig) -> Result<Metadata> {
3348 let output = Command::new("cargo")
3349 .args(["metadata", "--no-deps", "--format-version", "1"])
3350 .args(cargo.flags())
3351 .current_dir(dir)
3352 .output()
3353 .context("running cargo metadata")?;
3354 if !output.status.success() {
3355 bail!(
3356 "cargo metadata failed:\n{}",
3357 String::from_utf8_lossy(&output.stderr)
3358 );
3359 }
3360 serde_json::from_slice(&output.stdout).context("parsing cargo metadata")
3361}
3362
3363#[derive(Clone, Copy)]
3364struct WorkspaceShard {
3365 offset: usize,
3366 total: usize,
3367 member_total: usize,
3368}
3369
3370struct CatalogueSnapshot {
3371 path: PathBuf,
3372 ready: std::cell::Cell<bool>,
3373 _lock: WorkLock,
3374}
3375
3376struct WorkspaceBatch<'a> {
3377 metadata: &'a Metadata,
3378 work: &'a Path,
3379 catalogue: Option<CatalogueSnapshot>,
3380}
3381
3382pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
3384 let mut reports = vec![];
3385 run_packages_each(options, names, |name, result| {
3386 reports.push((name, result));
3387 Ok(())
3388 })?;
3389 Ok(reports)
3390}
3391
3392pub fn run_packages_each(
3394 options: &Options,
3395 names: &[String],
3396 mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
3397) -> Result<()> {
3398 if options.baseline.is_some() || options.write_baseline.is_some() {
3399 bail!("baseline files require a single package");
3400 }
3401 let metadata = cargo_metadata(&options.dir, &options.cargo)?;
3402 let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
3403 let selected = if names.is_empty() {
3404 all.clone()
3405 } else {
3406 names.iter().cloned().collect()
3407 };
3408 if let Some(unknown) = selected.difference(&all).next() {
3409 bail!("no package `{unknown}` in the workspace");
3410 }
3411 let base = options
3412 .work_dir
3413 .clone()
3414 .unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
3415 fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
3416 let base = base.canonicalize()?;
3417 if metadata.workspace_root.canonicalize()?.starts_with(&base) {
3418 bail!(
3419 "the work directory {} contains the workspace",
3420 base.display()
3421 );
3422 }
3423 let catalogue = if options.list || options.shard.is_some() {
3424 let path = work_directory(&base, ".catalogue")?;
3425 Some(CatalogueSnapshot {
3426 _lock: WorkLock::take(&path)?,
3427 path,
3428 ready: std::cell::Cell::new(false),
3429 })
3430 } else {
3431 None
3432 };
3433 let batch = WorkspaceBatch {
3434 metadata: &metadata,
3435 work: &base,
3436 catalogue,
3437 };
3438 let member_options = selected.into_iter().map(|name| {
3439 let mut member = options.clone();
3440 member.package = Some(name.clone());
3441 member.work_dir = Some(base.join(&name));
3442 (name, member)
3443 });
3444 let Some(shard) = options.shard else {
3445 for (name, member) in member_options {
3446 let result = run_package(&member, Some(&batch), None);
3447 completed(name, result)?;
3448 }
3449 return Ok(());
3450 };
3451 if !options.source_only || shard.index >= shard.count {
3452 bail!("shards require --source-only and a valid shard index");
3453 }
3454 let catalogues: Vec<_> = member_options
3457 .map(|(name, member)| {
3458 let mut preview = member.clone();
3459 preview.list = true;
3460 preview.shard = None;
3461 preview.progress = false;
3462 let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
3463 let count = report.mutants.as_ref().map_or(0, Vec::len);
3464 if !member.list {
3465 report.mutants = None;
3466 }
3467 (count, report)
3468 });
3469 (name, member, catalogue)
3470 })
3471 .collect();
3472 let total = catalogues
3473 .iter()
3474 .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
3475 .map(|(count, _)| count)
3476 .sum();
3477 let mut offset = 0;
3478 for (name, member, catalogue) in catalogues {
3479 let result = catalogue.and_then(|(member_total, mut report)| {
3480 let range = WorkspaceShard {
3481 offset,
3482 total,
3483 member_total,
3484 };
3485 offset += member_total;
3486 if member.list {
3487 report.analysis.shard = Some(shard);
3488 let mut index = range.offset;
3489 report
3490 .mutants
3491 .as_mut()
3492 .expect("source catalogue")
3493 .retain(|_| {
3494 let keep = shard.contains(index, total);
3495 index += 1;
3496 keep
3497 });
3498 Ok(report)
3499 } else {
3500 run_package(&member, Some(&batch), Some(range))
3501 }
3502 });
3503 completed(name, result)?;
3504 }
3505 Ok(())
3506}
3507
3508struct LeftoverNote(bool);
3510
3511impl Drop for LeftoverNote {
3512 fn drop(&mut self) {
3513 use std::sync::atomic::Ordering;
3514 let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
3515 let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
3516 if let Some(text) = leftover_note(stopped, not_stopped)
3517 && self.0
3518 {
3519 eprintln!("tmt: {text}");
3520 }
3521 }
3522}
3523
3524fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
3525 let stopped = (stopped > 0).then(|| {
3526 format!("stopped {stopped} processes that the tests had left running after their run")
3527 });
3528 let not_stopped = (not_stopped > 0).then(|| {
3529 format!(
3530 "after {not_stopped} runs something the tests started may still be running \
3531 (it could not be found or stopped)"
3532 )
3533 });
3534 match (stopped, not_stopped) {
3535 (None, None) => None,
3536 (Some(one), None) | (None, Some(one)) => Some(one),
3537 (Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
3538 }
3539}
3540
3541pub fn run(options: &Options) -> Result<Report> {
3542 run_package(options, None, None)
3543}
3544
3545fn run_package(
3546 options: &Options,
3547 batch: Option<&WorkspaceBatch<'_>>,
3548 workspace_shard: Option<WorkspaceShard>,
3549) -> Result<Report> {
3550 let _leftovers = LeftoverNote(options.progress);
3551 if let Some(shard) = options.shard
3552 && (!options.source_only || shard.index >= shard.count)
3553 {
3554 bail!("shards require --source-only and a valid shard index");
3555 }
3556 let mut seen_errors = HashSet::new();
3557 let mut error_values = vec![];
3558 for expression in &options.error_values {
3559 let expression = expression.trim();
3560 if expression.chars().any(char::is_control) {
3563 bail!(
3564 "invalid --error expression {expression:?}: it has to be on one line, \
3565 without control characters"
3566 );
3567 }
3568 let parsed = syn::parse_str::<syn::Expr>(expression)
3569 .with_context(|| format!("invalid --error expression {expression:?}"))?;
3570 if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3571 error_values.push(expression);
3572 }
3573 }
3574 let selection = &options.test_selection;
3575 if options.nextest.is_some() {
3576 if !cfg!(unix) {
3577 bail!("the nextest runner is available on Unix");
3578 }
3579 if !options.source_only || options.doc || selection.enabled() {
3580 bail!(
3581 "--test-tool nextest requires --source-only; select tests through the nextest profile"
3582 );
3583 }
3584 }
3585 if options.baseline_jobs > 1 && !selection.enabled() {
3586 bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3587 }
3588 if options.doc && selection.enabled() {
3589 bail!("--doc cannot be combined with isolated test selection");
3590 }
3591 let note = |text: &str| {
3592 if options.progress {
3593 eprintln!("tmt: {text}");
3594 }
3595 };
3596 let dir = options
3597 .dir
3598 .canonicalize()
3599 .with_context(|| format!("no such directory: {}", options.dir.display()))?;
3600
3601 let local_metadata;
3602 let metadata = if let Some(batch) = batch {
3603 batch.metadata
3604 } else {
3605 local_metadata = cargo_metadata(&dir, &options.cargo)?;
3606 &local_metadata
3607 };
3608 let catalogue = batch
3609 .and_then(|batch| batch.catalogue.as_ref())
3610 .filter(|_| options.list);
3611 let package = match &options.package {
3612 Some(name) => metadata.packages.iter().find(|p| &p.name == name),
3613 None => metadata
3614 .packages
3615 .iter()
3616 .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
3617 .or(match &metadata.packages[..] {
3618 [only] => Some(only),
3619 _ => None,
3620 }),
3621 }
3622 .ok_or_else(|| anyhow!("cannot tell which package to analyse; pass --package <name>"))?;
3623 let mut test_packages: Vec<&Package> = vec![package];
3626 for name in &options.also_test {
3627 let other = metadata
3628 .packages
3629 .iter()
3630 .find(|p| &p.name == name)
3631 .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
3632 if !test_packages.iter().any(|p| p.name == other.name) {
3633 test_packages.push(other);
3634 }
3635 }
3636 if options.test_workspace {
3637 test_packages.extend(
3638 metadata
3639 .packages
3640 .iter()
3641 .filter(|other| {
3642 !test_packages
3643 .iter()
3644 .any(|selected| selected.name == other.name)
3645 })
3646 .collect::<Vec<_>>(),
3647 );
3648 }
3649 if options.dependents {
3650 for name in dependents_of(&package.name, &metadata.packages) {
3651 if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
3652 && !test_packages.iter().any(|p| p.name == other.name)
3653 {
3654 test_packages.push(other);
3655 }
3656 }
3657 }
3658 let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
3659 let root_target = package
3660 .targets
3661 .iter()
3662 .find(|t| {
3663 is_kind(
3664 t,
3665 &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
3666 )
3667 })
3668 .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
3669 .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
3670
3671 let workspace = metadata.workspace_root.canonicalize()?;
3673 let requested_work = catalogue
3674 .map(|catalogue| &catalogue.path)
3675 .or(options.work_dir.as_ref());
3676 let work = match requested_work {
3677 Some(dir) => {
3678 fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3679 dir.canonicalize()?
3680 }
3681 None => metadata.target_directory.join("tmt"),
3682 };
3683 if workspace.starts_with(&work) {
3686 bail!(
3687 "the work directory {} contains the workspace; choose a directory of its own",
3688 work.display()
3689 );
3690 }
3691 fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
3692 let work = work.canonicalize()?;
3693 let work_lock = if catalogue.is_none() {
3694 Some(Arc::new(WorkLock::take(&work)?))
3695 } else {
3696 None
3697 };
3698 let copy = work.join("src");
3699 let marker = work.join(WORK_MARKER);
3700 if copy.exists() && !marker.exists() {
3701 bail!(
3702 "{} exists and was not created by tmt; refusing to delete it. \
3703 Choose another --work-dir or remove it yourself.",
3704 copy.display()
3705 );
3706 }
3707 fs::write(
3708 &marker,
3709 "Working directory of tmt (targeted-mutation). Safe to delete.\n",
3710 )?;
3711 let target_dir = metadata.target_directory.clone();
3712 let forbidden = |path: &Path| {
3713 path == target_dir
3714 || path == work
3715 || batch.is_some_and(|batch| path == batch.work)
3716 || path.file_name().is_some_and(|n| n == ".git")
3717 || (path.parent() == Some(workspace.as_path())
3718 && path.file_name().is_some_and(|n| n == "target"))
3719 };
3720 let state = WorkCopy::open(&work, ©);
3721 let fixtures = options
3722 .copy_fixtures
3723 .iter()
3724 .map(|path| fixture_relative(path))
3725 .collect::<Result<Vec<_>>>()?;
3726 let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
3727 let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
3728 let skip = |path: &Path| {
3729 fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
3730 };
3731 if options.progress && !options.list {
3732 for path in &excluded {
3733 note(&format!(
3734 "excluded fixture {}",
3735 path.strip_prefix(&workspace).unwrap_or(path).display()
3736 ));
3737 }
3738 }
3739 if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
3740 work_directory(&work, "src")?;
3741 let visible = if options.all_files {
3742 None
3743 } else {
3744 git_visible_files(&workspace)?
3745 };
3746 match visible {
3747 Some(files) => {
3750 let copied = copy_git_visible(&workspace, ©, files, &workspace, &skip, &state)?;
3751 note(&format!(
3752 "copied {copied} files (ignored files are left out)"
3753 ));
3754 }
3755 None => copy_tree(&workspace, ©, &workspace, &skip, &state)?,
3756 }
3757 for relative in &fixtures {
3758 copy_fixture_entry(
3759 &workspace.join(relative),
3760 ©.join(relative),
3761 &workspace,
3762 &fixture_forbidden,
3763 &state,
3764 &mut BTreeSet::new(),
3765 )?;
3766 }
3767 prune(©, &state)?;
3768 if options.git_index {
3769 git_index::snapshot(&workspace, ©)?;
3770 }
3771 if !options.list {
3772 let mut manifests: Vec<&Path> = metadata
3774 .packages
3775 .iter()
3776 .map(|p| p.manifest_path.as_path())
3777 .collect();
3778 let root_manifest = metadata.workspace_root.join("Cargo.toml");
3779 manifests.push(&root_manifest);
3780 for manifest in manifests {
3781 let Ok(canonical) = manifest.canonicalize() else {
3782 continue;
3783 };
3784 let (Some(manifest_dir), Ok(relative)) =
3785 (canonical.parent(), canonical.strip_prefix(&workspace))
3786 else {
3787 continue;
3788 };
3789 let text = fs::read_to_string(&canonical)?;
3790 if let Some(rewritten) =
3791 absolutize_path_dependencies(&text, manifest_dir, &workspace, ©)?
3792 {
3793 state.write(©.join(relative), &rewritten)?;
3794 }
3795 }
3796 }
3797 if let Some(catalogue) = catalogue {
3798 state.settle(&workspace)?;
3799 catalogue.ready.set(true);
3800 }
3801 }
3802
3803 let in_copy = |path: &Path| -> Result<PathBuf> {
3804 let canonical = path.canonicalize()?;
3805 let relative = canonical
3806 .strip_prefix(&workspace)
3807 .with_context(|| format!("{} is outside the workspace", path.display()))?;
3808 Ok(copy.join(relative))
3809 };
3810 let package_dir = in_copy(
3811 package
3812 .manifest_path
3813 .parent()
3814 .expect("manifest has a parent"),
3815 )?;
3816 let root_file = in_copy(&root_target.src_path)?;
3817 let source_dir = root_file
3818 .parent()
3819 .expect("source file has a parent")
3820 .to_path_buf();
3821
3822 let mut roots = BTreeMap::new();
3825 for owner in &metadata.packages {
3826 for target in &owner.targets {
3827 let production = owner.name == package.name && target.is_production();
3828 if let Ok(path) = in_copy(&target.src_path)
3829 && path.is_file()
3830 {
3831 let selected = roots.entry(path).or_insert(false);
3832 *selected |= production;
3833 }
3834 }
3835 }
3836 let paths = source_graph(roots, ©, |path| state.original(path, &workspace))?;
3837 let scope = requested_scope(options, &workspace, &package_dir, ©)?;
3838 let mut skipped = vec![];
3839 let mut files = vec![];
3840 let mut next_id = 0u32;
3841 let want_witnesses = (options.list || options.rebuild || options.source_only)
3842 && root_target.test_build_arg() == Some(("--lib", None));
3843 let mut witness_candidates = vec![];
3844 for (path, owners) in paths {
3845 let Some(original) = state.original(&path, &workspace)? else {
3846 continue; };
3848 let selected_file = scope.as_ref().is_none_or(|scope| {
3849 let relative = path.strip_prefix(©).unwrap_or(&path).to_string_lossy();
3850 scope.touches(&relative, 1, usize::MAX)
3851 });
3852 if !selected_file && path != root_file {
3853 continue;
3854 }
3855 let display = relative_source(&path, &package_dir).display().to_string();
3856 match instrument::parse_source(&original) {
3857 Ok(parsed) => {
3858 let mut found =
3859 instrument::discover_parsed(&original, &parsed, next_id, &error_values);
3860 if want_witnesses && selected_file && path == root_file {
3861 witness_candidates =
3862 witness::discover_parsed(&original, &parsed, !options.list);
3863 }
3864 next_id += found.sites.len() as u32;
3865 if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
3866 found.rebuild_sites.append(&mut found.sites);
3867 }
3868 let places = if options.list {
3869 vec![]
3870 } else {
3871 found
3872 .sites
3873 .iter()
3874 .chain(&found.rebuild_sites)
3875 .map(|site| (site.line, site.column, report::one_line(&site.text)))
3876 .collect()
3877 };
3878 files.push(SourceFile {
3879 display,
3880 path,
3881 owners: owners.production,
3882 lines: scope::LineIndex::new(&original),
3883 original,
3884 places,
3885 sites: found.sites,
3886 rebuild_sites: found.rebuild_sites,
3887 rendered: None,
3888 });
3889 }
3890 Err(err) => {
3891 if selected_file {
3892 let diagnostic = format!("{err:#}");
3893 note(&format!("skipping {display}: {diagnostic}"));
3894 let end_line = scope::line_of(&original, original.len());
3895 let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
3896 skipped.push(report::SkippedSite::new(
3897 report::Location {
3898 file: display,
3899 line: 1,
3900 column: 1,
3901 ..Default::default()
3902 },
3903 (end_line, end_column),
3904 report::SkipReason::UnparseableSource,
3905 Some(diagnostic),
3906 ));
3907 }
3908 }
3909 }
3910 }
3911
3912 if let Some(scope) = &scope {
3914 for file in &mut files {
3915 let relative = file
3916 .path
3917 .strip_prefix(©)
3918 .unwrap_or(&file.path)
3919 .to_string_lossy()
3920 .into_owned();
3921 let in_scope = |site: &Site| {
3922 scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
3923 || scope.touches(&relative, site.line, site.line)
3925 };
3926 file.sites.retain(in_scope);
3927 file.rebuild_sites.retain(in_scope);
3928 }
3929 files.retain(|f| !f.sites.is_empty() || !f.rebuild_sites.is_empty() || f.path == root_file);
3930 }
3931 if !witness_candidates.is_empty()
3932 && let Some(file) = files.iter_mut().find(|file| file.path == root_file)
3933 {
3934 let relative = file
3935 .path
3936 .strip_prefix(©)
3937 .unwrap_or(&file.path)
3938 .to_string_lossy();
3939 if !options.list {
3940 let locations: Vec<_> = witness_candidates
3941 .iter()
3942 .filter(|candidate| !candidate.existing)
3943 .map(|candidate| {
3944 let at = witness_location(file, candidate);
3945 (at.line, at.column, at.code)
3946 })
3947 .collect();
3948 file.places.extend(locations);
3949 }
3950 witness_candidates.retain(|candidate| {
3951 scope.as_ref().is_none_or(|scope| {
3952 let site_in_scope = if candidate.edits.len() == 1 {
3953 scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
3954 } else {
3955 candidate.edits.iter().any(|edit| {
3956 scope.touches(
3957 &relative,
3958 file.lines.line_of(edit.span.start),
3959 file.lines.line_of(edit.span.end),
3960 )
3961 })
3962 };
3963 site_in_scope
3964 || candidate
3965 .signature_lines
3966 .iter()
3967 .any(|&line| scope.touches(&relative, line, line))
3968 })
3969 });
3970 }
3971 let total_sites: usize = files
3972 .iter()
3973 .map(|f| f.sites.len() + f.rebuild_sites.len())
3974 .sum::<usize>()
3975 + witness_candidates
3976 .iter()
3977 .filter(|candidate| !candidate.existing)
3978 .count();
3979 note(&format!("{} sites in {} files", total_sites, files.len()));
3980 if options.source_only {
3981 for file in &mut files {
3982 file.rebuild_sites.append(&mut file.sites);
3983 }
3984 }
3985
3986 let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
3987 let mut mutants = instrument::source_mutants(site);
3988 if include_boundary {
3989 mutants.extend(instrument::source_boundary_mutant(site));
3990 }
3991 if options.literal_operators {
3992 instrument::literal_operator_mutants(&file.original, site, &mut mutants);
3993 }
3994 mutants
3995 };
3996 let counts = options.shard.map(|_| {
3997 let regular: usize = files
3998 .iter()
3999 .map(|file| {
4000 file.rebuild_sites
4001 .iter()
4002 .map(|site| source_mutants(file, site, true).len())
4003 .sum::<usize>()
4004 })
4005 .sum();
4006 let total = regular
4007 + witness_candidates
4008 .iter()
4009 .filter(|candidate| !candidate.existing)
4010 .count();
4011 (regular, total)
4012 });
4013 if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
4014 && range.member_total != local_total
4015 {
4016 bail!("package catalogue changed while preparing its workspace shard");
4017 }
4018 let in_shard = |index| match (options.shard, counts, workspace_shard) {
4019 (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
4020 (Some(shard), Some((_, total)), _) => shard.contains(index, total),
4021 _ => true,
4022 };
4023 if let Some((mut index, _)) = counts {
4024 witness_candidates.retain(|candidate| {
4025 if candidate.existing {
4026 return true;
4027 }
4028 let selected = in_shard(index);
4029 index += 1;
4030 selected
4031 });
4032 }
4033 let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
4034
4035 let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
4036 let mut report_path = repository_prefix(package_path);
4037 if report_path.is_empty()
4038 && batch.is_some()
4039 && let Ok(relative) = package_path.strip_prefix(&workspace)
4040 && !relative.as_os_str().is_empty()
4041 {
4042 report_path = format!("{}/", relative.to_string_lossy().replace('\\', "/"));
4043 }
4044 let mut report = Report {
4045 package: package.name.clone(),
4046 sites: if empty_shard { 0 } else { total_sites },
4047 analysis: report::Analysis {
4048 package_path: report_path,
4049 since: options.since.clone(),
4050 lines: options.lines.clone(),
4051 tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
4052 cargo: options.cargo.clone(),
4053 opt_level: options.opt_level,
4054 timeout_seconds: options.timeout_seconds,
4055 baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
4056 timeout_recheck: if options.serial_timeout_rechecks {
4057 "serial"
4058 } else {
4059 "none"
4060 },
4061 wrapper_grace_seconds: selection
4062 .wrapper
4063 .as_ref()
4064 .map(|_| options.wrapper_grace.as_secs()),
4065 rebuild: options.rebuild || options.source_only,
4066 verified: options.verify && !options.source_only,
4067 doc_tests: options.doc,
4068 source_only: options.source_only,
4069 literal_operators: options.literal_operators,
4070 shard: options.shard,
4071 nextest: options.nextest.clone(),
4072 error_values: error_values
4073 .iter()
4074 .map(|value| (*value).to_owned())
4075 .collect(),
4076 test_selection: None,
4077 git_index: options.git_index,
4078 copy_fixtures: options.copy_fixtures.clone(),
4079 copy_fixture_excludes: options.copy_fixture_excludes.clone(),
4080 output_fixtures: options.output_fixtures.clone(),
4081 checkpoint: (options.checkpoint && !options.list)
4082 .then(|| work.join("checkpoint.jsonl")),
4083 },
4084 skipped,
4085 ..Report::default()
4086 };
4087 if options.list {
4088 if catalogue.is_none() {
4089 state.settle(&workspace)?;
4090 }
4091 let mut candidates = vec![];
4092 let mut index = 0;
4093 for file in &files {
4094 let sites = file
4095 .sites
4096 .iter()
4097 .map(|site| (site, false))
4098 .chain(file.rebuild_sites.iter().map(|site| (site, true)));
4099 for (site, requires_rebuild) in sites {
4100 for mutant in source_mutants(file, site, true) {
4101 if in_shard(index) {
4102 candidates.push(report::Candidate {
4103 what: mutant.what,
4104 into: mutant.into,
4105 requires_rebuild,
4106 edits: vec![candidate_edit(
4107 file,
4108 mutant.start,
4109 mutant.end,
4110 mutant.replacement,
4111 )],
4112 });
4113 }
4114 index += 1;
4115 }
4116 }
4117 }
4118 if let Some(root) = files.iter().find(|file| file.path == root_file) {
4119 candidates.extend(
4120 witness_candidates
4121 .iter()
4122 .filter(|candidate| !candidate.existing)
4123 .map(|candidate| report::Candidate {
4124 what: "witness".into(),
4125 into: candidate.description.clone(),
4126 requires_rebuild: true,
4127 edits: candidate
4128 .edits
4129 .iter()
4130 .map(|edit| {
4131 candidate_edit(
4132 root,
4133 edit.span.start,
4134 edit.span.end,
4135 edit.replacement.clone(),
4136 )
4137 })
4138 .collect(),
4139 }),
4140 );
4141 }
4142 report.mutants = Some(candidates);
4143 return Ok(report);
4144 }
4145 if empty_shard || (scope.is_some() && total_sites == 0) {
4146 state.settle(&workspace)?;
4148 if let Some(path) = &options.baseline {
4149 crate::baseline::load(path)?;
4150 }
4151 if let Some(path) = &options.write_baseline {
4152 crate::baseline::write(path, &[])?;
4153 }
4154 report.record_evaluation();
4155 if let Some(path) = report.analysis.checkpoint.as_deref() {
4156 let checkpoint = Checkpoint::open(path)?;
4157 let settings =
4158 serde_json::json!({"analysis": &report.analysis, "package": &package.name});
4159 let identity = crate::campaign_identity::compute(©, &settings, [], false)?;
4160 checkpoint.start(&identity, settings)?;
4161 checkpoint.finish()?;
4162 }
4163 return Ok(report);
4164 }
4165
4166 for (id, site) in files
4169 .iter_mut()
4170 .flat_map(|file| &mut file.sites)
4171 .enumerate()
4172 {
4173 site.id = id as u32;
4174 }
4175
4176 let root_source = state
4177 .original(&root_file, &workspace)?
4178 .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
4179 let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
4180 String::new()
4181 } else {
4182 state.write(
4183 &source_dir.join(format!("{RUNTIME_MOD}.rs")),
4184 crate::RUNTIME_SOURCE,
4185 )?;
4186 let std_alias = format!("extern crate std as {STD_ALIAS};");
4187 if root_source.contains(&std_alias) {
4188 format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
4189 } else {
4190 format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
4191 }
4192 };
4193
4194 let mut disabled: HashSet<u32> = HashSet::new();
4196 let mut repairs = BTreeMap::new();
4197 let build_target = work_directory(&work, "target")?;
4198 let target_flags = test_build_flags(
4199 &test_packages,
4200 &selection.targets,
4201 &workspace,
4202 &options.cargo,
4203 );
4204 let build_scope = if target_flags.is_some() {
4205 report::TestBuildScope::SelectedTargets
4206 } else {
4207 report::TestBuildScope::PackageWide
4208 };
4209 let build_note = if !selection.targets.is_empty() && target_flags.is_none() {
4210 "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
4211 } else {
4212 ""
4213 };
4214 if !build_note.is_empty() {
4215 note(build_note.trim_end());
4216 }
4217 let can_build_only_observer = !options.doc
4220 && target_flags.is_none()
4221 && test_packages.len() == 1
4222 && package.targets.len() == 1
4223 && root_target.test
4224 && root_target.test_build_arg() == Some(("--lib", None));
4225 let build_test_binaries = |observer: bool| {
4226 let mut command = Command::new("cargo");
4227 isolate_copy_command(&mut command, &work);
4228 if let Some(lock) = &work_lock {
4229 lock.retain_for(&mut command);
4230 }
4231 command
4232 .args(["test", "--no-run", "--message-format=json"])
4233 .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
4234 .args(target_flags.as_deref().unwrap_or_default())
4235 .args((observer && can_build_only_observer).then_some("--lib"))
4236 .args(options.cargo.flags())
4237 .current_dir(©)
4238 .env("CARGO_TARGET_DIR", &build_target)
4239 .env("CARGO_BUILD_BUILD_DIR", &build_target)
4240 .envs(profile_env(options.opt_level))
4241 .stderr(Stdio::piped())
4242 .output()
4243 .context("running cargo test --no-run")
4244 };
4245 let cargo_build = || build_test_binaries(false);
4246 let mut rounds = 0;
4247 let mut newly_disabled = HashSet::new();
4248 let build = loop {
4249 for file in &mut files {
4250 let suffix = if file.path == root_file {
4251 root_suffix.as_str()
4252 } else {
4253 ""
4254 };
4255 write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
4256 }
4257 if !files.iter().any(|f| f.path == root_file) {
4258 state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
4259 }
4260 if rounds == 0 {
4261 state.settle(&workspace)?;
4262 }
4263 note(if rounds == 0 {
4264 "building the instrumented crate"
4265 } else {
4266 "rebuilding without the sites that failed to compile"
4267 });
4268 let output = cargo_build()?;
4269 let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
4270 let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
4271 if output.status.success() {
4272 break build;
4273 }
4274 let diagnostics = || {
4275 [
4276 build.diagnostics.join("\n"),
4277 String::from_utf8_lossy(&output.stderr).into_owned(),
4278 ]
4279 .into_iter()
4280 .filter(|part| !part.trim().is_empty())
4281 .collect::<Vec<_>>()
4282 .join("\n")
4283 };
4284 if build.errors.is_empty() {
4285 bail!("the build failed:\n{build_note}{}", diagnostics());
4286 }
4287 rounds += 1;
4288 let before = disabled.len();
4289 let mut blamed_now: HashSet<u32> = HashSet::new();
4290 for error in &build.errors {
4291 let blamed = blame_error(error, &files, ©, &disabled);
4292 if std::env::var_os("TMT_DEBUG").is_some() {
4293 eprintln!("tmt: debug: blaming {blamed:?} for\n{}", error.rendered);
4294 }
4295 for id in blamed {
4296 repairs
4297 .entry(id)
4298 .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
4299 blamed_now.insert(id);
4300 }
4301 }
4302 disabled.extend(blamed_now.iter().copied());
4303 newly_disabled = blamed_now;
4304 if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
4305 bail!(
4306 "the crate does not build after instrumentation.\n\
4307 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
4308 diagnostics()
4309 );
4310 }
4311 };
4312 let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
4313 BuiltSources::from_artifacts(&build.artifacts, ©)
4314 } else {
4315 BuiltSources::default()
4316 };
4317 output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
4318 let checkpoint_path = report.analysis.checkpoint.as_deref();
4319 let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
4320 let doc_packages = test_packages
4321 .iter()
4322 .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
4323 if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
4324 bail!("{build_note}`{}` has no test binaries", package.name);
4325 }
4326
4327 let mut session = Session {
4329 progress: options.progress,
4330 serial_timeout_rechecks: options.serial_timeout_rechecks,
4331 package_dir,
4332 binaries: vec![],
4333 };
4334 let wrapper = selection
4335 .wrapper
4336 .as_ref()
4337 .map(|path| {
4338 if path.is_absolute()
4339 || path
4340 .components()
4341 .any(|c| matches!(c, std::path::Component::ParentDir))
4342 {
4343 bail!(
4344 "--test-wrapper must be a path inside the workspace: {}",
4345 path.display()
4346 );
4347 }
4348 let copied = copy.join(path);
4349 if !copied.is_file() {
4350 bail!(
4351 "test wrapper is missing from the work copy: {}",
4352 copied.display()
4353 );
4354 }
4355 Ok(copied)
4356 })
4357 .transpose()?;
4358 let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
4359 let root_test_exe = |built: &BuildOutput| {
4360 built
4361 .test_binaries
4362 .iter()
4363 .find(|(name, _, owner, kind)| {
4364 *name == root_target.name && *owner == package.name && *kind == root_target.kind
4365 })
4366 .map(|(_, exe, _, _)| exe.clone())
4367 };
4368 let root_exe = (!witness_candidates.is_empty())
4369 .then(|| root_test_exe(&build))
4370 .flatten();
4371 if let Some(nextest) = &options.nextest {
4372 let mut flags: Vec<_> = test_packages
4373 .iter()
4374 .flat_map(|p| ["-p".to_owned(), p.name.clone()])
4375 .collect();
4376 flags.extend(options.cargo.flags());
4377 runners.push((
4378 "nextest".to_owned(),
4379 Runner::Nextest {
4380 copy: copy.clone(),
4381 target_dir: build_target.clone(),
4382 profile: nextest.profile.clone(),
4383 opt_level: options.opt_level,
4384 flags,
4385 },
4386 session.package_dir.clone(),
4387 ));
4388 } else {
4389 for (name, exe, owner, kind) in build.test_binaries {
4390 if !selection.targets.is_empty() && !selection.targets.contains(&name) {
4391 continue;
4392 }
4393 let owner_package = test_packages
4394 .iter()
4395 .find(|p| p.name == owner)
4396 .expect("binaries are filtered by these packages");
4397 let cwd = in_copy(
4398 owner_package
4399 .manifest_path
4400 .parent()
4401 .expect("manifest has a parent"),
4402 )?;
4403 if selection.enabled() {
4404 let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
4405 let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
4406 for test in all {
4407 let was_ignored = ignored.contains(&test);
4408 if (was_ignored && !selection.include_ignored)
4409 || (!selection.include.is_empty() && !selection.include.contains(&test))
4410 || selection.exclude.contains(&test)
4411 {
4412 continue;
4413 }
4414 runners.push((
4415 format!("{owner}::{}::{name}::{test}", kind.join("+")),
4416 Runner::Isolated {
4417 exe: exe.clone(),
4418 test,
4419 ignored: was_ignored,
4420 wrapper: wrapper.clone(),
4421 },
4422 cwd.clone(),
4423 ));
4424 }
4425 continue;
4426 }
4427 let name = if owner == package.name {
4429 name
4430 } else {
4431 format!("{owner}::{name}")
4432 };
4433 runners.push((name, Runner::Exe(exe), cwd));
4434 }
4435 }
4436 if selection.enabled() && runners.is_empty() {
4437 bail!("{build_note}no tests matched the requested selection");
4438 }
4439 let selected_tests = selection.enabled().then(|| report::TestSelection {
4440 build_scope,
4441 wrapper: selection
4442 .wrapper
4443 .as_ref()
4444 .map(|path| path.display().to_string()),
4445 tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
4446 });
4447 for owner in doc_packages {
4448 let doc = Runner::Doc {
4449 copy: copy.clone(),
4450 target_dir: build_target.clone(),
4451 package: owner.name.clone(),
4452 opt_level: options.opt_level,
4453 flags: options.cargo.flags(),
4454 };
4455 let name = if owner.name == package.name {
4456 "doc tests".to_owned()
4457 } else {
4458 format!("{}::doc tests", owner.name)
4459 };
4460 let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
4461 runners.push((name, doc, cwd));
4462 }
4463 report.analysis.test_selection = selected_tests;
4464 let identity = if checkpoint.is_some() {
4465 let mut build_inputs: Vec<_> = build
4466 .build_scripts
4467 .iter()
4468 .map(serde_json::Value::to_string)
4469 .collect();
4470 build_inputs.sort();
4471 let settings = serde_json::json!({
4474 "build_scripts": build_inputs,
4475 "analysis": &report.analysis, "package": &package.name, "jobs": options.jobs,
4476 "verify": options.verify, "audit": options.audit, "effects": options.effects,
4477 "all_files": options.all_files, "build_scope": build_scope,
4478 "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
4479 });
4480 let mut inputs = BTreeSet::new();
4481 for (root, artifacts) in &build.artifacts {
4482 inputs.insert(root.clone());
4483 if let Some(dependencies) = artifacts
4484 .iter()
4485 .map(|artifact| artifact_inputs(artifact, root, ©))
4486 .find(|deps| !deps.is_empty())
4487 {
4488 inputs.extend(dependencies);
4489 } else {
4490 inputs.extend(artifacts.iter().cloned());
4493 }
4494 }
4495 inputs.extend(
4496 build
4497 .build_scripts
4498 .iter()
4499 .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
4500 );
4501 inputs.retain(|path| !path.starts_with(©));
4504 inputs.extend(
4505 options
4506 .output_fixtures
4507 .iter()
4508 .map(|fixture| build_target.join(&fixture.to)),
4509 );
4510 Some(crate::campaign_identity::compute(
4511 ©,
4512 &settings,
4513 inputs,
4514 options.nextest.is_some(),
4515 )?)
4516 } else {
4517 None
4518 };
4519 let marks = marks_dir(&work)?;
4524 let baseline_jobs = if selection.enabled() {
4525 options.baseline_jobs
4526 } else {
4527 1
4528 };
4529 if options.progress {
4530 eprintln!(
4531 "tmt: baselines: 0/{} completed ({} workers)",
4532 runners.len(),
4533 baseline_jobs
4534 );
4535 }
4536
4537 session.binaries = progress::track_baselines(options.progress, runners.len(), |progress| {
4538 run_pool(runners.len(), baseline_jobs, |slot| {
4539 let index = slot;
4540 let (name, runner, cwd) = runners[index].clone();
4541 let result = (|| {
4542 let trace_path = work.join(format!("trace-{index}.tsv"));
4543 let _ = fs::remove_file(&trace_path);
4544 let mut bin = TestBinary {
4545 name,
4546 cwd,
4547 marks: marks.clone(),
4548 git_ceiling: work.clone(),
4549 work_lock: work_lock.clone(),
4550 tests: BTreeSet::new(),
4551 runner,
4552 baseline: Duration::ZERO,
4553 untraced_baseline: None,
4554 timeout_diagnostic: std::sync::Once::new(),
4555 traced: Duration::ZERO,
4556 timeout: options.timeout_seconds.map(Duration::from_secs),
4557 wrapper_grace: options.wrapper_grace,
4558 report_slow: options.progress,
4559 filtered_timings: Default::default(),
4560 trace: Trace::default(),
4561 effects_baseline: std::sync::OnceLock::new(),
4562 };
4563 session.note(&format!("tracing `{}`", bin.name));
4564 let started = Instant::now();
4565 let trace_env = trace_path.to_string_lossy().into_owned();
4566 let trace = [("TMT_TRACE", trace_env.as_str())];
4567 run_baseline(
4568 &bin,
4569 if options.source_only { &[] } else { &trace },
4570 Duration::from_secs(3600),
4571 &work.join(format!("baseline-{index}.log")),
4572 false,
4573 )?;
4574 bin.traced = started.elapsed();
4575 bin.baseline = bin.traced;
4576 if options.source_only {
4577 bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
4578 }
4579 if !options.source_only && bin.traced > SLOW_TRACE {
4582 let started = Instant::now();
4583 let passed = run_baseline(
4584 &bin,
4585 &[],
4586 bin.traced,
4587 &work.join(format!("baseline-{index}-untraced.log")),
4588 true,
4589 )?;
4590 let elapsed = started.elapsed();
4591 if passed {
4592 bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
4593 bin.baseline = elapsed;
4594 } else {
4595 bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
4596 }
4597 }
4598 let text = match fs::read_to_string(&trace_path) {
4601 Ok(text) => text,
4602 Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
4603 Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
4604 };
4605 bin.trace = Trace::parse(&text);
4606 if bin.trace.malformed_lines > 0 {
4607 bail!(
4608 "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
4609 bin.name,
4610 bin.trace.malformed_lines
4611 );
4612 }
4613 if let Runner::Exe(exe) = &bin.runner {
4614 bin.tests =
4615 list_tests(exe, &bin.cwd, &work, false, false, work_lock.as_deref())?;
4616 }
4617 Ok(bin)
4618 })();
4619 progress.complete(if result.is_ok() {
4620 progress::Outcome::Survived
4621 } else {
4622 progress::Outcome::Failed
4623 });
4624 result
4625 })
4626 })?;
4627
4628 for file in &files {
4630 for site in &file.sites {
4631 if disabled.contains(&site.id) {
4632 let fallback = options.rebuild
4633 && !matches!(site.kind, SiteKind::Body { .. })
4634 && !instrument::source_mutants(site).is_empty();
4635 match site.kind {
4636 SiteKind::Body { .. } => report.unviable_mutants += 1,
4637 _ if fallback => {}
4638 _ => report.skipped_sites += 1,
4639 }
4640 report.skipped.push(report::SkippedSite::new(
4641 report::location(&file.display, site),
4642 file.lines.position(&file.original, site.end),
4643 if fallback {
4644 report::SkipReason::ProbeReplacedBySourceRebuild
4645 } else {
4646 report::SkipReason::ProbeCompileError
4647 },
4648 repairs.get(&site.id).cloned(),
4649 ));
4650 }
4651 }
4652 if !options.rebuild && !options.source_only {
4653 report.skipped.extend(file.rebuild_sites.iter().map(|site| {
4654 report::SkippedSite::new(
4655 report::location(&file.display, site),
4656 file.lines.position(&file.original, site.end),
4657 report::SkipReason::RequiresSourceRebuild,
4658 None,
4659 )
4660 }));
4661 }
4662 }
4663 if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
4664 checkpoint.start(
4665 identity,
4666 serde_json::json!({
4667 "package": &package.name, "analysis": &report.analysis,
4668 "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
4669 "jobs": options.jobs, "tool_version": env!("CARGO_PKG_VERSION")
4670 }),
4671 )?;
4672 }
4673 let phase = |name: &str, keys: Vec<String>| {
4674 checkpoint
4675 .as_ref()
4676 .zip(identity.as_deref())
4677 .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
4678 .transpose()
4679 };
4680 let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
4681 if checkpoint.is_none() {
4682 return Ok(None);
4683 }
4684 let locations: BTreeMap<_, _> = files
4685 .iter()
4686 .flat_map(|file| {
4687 file.sites
4688 .iter()
4689 .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
4690 })
4691 .collect();
4692 let keys = jobs
4693 .iter()
4694 .map(|job| {
4695 let tests = job
4696 .tests
4697 .iter()
4698 .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
4699 .collect::<Vec<_>>();
4700 serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
4701 })
4702 .collect::<std::result::Result<Vec<_>, _>>()?;
4703 phase(name, keys)
4704 };
4705 let scratch = work.clone();
4706 let mut jobs: Vec<Job> = vec![];
4707 let mut not_evaluated: HashSet<u32> = HashSet::new();
4710 let mut work: Vec<SiteWork> = vec![];
4711 let mut effect_jobs: Vec<(usize, usize)> = vec![];
4713 for file in &files {
4714 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
4715 let plan = match session.plan(&file.display, site, options.verify) {
4716 Planned::Unreached => {
4717 let at = report::location(&file.display, site);
4719 if report.unreached.last() != Some(&at) {
4720 report.unreached.push(at);
4721 }
4722 continue;
4723 }
4724 Planned::Nothing => continue,
4725 Planned::NotEvaluated => {
4726 not_evaluated.insert(site.id);
4727 continue;
4728 }
4729 Planned::Plan(plan) => plan,
4730 };
4731 let mut add =
4732 |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
4733 jobs.push(session.job(site.id, mutation, tests_of));
4734 jobs.len() - 1
4735 };
4736 let gaps = plan
4737 .gaps
4738 .into_iter()
4739 .map(
4740 |PlannedGap {
4741 finding,
4742 survivors,
4743 constant_expr,
4744 }| {
4745 let confirm = if options.verify {
4748 survivors
4749 .into_iter()
4750 .map(|m| add(m, &*plan.reaching))
4751 .collect()
4752 } else {
4753 vec![]
4754 };
4755 (finding, confirm, constant_expr)
4756 },
4757 )
4758 .collect();
4759 let infected = &plan.infected;
4760 let runs = plan
4761 .run
4762 .iter()
4763 .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
4764 .collect();
4765 work.push(SiteWork {
4766 file: &file.display,
4767 site,
4768 gaps,
4769 constant: plan.constant,
4770 cannot_differ: plan.cannot_differ,
4771 runs,
4772 });
4773 }
4774 }
4775 session.note(&format!(
4776 "running {} mutants on {} thread(s)",
4777 jobs.len(),
4778 options.jobs.max(1)
4779 ));
4780 let probe_checkpoint = probe_phase("probe", &jobs)?;
4781 let mut results =
4782 session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
4783 for result in &results {
4784 report.timeout_rechecks.include(result);
4785 }
4786
4787 if let Some(wanted) = options.audit {
4790 let survivors: Vec<usize> = (0..jobs.len())
4791 .filter(|job| results[*job].survived.is_some())
4792 .collect();
4793 let chosen: Vec<usize> = spread(survivors.len(), wanted)
4794 .into_iter()
4795 .map(|nth| survivors[nth])
4796 .collect();
4797 session.note(&format!(
4798 "audit: running {} of {} surviving mutants against all tests",
4799 chosen.len(),
4800 survivors.len()
4801 ));
4802 let against_all: Vec<Job> = chosen
4803 .iter()
4804 .map(|job| Job {
4805 site: jobs[*job].site,
4806 mutation: jobs[*job].mutation,
4807 tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
4808 })
4809 .collect();
4810 let mut audit = report::Audit {
4811 sampled: chosen.len(),
4812 survivors: survivors.len(),
4813 ..report::Audit::default()
4814 };
4815 let audit_checkpoint = probe_phase("audit", &against_all)?;
4816 for (job, again) in chosen.iter().zip(session.run_jobs(
4817 &against_all,
4818 options.jobs,
4819 "audit mutants",
4820 audit_checkpoint.as_ref(),
4821 )?) {
4822 report.timeout_rechecks.include(&again);
4823 if again.survived.is_none() {
4824 results[*job] = again;
4826 let site = files
4827 .iter()
4828 .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
4829 if let Some((file, site)) = site {
4830 audit
4831 .disagreements
4832 .push(report::location(&file.display, site));
4833 }
4834 }
4835 }
4836 session.note("audit: recording the tests once more");
4837 for (index, bin) in session.binaries.iter().enumerate() {
4838 let path = scratch.join(format!("trace-{index}-audit.tsv"));
4839 let _ = fs::remove_file(&path);
4840 let trace_env = path.to_string_lossy().into_owned();
4841 let limit = Duration::from_secs(3600);
4842 let outcome = run_binary(
4843 bin,
4844 None,
4845 &[("TMT_TRACE", &trace_env)],
4846 limit,
4847 RunOutput::Quiet,
4848 1,
4849 )?;
4850 let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
4851 let _ = fs::remove_file(&path);
4852 let records = bin.trace.differences(&again);
4853 if outcome != Outcome::Pass || records > 0 {
4854 audit.trace_differences.push(report::TraceDifference {
4855 binary: bin.name.clone(),
4856 records,
4857 });
4858 }
4859 }
4860 report.audit = Some(audit);
4861 }
4862 let unable = results
4863 .iter()
4864 .filter(|r| r.unable || r.unconfirmed_timeout)
4865 .count();
4866 not_evaluated.extend(
4867 jobs.iter()
4868 .zip(&results)
4869 .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
4870 .map(|(job, _)| job.site),
4871 );
4872 if !options.rebuild {
4873 report.mutants_not_evaluated = not_evaluated.len();
4874 }
4875 report.mutants_run = results.len() - unable;
4876 report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
4877 report.mutants_timed_out = results
4878 .iter()
4879 .filter(|r| r.timed_out && !r.unconfirmed_timeout)
4880 .count();
4881
4882 let confirmed = |w: &SiteWork| {
4885 w.gaps
4886 .iter()
4887 .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
4888 };
4889 let constants: BTreeSet<(&str, usize, usize)> = work
4890 .iter()
4891 .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
4892 .map(|w| (w.file, w.site.start, w.site.end))
4893 .collect();
4894 for item in &work {
4895 let at = report::location(item.file, item.site);
4896 for (finding, confirm, constant_expr) in &item.gaps {
4897 let repeats = constant_expr
4900 .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
4901 match Prediction::of(confirm.iter().map(|j| &results[*j])) {
4902 Prediction::Refuted => report.unstable.push(at.clone()),
4903 Prediction::Confirmed if !repeats => report.findings.push(finding.clone()),
4904 Prediction::Confirmed | Prediction::Unknown => {}
4906 }
4907 }
4908 if let SiteKind::Body {
4911 sole_expr: Some((start, end)),
4912 ..
4913 } = item.site.kind
4914 && constants.contains(&(item.file, start, end))
4915 {
4916 continue;
4917 }
4918 let mut survivors = vec![];
4919 let mut passing_tests = BTreeSet::new();
4920 for (mutation, job) in &item.runs {
4921 if let Some(tests) = &results[*job].survived {
4922 survivors.push(report::describe(item.site, *mutation));
4923 passing_tests.extend(tests.iter().cloned());
4924 }
4925 }
4926 if !survivors.is_empty() {
4927 let first = item
4929 .runs
4930 .iter()
4931 .find(|(_, job)| results[*job].survived.is_some());
4932 effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
4933 report.findings.push(Finding::AssertionGap {
4934 at,
4935 survivors,
4936 tests: passing_tests.into_iter().collect(),
4937 effects: vec![],
4938 effects_of: None,
4939 witness: None,
4940 });
4941 }
4942 }
4943
4944 if options.effects && !effect_jobs.is_empty() {
4946 session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
4947 let sites: BTreeMap<u32, (&str, &Site)> = files
4948 .iter()
4949 .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
4950 .collect();
4951 let traced = run_pool(effect_jobs.len(), options.jobs, |index| {
4952 session.trace_job(
4953 &jobs[effect_jobs[index].1],
4954 &scratch,
4955 options.jobs.clamp(1, effect_jobs.len()),
4956 )
4957 })?;
4958 for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
4959 if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
4962 for found in changes.values_mut() {
4963 found.retain(|change| {
4964 sites.get(&change.site()).is_none_or(|(file, site)| {
4965 file != mutated_file
4966 || site.end <= mutated.start
4967 || mutated.end <= site.start
4968 })
4969 });
4970 }
4971 changes.retain(|_, found| !found.is_empty());
4972 }
4973 if let Finding::AssertionGap {
4974 effects,
4975 effects_of,
4976 ..
4977 } = &mut report.findings[*finding]
4978 {
4979 *effects = describe_effects(&changes, &sites);
4980 *effects_of = sites
4981 .get(&jobs[*job].site)
4982 .map(|(_, site)| report::describe(site, jobs[*job].mutation));
4983 }
4984 }
4985 }
4986
4987 let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
4991 let build_regular_mutants = options.rebuild || options.source_only;
4992 let mut index = 0;
4993 for file in &files {
4994 let retried = file.sites.iter().filter(|site| {
4997 (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
4998 || not_evaluated.contains(&site.id)
4999 });
5000 for site in file.rebuild_sites.iter().chain(retried) {
5001 let mutants = source_mutants(file, site, options.source_only);
5002 if build_regular_mutants {
5003 built.extend(mutants.into_iter().filter_map(|mutant| {
5004 let selected = in_shard(index);
5005 index += 1;
5006 selected.then_some((file, site, mutant, None))
5007 }));
5008 } else {
5009 report.mutants_not_built += mutants.len();
5010 }
5011 }
5012 }
5013 if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
5016 let mut twins = vec![];
5017 for file in &files {
5018 for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
5019 let integers = session.binaries.iter().all(|bin| {
5021 let seen = bin.trace.merged(site.id);
5022 !seen.reached() || seen.valued()
5023 });
5024 let candidates = jobs_for_site(&jobs, site.id);
5025 let job_of = |mutation: Mutation| {
5026 candidates
5027 .clone()
5028 .find(|&index| jobs[index].mutation == mutation)
5029 };
5030 let mut compared = vec![];
5031 for mutant in instrument::source_mutants(site) {
5032 let job = mutations_like(site, &mutant, integers)
5034 .into_iter()
5035 .find_map(job_of);
5036 if let Some(job) = job {
5037 compared.push(job);
5038 twins.push((file, site, mutant, Some(job)));
5039 }
5040 }
5041 if let (SiteKind::Cmp { op, .. }, Some(job)) =
5044 (&site.kind, job_of(Mutation::Negate))
5045 && !compared.contains(&job)
5046 {
5047 let negated = instrument::SourceMutant {
5048 start: site.start,
5049 end: site.end,
5050 replacement: format!("!({})", site.text),
5051 what: op.symbol().to_string(),
5052 into: "!".to_string(),
5053 };
5054 twins.push((file, site, negated, Some(job)));
5055 }
5056 }
5057 }
5058 let chosen = spread(twins.len(), wanted);
5059 audit.rebuilt = chosen.len();
5060 let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
5061 built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
5062 }
5063 let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
5064 by_speed.sort_by_key(|bin| bin.baseline);
5065 let root_mutant_suffix = if files.iter().any(|file| {
5067 file.path != root_file
5068 && file
5069 .rendered
5070 .as_ref()
5071 .is_some_and(|rendered| rendered.text != file.original)
5072 }) {
5073 root_suffix.as_str()
5074 } else {
5075 ""
5076 };
5077 if !built.is_empty() {
5078 if options.timeout_seconds.is_some()
5079 && built
5080 .iter()
5081 .any(|(file, _, _, _)| built_sources.contains(file))
5082 {
5083 for bin in &by_speed {
5084 bin.warn_timeout_conflict(None);
5085 }
5086 }
5087 let source_checkpoint = if checkpoint.is_some() {
5088 let keys = built
5089 .iter()
5090 .map(|(file, _, mutation, twin)| {
5091 serde_json::to_string(&(
5092 &file.display,
5093 mutation.start,
5094 mutation.end,
5095 &mutation.replacement,
5096 twin,
5097 ))
5098 })
5099 .collect::<std::result::Result<Vec<_>, _>>()?;
5100 phase("source", keys)?
5101 } else {
5102 None
5103 };
5104 session.note(&format!(
5105 "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
5106 built.len()
5107 ));
5108 let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
5109 if file.path == root_file {
5110 format!("{text}{suffix}")
5111 } else {
5112 text.to_string()
5113 }
5114 };
5115 let mut skipped_targets = BTreeSet::new();
5118 let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
5119 progress::track(
5120 options.progress,
5121 "source mutants",
5122 built.len(),
5123 |progress| -> Result<()> {
5124 for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
5125 let cached = source_checkpoint
5126 .as_ref()
5127 .map(|phase| phase.get::<Option<Outcome>>(index))
5128 .transpose()?
5129 .flatten();
5130 if !built_sources.contains(file) {
5131 if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
5132 {
5133 phase.record(index, &Some(Outcome::Unable))?;
5134 }
5135 if twin.is_none() {
5136 report.mutants_not_evaluated += 1;
5137 if skipped_targets.insert((&file.path, site.start, site.end)) {
5138 report.skipped.push(report::SkippedSite::new(
5139 report::location(&file.display, site),
5140 file.lines.position(&file.original, site.end),
5141 report::SkipReason::SourceNotBuilt,
5142 None,
5143 ));
5144 }
5145 } else if let Some(audit) = report.audit.as_mut() {
5146 audit.not_compared += 1;
5147 }
5148 progress.complete(progress::Outcome::Unable);
5149 continue;
5150 }
5151 let outcome = if let Some(cached) = cached {
5152 cached
5153 } else {
5154 let mutated = format!(
5155 "{}{}{}",
5156 &file.original[..mutant.start],
5157 mutant.replacement,
5158 &file.original[mutant.end..]
5159 );
5160 let attempt = || -> Result<Option<Outcome>> {
5162 state.write(
5163 &file.path,
5164 &instrumented(file, &mutated, root_mutant_suffix),
5165 )?;
5166 match source_build(&cargo_build()?) {
5167 SourceBuild::Built => run_source_tests(&by_speed).map(Some),
5168 SourceBuild::Refused => Ok(None),
5169 SourceBuild::Failed(why) => {
5172 session.note(&format!(
5173 "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
5174 ));
5175 Ok(Some(Outcome::Unable))
5176 }
5177 }
5178 };
5179 let attempted = attempt();
5180 let rendered = file.rendered.as_ref().expect("rendered before building");
5182 state.write(
5183 &file.path,
5184 &instrumented(file, &rendered.text, &root_suffix),
5185 )?;
5186 let outcome = attempted?;
5187 if let Some(phase) = &source_checkpoint
5190 && outcome != Some(Outcome::Unable)
5191 {
5192 phase.record(index, &outcome)?;
5193 }
5194 outcome
5195 };
5196 progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
5197 if let Some(job) = twin {
5198 let as_probe = results[*job].survived.is_some();
5200 let Some(audit) = report.audit.as_mut() else {
5201 continue;
5202 };
5203 let comparable = outcome.filter(|_| !results[*job].unable);
5205 match comparable {
5206 Some(_) => audit.compared += 1,
5207 None => audit.not_compared += 1,
5208 }
5209 if comparable.is_some_and(|built| (built == Outcome::Pass) != as_probe) {
5210 let verdict = |passes: bool| if passes { "passes" } else { "fails" };
5211 audit.source_disagreements.push(report::SourceDisagreement {
5212 at: report::location(&file.display, site),
5213 mutant: report::describe(site, mutation_of(site, mutant)),
5214 as_probe: verdict(as_probe).to_string(),
5215 built: verdict(!as_probe).to_string(),
5216 });
5217 }
5218 continue;
5219 }
5220 match outcome {
5221 None => report.unviable_mutants += 1,
5222 Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
5223 Some(outcome) => {
5224 report.mutants_run += 1;
5225 report.mutants_killed += (outcome != Outcome::Pass) as usize;
5226 report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
5227 }
5228 }
5229 let survived = outcome == Some(Outcome::Pass);
5230 if survived {
5231 let at = report::location(&file.display, site);
5232 let text = match (&site.kind, mutant.replacement.is_empty()) {
5233 (SiteKind::Field { .. }, true) => {
5234 format!("without the field `{}`", report::one_line(&site.text))
5235 }
5236 _ => report::describe(site, mutation_of(site, mutant)),
5237 };
5238 match survivors.last_mut() {
5239 Some((last, texts)) if *last == at => texts.push(text),
5240 _ => survivors.push((at, vec![text])),
5241 }
5242 }
5243 }
5244 Ok(())
5245 },
5246 )?;
5247 if let Some(phase) = &source_checkpoint {
5248 phase.finish()?;
5249 }
5250 report.findings.extend(
5251 survivors
5252 .into_iter()
5253 .map(|(at, survivors)| Finding::Survivor {
5254 at,
5255 survivors,
5256 witness: None,
5257 }),
5258 );
5259 }
5260
5261 if !witness_candidates.is_empty() {
5262 let file = files
5263 .iter()
5264 .find(|file| file.path == root_file)
5265 .expect("witness candidates in the root file");
5266 let rendered = file.rendered.as_ref().expect("rendered before building");
5267 let restore = format!("{}{root_suffix}", rendered.text);
5268 let library_runners: Vec<_> = session
5269 .binaries
5270 .iter()
5271 .filter(|bin| {
5272 root_exe
5273 .as_deref()
5274 .is_some_and(|exe| bin.runner.executable() == Some(exe))
5275 })
5276 .collect();
5277 let ignored = library_runners
5278 .iter()
5279 .find_map(|bin| match &bin.runner {
5280 Runner::Exe(exe) => Some(list_tests(
5281 exe,
5282 &bin.cwd,
5283 &bin.git_ceiling,
5284 true,
5285 false,
5286 bin.work_lock.as_deref(),
5287 )),
5288 _ => None,
5289 })
5290 .transpose()?
5291 .unwrap_or_default();
5292 let runner_for = |scenario: &witness::Scenario| {
5293 library_runners.iter().copied().find(|bin| {
5294 scenario
5295 .source_test
5296 .as_ref()
5297 .is_none_or(|required| match &bin.runner {
5298 Runner::Exe(_) => {
5299 bin.tests.contains(required) && !ignored.contains(required)
5300 }
5301 Runner::Isolated { test, .. } => test == required,
5302 Runner::Doc { .. } | Runner::Nextest { .. } => false,
5303 })
5304 })
5305 };
5306 let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
5307 let Some(source) = witness::render_edits(&file.original, edits, None) else {
5308 return Ok(false);
5309 };
5310 state.write(&root_file, &format!("{source}{root_mutant_suffix}"))?;
5311 Ok(true)
5312 };
5313 let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
5314 if !write_edits(edits)? || !cargo_build()?.status.success() {
5315 return Ok(None);
5316 }
5317 run_source_tests(&by_speed).map(Some)
5318 };
5319 let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
5320 if !write_edits(edits)? {
5321 return Ok(None);
5322 }
5323 let build = build_test_binaries(true)?;
5324 if !build.status.success() {
5325 return Ok(None);
5326 }
5327 let artifacts = parse_build_output(
5328 &String::from_utf8_lossy(&build.stdout),
5329 &[package.name.as_str()],
5330 );
5331 Ok(root_test_exe(&artifacts))
5332 };
5333 let observe = |scenario: &witness::Scenario,
5334 baseline: &TestBinary,
5335 edits: &[witness::Edit],
5336 expected: Option<&str>|
5337 -> Result<Option<witness::Observation>> {
5338 let test = scenario.test_edit(&file.original, witness::TEST_NAME, expected);
5339 let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
5340 let Some(exe) = compile_observer(&edits)? else {
5341 return Ok(None);
5342 };
5343 observe_witness(
5344 baseline,
5345 exe,
5346 wrapper.as_deref(),
5347 scenario,
5348 witness::TEST_NAME,
5349 expected.is_some(),
5350 )
5351 };
5352 let witness_checkpoint = if checkpoint.is_some() {
5353 let keys = witness_candidates
5354 .iter()
5355 .map(|candidate| {
5356 let edits = candidate
5357 .edits
5358 .iter()
5359 .map(|edit| (&edit.span, &edit.replacement))
5360 .collect::<Vec<_>>();
5361 serde_json::to_string(&(&candidate.description, edits))
5362 })
5363 .collect::<std::result::Result<Vec<_>, _>>()?;
5364 phase("witness", keys)?
5365 } else {
5366 None
5367 };
5368 let mut survivors = vec![];
5369 progress::track(
5370 options.progress,
5371 "source witness mutants",
5372 witness_candidates.len(),
5373 |progress| -> Result<()> {
5374 for (index, candidate) in witness_candidates.iter().enumerate() {
5375 let cached = witness_checkpoint
5376 .as_ref()
5377 .map(|phase| phase.get::<WitnessTrial>(index))
5378 .transpose()?
5379 .flatten();
5380 let at = witness_location(file, candidate);
5381 let existing = candidate
5382 .existing
5383 .then(|| {
5384 report.findings.iter().position(|finding| {
5385 let location = finding.at();
5386 location.file == at.file
5387 && location.line == at.line
5388 && location.column == at.column
5389 && finding.survivors().contains(&candidate.description)
5390 })
5391 })
5392 .flatten();
5393 let scenarios: Vec<_> = candidate
5394 .scenarios
5395 .iter()
5396 .filter_map(|scenario| {
5397 runner_for(scenario).map(|runner| (scenario, runner))
5398 })
5399 .take(4)
5400 .collect();
5401 let paired = candidate.edits.len() > 1;
5402 if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
5403 || (paired && scenarios.is_empty())
5404 {
5405 if let Some(phase) =
5406 witness_checkpoint.as_ref().filter(|_| cached.is_none())
5407 {
5408 phase.record(index, &WitnessTrial::Inapplicable)?;
5409 }
5410 progress.complete(progress::Outcome::Unable);
5411 continue;
5412 }
5413 let trial = if let Some(cached) = cached {
5416 cached
5417 } else {
5418 let attempted = (|| -> Result<WitnessTrial> {
5419 if paired {
5420 for edit in &candidate.edits {
5421 if suite(std::slice::from_ref(edit))? != Some(Outcome::Fail) {
5422 return Ok(WitnessTrial::Inapplicable);
5423 }
5424 }
5425 }
5426 Ok(suite(&candidate.edits)?
5427 .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
5428 })();
5429 state.write(&root_file, &restore)?;
5430 let trial = attempted?;
5431 if let Some(phase) = &witness_checkpoint {
5432 phase.record(index, &trial)?;
5433 }
5434 trial
5435 };
5436 let outcome = match trial {
5437 WitnessTrial::Inapplicable => {
5438 progress.complete(progress::Outcome::Unable);
5439 continue;
5440 }
5441 WitnessTrial::Unviable => {
5442 progress.complete(progress::Outcome::Unable);
5443 report.unviable_mutants += usize::from(!candidate.existing);
5444 continue;
5445 }
5446 WitnessTrial::Evaluated(outcome) => outcome,
5447 };
5448 progress.complete(outcome.into());
5449 if !candidate.existing {
5450 report.mutants_run += 1;
5451 report.mutants_killed += usize::from(outcome != Outcome::Pass);
5452 report.mutants_timed_out += usize::from(outcome == Outcome::Timeout);
5453 }
5454 if outcome == Outcome::Pass {
5455 survivors.push(WitnessSurvivor {
5456 candidate,
5457 at,
5458 existing,
5459 scenarios,
5460 });
5461 }
5462 }
5463 Ok(())
5464 },
5465 )?;
5466
5467 if let Some(phase) = &witness_checkpoint {
5468 phase.finish()?;
5469 }
5470 let originals = shared_witnesses(
5471 &file.original,
5472 &survivors,
5473 wrapper.as_deref(),
5474 compile_observer,
5475 note,
5476 );
5477 if !survivors.is_empty() {
5478 state.write(&root_file, &restore)?;
5479 }
5480 let originals = originals?;
5481
5482 progress::track(
5483 options.progress,
5484 "distinguishing tests",
5485 survivors.len(),
5486 |progress| -> Result<()> {
5487 for (survivor, original) in survivors.into_iter().zip(originals) {
5488 let mut evidence = None;
5489 let mut original = original;
5490 for (scenario, baseline) in survivor.scenarios {
5491 let shared = original.take();
5492 let distinction = (|| -> Result<_> {
5493 if let Some(shared) = shared {
5494 let edits: Vec<_> = survivor
5496 .candidate
5497 .edits
5498 .iter()
5499 .chain(shared.tests.iter())
5500 .cloned()
5501 .collect();
5502 if let Some(exe) = compile_observer(&edits)?
5503 && let Some(mutant) = observe_witness(
5504 baseline,
5505 exe,
5506 wrapper.as_deref(),
5507 scenario,
5508 &shared.name,
5509 true,
5510 )
5511 .ok()
5512 .flatten()
5513 && mutant.equals_expected == Some(false)
5514 && let Some(verified) =
5515 scenario.verified(shared.value, mutant.value)
5516 {
5517 return Ok(Some(verified));
5518 }
5519 }
5522 let Some(original) = observe(scenario, baseline, &[], None)? else {
5523 return Ok(None);
5524 };
5525 let value = original.value;
5526 if !witness::is_expected_literal(&value) {
5527 return Ok(None);
5528 }
5529 let Some(mutant) = observe(
5530 scenario,
5531 baseline,
5532 &survivor.candidate.edits,
5533 Some(&value),
5534 )?
5535 else {
5536 return Ok(None);
5537 };
5538 if mutant.equals_expected != Some(false) || value == mutant.value {
5539 return Ok(None);
5540 }
5541 let Some(checked) = observe(scenario, baseline, &[], Some(&value))?
5542 else {
5543 return Ok(None);
5544 };
5545 if checked.equals_expected != Some(true) || checked.value != value {
5546 return Ok(None);
5547 }
5548 Ok(scenario.verified(value, mutant.value))
5549 })();
5550 match distinction {
5551 Ok(Some(mut verified)) => {
5552 let edits = survivor.candidate.edits.len();
5553 verified.individually_killed = (edits > 1).then_some(edits);
5554 evidence = Some(verified);
5555 break;
5556 }
5557 Ok(None) => {}
5558 Err(err) => note(&format!(
5559 "could not check a distinguishing test for {}: {err:#}",
5560 scenario.expression,
5561 )),
5562 }
5563 }
5564 state.write(&root_file, &restore)?;
5565 progress.complete(Outcome::Pass.into());
5566 if let Some(index) = survivor.existing {
5567 if let Some(evidence) = evidence {
5568 report.findings[index].set_witness(evidence);
5569 }
5570 } else {
5571 report.findings.push(Finding::Survivor {
5572 at: survivor.at,
5573 survivors: vec![survivor.candidate.description.clone()],
5574 witness: evidence,
5575 });
5576 }
5577 }
5578 Ok(())
5579 },
5580 )?;
5581 }
5582
5583 report.record_evaluation();
5584 report.sort_findings();
5585 let places: Vec<FilePlaces> = files
5586 .iter()
5587 .map(|file| FilePlaces {
5588 display: &file.display,
5589 source: &file.original,
5590 lines: &file.lines,
5591 places: &file.places,
5592 })
5593 .collect();
5594 name_findings(&mut report.findings, &places);
5595
5596 let files_with_findings: BTreeSet<&str> = report
5598 .findings
5599 .iter()
5600 .map(|finding| finding.at().file.as_str())
5601 .collect();
5602 let ignored: BTreeMap<&str, BTreeMap<usize, String>> = files
5603 .iter()
5604 .filter(|file| files_with_findings.contains(file.display.as_str()))
5605 .map(|f| {
5606 (
5607 f.display.as_str(),
5608 crate::baseline::ignored_lines(&f.original),
5609 )
5610 })
5611 .collect();
5612 let known = match &options.baseline {
5613 Some(path) => Some(crate::baseline::load(path)?),
5614 None => None,
5615 };
5616 let before = report.findings.len();
5617 report.findings.retain(|finding| {
5618 let at = finding.at();
5619 !ignored
5620 .get(at.file.as_str())
5621 .is_some_and(|lines| lines.contains_key(&at.line))
5622 });
5623 if let Some(path) = &options.write_baseline {
5624 crate::baseline::write(path, &report.findings)?;
5625 }
5626 report
5627 .findings
5628 .retain(|finding| !known.as_ref().is_some_and(|known| known.knows(finding)));
5629 report.suppressed = before - report.findings.len();
5630 if let Some(checkpoint) = &checkpoint {
5631 checkpoint.finish()?;
5632 }
5633 Ok(report)
5634}
5635
5636fn repository_prefix(dir: &Path) -> String {
5640 let shown = Command::new("git")
5641 .arg("-C")
5642 .arg(dir)
5643 .args(["rev-parse", "--show-prefix"])
5644 .stderr(Stdio::null())
5645 .output();
5646 match shown {
5647 Ok(output) if output.status.success() => {
5648 String::from_utf8_lossy(&output.stdout).trim().to_string()
5649 }
5650 _ => String::new(),
5651 }
5652}
5653
5654fn spread(count: usize, wanted: usize) -> Vec<usize> {
5657 let wanted = wanted.min(count);
5658 (0..wanted).map(|nth| nth * count / wanted).collect()
5659}
5660
5661struct FilePlaces<'a> {
5663 display: &'a str,
5664 source: &'a str,
5665 lines: &'a scope::LineIndex,
5666 places: &'a [(usize, usize, String)],
5668}
5669
5670fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
5675 let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
5676 for finding in findings {
5677 by_file
5678 .entry(finding.at().file.clone())
5679 .or_default()
5680 .push(finding);
5681 }
5682 for file in files {
5683 let Some(findings) = by_file.remove(file.display) else {
5684 continue;
5685 };
5686 let items = instrument::named_items(file.source);
5687 let index = instrument::ItemIndex::new(&items);
5688 let item_at = |line, column| {
5689 file.lines
5690 .offset_of(file.source, line, column)
5691 .map_or("", |offset| index.at(offset))
5692 };
5693 let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
5694 for (line, column, code) in file.places {
5695 positions
5696 .entry((item_at(*line, *column), code))
5697 .or_default()
5698 .push((*line, *column));
5699 }
5700 for places in positions.values_mut() {
5701 places.sort_unstable();
5702 places.dedup();
5703 }
5704 for finding in findings {
5705 let kind = finding.kind();
5706 let at = finding.at_mut();
5707 let item = item_at(at.line, at.column);
5708 let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
5709 places.partition_point(|&place| place < (at.line, at.column))
5710 });
5711 at.item = item.to_string();
5712 at.id = report::finding_id(kind, at, nth);
5713 }
5714 }
5715}
5716
5717fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
5719 match &site.kind {
5720 SiteKind::Cmp { .. } => plan::CmpOp::ALL
5721 .into_iter()
5722 .find(|op| op.symbol() == mutant.into)
5723 .map_or(Mutation::Negate, Mutation::Op),
5724 SiteKind::Arith { op, .. } => {
5725 if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
5726 Mutation::ArithSwap
5727 } else {
5728 Mutation::ArithSwap2
5729 }
5730 }
5731 SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
5732 SiteKind::Logic { .. } => Mutation::LogicSwap,
5733 SiteKind::Not { .. } => Mutation::DropNot,
5734 SiteKind::Range { .. } => Mutation::RangeEnd,
5735 _ => Mutation::Delete,
5738 }
5739}
5740
5741fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
5750 let mut all = vec![mutation_of(site, mutant)];
5751 if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
5752 let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
5753 if into == op.negated() && (integers || !an_order_is_needed) {
5754 all.push(Mutation::Negate);
5755 }
5756 match (op, into) {
5757 (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
5758 all.push(Mutation::Shift(1))
5759 }
5760 (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
5761 all.push(Mutation::Shift(-1))
5762 }
5763 _ => {}
5764 }
5765 }
5766 all
5767}
5768
5769fn describe_effects(
5772 changes: &BTreeMap<String, BTreeSet<Change>>,
5773 sites: &BTreeMap<u32, (&str, &Site)>,
5774) -> Vec<String> {
5775 let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
5776 for (test, found) in changes {
5777 for change in found {
5778 by_change.entry(change).or_default().push(test);
5779 }
5780 }
5781 if by_change.is_empty() {
5782 return vec![
5783 "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(),
5784 ];
5785 }
5786 let mut out = vec![];
5787 for (change, tests) in by_change.iter().take(3) {
5788 let Some((file, site)) = sites.get(&change.site()) else {
5789 continue;
5790 };
5791 let code = report::location(file, site).code;
5792 let at = format!("{file}:{}", site.line);
5793 let who = match tests[..] {
5794 ["?"] => "a test".to_string(),
5795 [one] => format!("`{one}`"),
5796 [first, ..] => format!("`{first}` (and {} more)", tests.len() - 1),
5797 [] => continue,
5798 };
5799 out.push(match change {
5800 Change::Returns { value, .. } => {
5801 format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
5802 }
5803 Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
5804 Change::NoLongerRuns { .. } => {
5805 format!("with the mutant, {who} no longer runs `{code}` ({at})")
5806 }
5807 Change::NewOutcome { .. } => {
5808 format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
5809 }
5810 });
5811 }
5812 if by_change.len() > 3 {
5813 out.push(format!("(and {} more such changes)", by_change.len() - 3));
5814 }
5815 out
5816}
5817
5818#[cfg(test)]
5819mod tests {
5820 use super::*;
5821 use crate::trace::UNKNOWN_TEST;
5822
5823 #[test]
5824 fn explicit_timeout_conflict_matches_the_coverage_table() {
5825 for row in include_str!("../tests/data/timeout-baseline.pict.tsv")
5826 .lines()
5827 .skip(1)
5828 {
5829 let columns: Vec<_> = row.split('\t').collect();
5830 let &[limit, baseline, selection] = columns.as_slice() else {
5831 panic!("invalid PICT row: {row}");
5832 };
5833 let timeout = (limit == "explicit").then_some(Duration::from_secs(1));
5834 let measured = Duration::from_millis(match baseline {
5835 "below" => 999,
5836 "equal" => 1_000,
5837 "above" => 1_001,
5838 _ => panic!("invalid baseline: {baseline}"),
5839 });
5840 let selected_count = match selection {
5841 "full" => None,
5842 "all-names" => Some(2),
5843 "filtered" => Some(1),
5844 _ => panic!("invalid selection: {selection}"),
5845 };
5846 let expected = limit == "explicit" && baseline != "below" && selection != "filtered";
5847 assert_eq!(
5848 explicit_timeout_conflict(timeout, measured, selected_count, 2).is_some(),
5849 expected,
5850 "{row}"
5851 );
5852 }
5853 }
5854
5855 #[test]
5856 fn campaign_phase_combinations() {
5857 let rows = include_str!("../tests/data/campaign-phases.pict.tsv");
5858 for line in rows.lines().skip(1) {
5859 let columns: Vec<_> = line.split('\t').collect();
5860 let &[baselines, workers, policy, verdict] = columns.as_slice() else {
5861 panic!("invalid PICT row: {line}");
5862 };
5863 let count = |value| if value == "one" { 1 } else { 2 };
5864 let ready = std::sync::Barrier::new(count(baselines));
5865 let baselines = run_pool(2, count(baselines), |index| {
5866 ready.wait();
5867 Ok(index)
5868 })
5869 .unwrap();
5870 assert_eq!(baselines, [0, 1]);
5871
5872 let serial = policy == "serial";
5873 let workers = count(workers);
5874 let results = evaluate_jobs(
5875 2,
5876 workers,
5877 serial,
5878 false,
5879 "test",
5880 None,
5881 &|index, sharing| {
5882 let time_out =
5883 index == 0 && verdict != "pass" && (sharing > 1 || verdict == "timeout");
5884 let unable = index == 0 && verdict == "unable" && sharing == 1;
5885 Ok(JobResult {
5886 first_pass_timeout: false,
5887 unconfirmed_timeout: false,
5888 survived: (!time_out && !unable).then(|| vec![index.to_string()]),
5889 timed_out: time_out,
5890 unable,
5891 })
5892 },
5893 )
5894 .unwrap();
5895 assert_eq!(results[1].survived.as_deref(), Some(&["1".to_owned()][..]));
5896 let mut stats = report::TimeoutRechecks::default();
5897 stats.include(&results[0]);
5898 let first_pass = usize::from(workers == 2 && verdict != "pass");
5899 assert_eq!(stats.first_pass, first_pass, "{line}");
5900 assert_eq!(
5901 stats.confirmed,
5902 usize::from(first_pass == 1 && serial && verdict == "timeout"),
5903 "{line}"
5904 );
5905 assert_eq!(
5906 stats.recovered,
5907 usize::from(first_pass == 1 && serial && verdict == "recovered"),
5908 "{line}"
5909 );
5910 assert_eq!(
5911 stats.unconfirmed,
5912 usize::from(first_pass == 1 && (!serial || verdict == "unable")),
5913 "{line}"
5914 );
5915 }
5916 }
5917
5918 #[cfg(unix)]
5919 #[test]
5920 fn mutant_timeout_uses_the_measured_filter_and_an_explicit_override_wins() {
5921 use std::os::unix::fs::PermissionsExt;
5922 let dir = scratch("filtered-timeout");
5923 let exe = dir.join("runner");
5924 fs::write(
5925 &exe,
5926 "#!/bin/sh\n[ \"$2\" = --exact ] && [ \"$3\" = fast ]\n",
5927 )
5928 .unwrap();
5929 fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
5930 let mut bin = TestBinary {
5931 name: "tests".into(),
5932 cwd: dir.clone(),
5933 marks: marks_dir(&dir).unwrap(),
5934 git_ceiling: dir.clone(),
5935 work_lock: None,
5936 tests: ["fast".to_string(), "slow".to_string()]
5937 .into_iter()
5938 .collect(),
5939 runner: Runner::Exe(exe),
5940 baseline: Duration::from_secs(70),
5941 untraced_baseline: None,
5942 timeout_diagnostic: std::sync::Once::new(),
5943 traced: Duration::from_secs(70),
5944 timeout: None,
5945 wrapper_grace: Duration::ZERO,
5946 report_slow: false,
5947 filtered_timings: Default::default(),
5948 trace: Trace::default(),
5949 effects_baseline: std::sync::OnceLock::new(),
5950 };
5951 assert!(bin.filtered_limit(Some(&["fast".to_string()]), false) < Duration::from_secs(355));
5954 assert_eq!(
5955 bin.filtered_limit(Some(&["slow".to_string()]), false),
5956 Duration::from_secs(355)
5957 );
5958 assert_eq!(bin.filtered_limit(None, false), Duration::from_secs(355));
5959 assert_eq!(bin.filtered_timings.lock().unwrap().len(), 2);
5960 bin.timeout = Some(Duration::from_secs(8));
5961 assert_eq!(
5962 bin.filtered_limit(Some(&["fast".to_string()]), false),
5963 Duration::from_secs(8)
5964 );
5965 fs::remove_dir_all(dir).unwrap();
5966 }
5967
5968 #[test]
5969 fn failed_build_retains_spanless_and_source_diagnostics() {
5970 let stdout = r#"
5971{"reason":"compiler-message","message":{"level":"error","message":"linking with cc failed","rendered":"ld: library not found for -liconv","spans":[]}}
5972{"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}]}}
5973"#;
5974 let failed = parse_build_output(stdout, &["p"]);
5975 assert_eq!(failed.errors.len(), 1);
5976 let text = failed.diagnostics.join("\n");
5977 assert!(text.contains("ld: library not found for -liconv"), "{text}");
5978 assert!(text.contains("source error"), "{text}");
5979 }
5980
5981 #[test]
5982 fn test_build_scope_uses_only_known_local_features() {
5983 let package = Package {
5984 name: "pkg".to_owned(),
5985 dependencies: vec![],
5986 features: BTreeMap::from([
5987 ("default".to_owned(), vec!["alias".to_owned()]),
5988 (
5989 "alias".to_owned(),
5990 vec!["extra".to_owned(), "dep/extra".to_owned()],
5991 ),
5992 ("extra".to_owned(), vec![]),
5993 ("separate".to_owned(), vec![]),
5994 ]),
5995 manifest_path: PathBuf::from("workspace/pkg/Cargo.toml"),
5996 targets: vec![],
5997 };
5998 let enabled = |workspace: &str, features: &str, no_default_features, all_features| {
5999 package.enabled_local_features(
6000 Path::new(workspace),
6001 &CargoConfig {
6002 features: vec![features.to_owned()],
6003 no_default_features,
6004 all_features,
6005 locked: false,
6006 },
6007 )
6008 };
6009 let root = "workspace/pkg";
6010 assert_eq!(
6011 enabled(root, "", false, false),
6012 BTreeSet::from(["default", "alias", "extra"])
6013 );
6014 assert_eq!(
6015 enabled(root, "", true, true),
6016 BTreeSet::from(["default", "alias", "extra", "separate"])
6017 );
6018 assert_eq!(
6019 enabled(root, "alias, separate", true, false),
6020 BTreeSet::from(["alias", "extra", "separate"])
6021 );
6022 assert_eq!(
6023 enabled("workspace", "extra other/separate", true, false),
6024 BTreeSet::new()
6025 );
6026 assert_eq!(
6027 enabled("workspace", "pkg/extra other/separate", true, false),
6028 BTreeSet::from(["extra"])
6029 );
6030 }
6031
6032 #[test]
6033 fn test_build_scope_preserves_cargo_target_eligibility() {
6034 let target = |name, kind, test, required_features: &[&str]| {
6035 serde_json::from_value(serde_json::json!({
6036 "name": name, "kind": [kind], "test": test, "src_path": "ignored.rs",
6037 "required-features": required_features,
6038 }))
6039 .unwrap()
6040 };
6041 let package = |name: &str, targets| Package {
6042 name: name.to_owned(),
6043 dependencies: vec![],
6044 targets,
6045 manifest_path: PathBuf::new(),
6046 features: BTreeMap::from([("extra".to_owned(), vec![])]),
6047 };
6048 let first = package(
6049 "first",
6050 vec![
6051 target("first", "proc-macro", true, &[]),
6052 target("name", "bin", true, &[]),
6053 target("name", "example", true, &[]),
6054 target("name", "bench", true, &[]),
6055 target("name", "test", true, &[]),
6056 target("conditional", "test", true, &["extra"]),
6057 target("dependency_feature", "test", true, &["dep/extra"]),
6058 target("disabled", "test", false, &[]),
6059 target("glob[a]", "test", true, &[]),
6060 target("--leading-dash", "test", true, &[]),
6061 target("build-script-build", "custom-build", false, &[]),
6062 ],
6063 );
6064 let second = package(
6065 "second",
6066 vec![
6067 target("second", "staticlib", true, &[]),
6068 target("name", "test", false, &[]),
6069 ],
6070 );
6071 let flags = |packages: &[&Package], names: &[&str], all| {
6072 test_build_flags(
6073 packages,
6074 &names.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
6075 Path::new("workspace"),
6076 &CargoConfig {
6077 all_features: all,
6078 ..CargoConfig::default()
6079 },
6080 )
6081 };
6082 assert_eq!(
6083 flags(&[&first], &["name", "first", "unknown"], false).unwrap(),
6084 [
6085 "--bench=name",
6086 "--bin=name",
6087 "--example=name",
6088 "--lib",
6089 "--test=name"
6090 ]
6091 );
6092 assert_eq!(flags(&[&first], &[], false), None);
6093 assert_eq!(flags(&[&first], &["unknown", "disabled"], false), None);
6094 assert_eq!(flags(&[&first], &["glob[a]"], false), None);
6095 assert_eq!(
6096 flags(&[&first], &["--leading-dash"], false).unwrap(),
6097 ["--test=--leading-dash"]
6098 );
6099 assert_eq!(flags(&[&first], &["name", "conditional"], false), None);
6100 assert_eq!(flags(&[&first], &["dependency_feature"], true), None);
6101 assert_eq!(
6102 flags(&[&first], &["conditional"], true).unwrap(),
6103 ["--test=conditional"]
6104 );
6105 assert_eq!(flags(&[&first, &second], &["name"], false), None);
6106 assert_eq!(flags(&[&first, &second], &["first"], false), None);
6107 assert_eq!(
6108 flags(&[&first, &second], &["first", "second"], false).unwrap(),
6109 ["--lib"]
6110 );
6111 }
6112
6113 #[test]
6114 fn parses_cargo_json_messages() {
6115 let stdout = concat!(
6116 r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":false},"executable":null}"#,
6117 "\n",
6118 r#"{"reason":"compiler-artifact","package_id":"p 0.1.0","target":{"name":"p","kind":["lib"]},"profile":{"test":true},"executable":"/t/p-abc"}"#,
6119 "\n",
6120 r#"{"reason":"compiler-artifact","package_id":"dep 1.0.0","target":{"name":"dep","kind":["lib"]},"profile":{"test":true},"executable":"/t/dep-abc"}"#,
6121 "\n",
6122 r#"{"reason":"compiler-message","message":{"level":"warning","rendered":"w","spans":[{"file_name":"src/lib.rs","byte_start":1,"line_start":1,"is_primary":true}]}}"#,
6123 "\n",
6124 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}]}}"#,
6125 "\n",
6126 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}]}}"#,
6127 "\n",
6128 r#"{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}"#,
6129 "\n",
6130 "not json\n",
6131 r#"{"reason":"build-finished","success":false}"#,
6132 "\n",
6133 );
6134 let out = parse_build_output(stdout, &["p", "other"]);
6135 assert_eq!(
6136 out.test_binaries,
6137 [(
6138 "p".to_string(),
6139 PathBuf::from("/t/p-abc"),
6140 "p".to_string(),
6141 vec!["lib".to_string()]
6142 )]
6143 );
6144 let both = parse_build_output(stdout, &["dep", "p"]);
6146 let owners: Vec<&str> = both.test_binaries.iter().map(|b| b.2.as_str()).collect();
6147 assert_eq!(owners, ["dep", "p"]);
6148 assert_eq!(
6149 out.errors,
6150 [CompileError {
6151 primary: vec![ErrorSpan {
6152 file: "src/lib.rs".into(),
6153 byte_start: 40,
6154 line: 3
6155 }],
6156 secondary: vec![ErrorSpan {
6157 file: "src/lib.rs".into(),
6158 byte_start: 2,
6159 line: 1
6160 }],
6161 rendered: "E0308".into(),
6162 }]
6163 );
6164 }
6165
6166 #[test]
6167 fn package_ids_are_matched_by_name() {
6168 assert!(is_package(
6169 "path+file:///w/target/tmt/src#eligibility@0.0.0",
6170 "eligibility"
6171 ));
6172 assert!(is_package(
6173 "path+file:///w/eligibility#0.1.0",
6174 "eligibility"
6175 ));
6176 assert!(is_package(
6177 "eligibility 0.1.0 (path+file:///w)",
6178 "eligibility"
6179 ));
6180 assert!(!is_package(
6181 "path+file:///w/eligibility#other@0.1.0",
6182 "eligibility-core"
6183 ));
6184 assert!(!is_package(
6185 "registry+https://github.com/rust-lang/crates.io-index#serde@1.0.0",
6186 "eligibility"
6187 ));
6188 }
6189
6190 #[test]
6191 fn test_filter_falls_back_to_the_whole_binary() {
6192 let set = |names: &[&str]| {
6193 names
6194 .iter()
6195 .map(|n| n.to_string())
6196 .collect::<BTreeSet<String>>()
6197 };
6198 let known = set(&["tests::a", "tests::b", "tests::c"]);
6199 assert_eq!(
6200 test_filter(&set(&["tests::a", "tests::b"]), &known),
6201 Some(vec!["tests::a".to_string(), "tests::b".to_string()])
6202 );
6203 assert_eq!(test_filter(&set(&["tests::a", UNKNOWN_TEST]), &known), None);
6205 assert_eq!(test_filter(&set(&["tests::a", "worker"]), &known), None);
6207 assert_eq!(test_filter(&set(&["worker"]), &known), None);
6208
6209 let many: BTreeSet<String> = (0..=MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
6210 assert_eq!(test_filter(&many, &many), None);
6211 let limit: BTreeSet<String> = (0..MAX_TEST_FILTERS).map(|i| format!("t{i}")).collect();
6212 assert!(test_filter(&limit, &limit).is_some());
6213 }
6214
6215 #[test]
6216 fn libtest_listing() {
6217 let listing =
6218 "tests::a: test\ntests::nested::b: test\nbench_it: benchmark\n\n2 tests, 1 benchmark\n";
6219 assert_eq!(
6220 parse_test_list(listing).into_iter().collect::<Vec<_>>(),
6221 ["tests::a", "tests::nested::b"]
6222 );
6223 }
6224
6225 #[test]
6226 fn domains_from_type_bounds() {
6227 let u8s = crate::trace::TypeBounds {
6228 lhs: (0, 255),
6229 rhs: (0, 255),
6230 };
6231 assert_eq!(
6232 domain_of(LiteralSide::Rhs(18), Some(&u8s)),
6233 Some((-18, 237))
6234 );
6235 assert_eq!(
6236 domain_of(LiteralSide::Lhs(18), Some(&u8s)),
6237 Some((-237, 18))
6238 );
6239 assert_eq!(domain_of(LiteralSide::None, Some(&u8s)), None);
6240 assert_eq!(domain_of(LiteralSide::Rhs(18), None), None);
6241 let wide = crate::trace::TypeBounds {
6242 lhs: (i128::MIN, 0),
6243 rhs: (0, 0),
6244 };
6245 assert_eq!(
6246 domain_of(LiteralSide::Rhs(1), Some(&wide)),
6247 None,
6248 "overflow is not a domain"
6249 );
6250 }
6251
6252 #[test]
6253 fn a_primary_blame_does_not_inspect_later_fallbacks() {
6254 let copy = Path::new("/work");
6255 let source = "pub fn f(n: u32) -> bool { n >= 4 }";
6256 let make = |name: &str, rendered: bool| {
6257 let sites = instrument::discover(source, 0).unwrap().sites;
6258 let output = rendered.then(|| instrument::render(source, &sites, &|_| true));
6259 SourceFile {
6260 display: name.to_string(),
6261 path: copy.join(name),
6262 owners: BTreeSet::new(),
6263 lines: scope::LineIndex::new(source),
6264 original: source.to_string(),
6265 places: vec![],
6266 sites,
6267 rebuild_sites: vec![],
6268 rendered: output,
6269 }
6270 };
6271 let files = [make("primary.rs", true), make("secondary.rs", false)];
6272 let rendered = files[0].rendered.as_ref().unwrap();
6273 let probe = rendered.text.find("__tmt_rt::").unwrap();
6274 let span = |file: &str, byte_start| ErrorSpan {
6275 file: file.to_string(),
6276 byte_start,
6277 line: 1,
6278 };
6279 let error = CompileError {
6280 primary: vec![span("primary.rs", probe)],
6281 secondary: vec![span("secondary.rs", 0)],
6282 rendered: String::new(),
6283 };
6284 assert_eq!(
6285 blame_error(&error, &files, copy, &HashSet::new()),
6286 [rendered.inserted_by(probe).unwrap()]
6287 );
6288 }
6289
6290 #[test]
6291 fn repair_reuses_a_render_but_still_corrects_the_working_copy() {
6292 let dir = scratch("render-repair");
6293 let root = dir.join("work/src");
6294 let path = root.join("f.rs");
6295 let state = WorkCopy::open(&dir.join("work"), &root);
6296 let source = "pub fn f(n: u32) -> bool { n >= 4 }";
6297 let suffix = "\n// root suffix\n";
6298 for row in include_str!("../tests/data/repair-reuse.pict.tsv")
6299 .lines()
6300 .skip(1)
6301 {
6302 let columns: Vec<_> = row.split('\t').collect();
6303 let [cache, which, disk] = columns.as_slice() else {
6304 panic!("{row}")
6305 };
6306 let sites = instrument::discover(source, 1).unwrap().sites;
6307 let id = sites
6308 .iter()
6309 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
6310 .unwrap()
6311 .id;
6312 let disabled = match *which {
6313 "here" => HashSet::from([id]),
6314 "elsewhere" => HashSet::from([u32::MAX]),
6315 _ => HashSet::new(),
6316 };
6317 let before = instrument::render(source, &sites, &|_| true);
6318 let expected = instrument::render(source, &sites, &|id| !disabled.contains(&id));
6319 let original_text = format!("{}{suffix}", before.text);
6320 fs::write(
6321 &path,
6322 if *disk == "rendered" {
6323 &original_text
6324 } else {
6325 source
6326 },
6327 )
6328 .unwrap();
6329 let mut file = SourceFile {
6330 display: "f.rs".to_string(),
6331 path: path.clone(),
6332 owners: BTreeSet::new(),
6333 lines: scope::LineIndex::new(source),
6334 original: source.to_string(),
6335 places: vec![],
6336 sites,
6337 rebuild_sites: vec![],
6338 rendered: (*cache == "present").then_some(before),
6339 };
6340 write_rendered(&mut file, &state, suffix, &disabled, &disabled).unwrap();
6341 assert_eq!(
6342 fs::read_to_string(&path).unwrap(),
6343 format!("{}{suffix}", expected.text),
6344 "{row}"
6345 );
6346 let rendered = file.rendered.unwrap();
6347 assert_eq!(rendered.text, expected.text, "{row}");
6348 for offset in 0..rendered.text.len() {
6349 assert_eq!(
6350 rendered.to_original(offset),
6351 expected.to_original(offset),
6352 "{row}"
6353 );
6354 assert_eq!(
6355 rendered.inserted_by(offset),
6356 expected.inserted_by(offset),
6357 "{row}"
6358 );
6359 }
6360 }
6361 fs::remove_dir_all(dir).unwrap();
6362 }
6363
6364 #[test]
6365 fn source_graph_shares_edges_without_sharing_resolution_or_ownership() {
6366 let scratch = scratch("shared-source-graph");
6367 let copy = scratch.join("work/src");
6368 let before = copy.join("before.rs");
6369 let library = copy.join("lib.rs");
6370 let after = copy.join("after.rs");
6371 let shared = copy.join("shared.rs");
6372 let leaf = copy.join("leaf.rs");
6373 let test_helper = copy.join("test_helper.rs");
6374 let nested_leaf = copy.join("shared/leaf.rs");
6375 let sources = BTreeMap::from([
6376 (before.clone(), r#"#[path = "shared.rs"] mod dep;"#),
6377 (
6378 library.clone(),
6379 r#"mod shared; #[path = "shared.rs"] mod dep;"#,
6380 ),
6381 (after.clone(), r#"include!("shared.rs");"#),
6382 (shared.clone(), "mod leaf; #[cfg(test)] mod test_helper;"),
6383 (leaf.clone(), "fn top() {}"),
6384 (test_helper.clone(), "fn testing() {}"),
6385 (nested_leaf.clone(), "fn nested() {}"),
6386 ]);
6387 for path in sources.keys() {
6388 fs::create_dir_all(path.parent().unwrap()).unwrap();
6389 fs::File::create(path).unwrap();
6390 }
6391 let mut reads = BTreeMap::new();
6392 let graph = source_graph(
6393 [
6394 (before.clone(), false),
6395 (library.clone(), true),
6396 (after.clone(), false),
6397 ],
6398 ©,
6399 |path| {
6400 *reads.entry(path.to_path_buf()).or_insert(0) += 1;
6401 Ok(sources.get(path).map(|source| (*source).to_string()))
6402 },
6403 )
6404 .unwrap();
6405 fs::remove_dir_all(scratch).unwrap();
6406
6407 assert_eq!(
6408 reads[&shared], 2,
6409 "one load in each of two resolution contexts"
6410 );
6411 assert_eq!(reads[&leaf], 1);
6412 assert_eq!(reads[&test_helper], 1);
6413 assert!(!graph.contains_key(&test_helper));
6414 assert_eq!(reads[&nested_leaf], 1);
6415 for path in [&leaf, &shared] {
6416 assert_eq!(
6417 graph[path].consumers,
6418 BTreeSet::from([before.clone(), library.clone(), after.clone()])
6419 );
6420 assert_eq!(graph[path].production, BTreeSet::from([library.clone()]));
6421 }
6422 assert_eq!(
6423 graph[&nested_leaf].consumers,
6424 BTreeSet::from([library.clone()])
6425 );
6426 assert_eq!(graph[&nested_leaf].production, BTreeSet::from([library]));
6427 assert!(!graph.contains_key(&before) && !graph.contains_key(&after));
6428 }
6429
6430 #[test]
6431 fn out_of_line_module_locations() {
6432 let file = Path::new("src/cli.rs");
6433 let statements = "mod child; #[path = \"spec/support.rs\"] mod helper;";
6434 let roots = crate::modules::external(statements, file, Path::new("src"));
6435 assert_eq!(
6436 roots[0].paths,
6437 [
6438 PathBuf::from("src/child.rs"),
6439 PathBuf::from("src/child/mod.rs")
6440 ]
6441 );
6442 assert_eq!(roots[1].paths, [PathBuf::from("src/spec/support.rs")]);
6443 let module = crate::modules::external(statements, file, Path::new("src/cli"));
6444 assert_eq!(module[0].paths[0], PathBuf::from("src/cli/child.rs"));
6445 assert_eq!(module[1].paths[0], PathBuf::from("src/spec/support.rs"));
6446 }
6447
6448 #[test]
6449 fn path_dependencies_outside_the_workspace_become_absolute() {
6450 let manifest = r#"[package]
6451name = "app"
6452
6453[dependencies]
6454serde = "1"
6455core = { path = "../core" } # inside the workspace: kept
6456outside = { path = "../../outside", version = "1" }
6457
6458[dev-dependencies.helper]
6459path = "../../../far/helper"
6460
6461[target.'cfg(unix)'.dependencies]
6462unix-only = { path = "../../unix" }
6463
6464[patch.crates-io]
6465serde = { path = "../../serde-fork" }
6466"#;
6467 let out = absolutize_path_dependencies(
6468 manifest,
6469 Path::new("/w/ws/app"),
6470 Path::new("/w/ws"),
6471 Path::new("/copy"),
6472 )
6473 .unwrap()
6474 .expect("something to rewrite");
6475 assert!(
6476 out.contains(r#"core = { path = "../core" } # inside the workspace: kept"#),
6477 "{out}"
6478 );
6479 assert!(
6480 out.contains(r#"outside = { path = "/w/outside", version = "1" }"#),
6481 "{out}"
6482 );
6483 assert!(out.contains("path = \"/far/helper\""), "{out}");
6484 assert!(out.contains(r#"unix-only = { path = "/w/unix" }"#), "{out}");
6485 assert!(
6486 out.contains(r#"serde = { path = "/w/serde-fork" }"#),
6487 "{out}"
6488 );
6489 assert!(out.contains("serde = \"1\""), "{out}");
6490
6491 let inside = "[dependencies]\ncore = { path = \"../core\" }\n[workspace.dependencies]\nx = { path = \"x\" }\n";
6492 assert_eq!(
6493 absolutize_path_dependencies(
6494 inside,
6495 Path::new("/w/ws/app"),
6496 Path::new("/w/ws"),
6497 Path::new("/copy")
6498 )
6499 .unwrap(),
6500 None
6501 );
6502 let ws = "[workspace.dependencies]\nshared = { path = \"../shared\" }\n";
6503 let out = absolutize_path_dependencies(
6504 ws,
6505 Path::new("/w/ws"),
6506 Path::new("/w/ws"),
6507 Path::new("/copy"),
6508 )
6509 .unwrap()
6510 .unwrap();
6511 assert!(out.contains(r#"shared = { path = "/w/shared" }"#), "{out}");
6512 assert!(
6513 absolutize_path_dependencies(
6514 "not [ toml",
6515 Path::new("/w"),
6516 Path::new("/w"),
6517 Path::new("/copy")
6518 )
6519 .is_err()
6520 );
6521 assert_eq!(normalize(Path::new("/a/./b/../c")), PathBuf::from("/a/c"));
6522 let absolute = "[dependencies]\nhelper = { path = \"/w/ws/helper\" }\n";
6524 let out = absolutize_path_dependencies(
6525 absolute,
6526 Path::new("/w/ws/app"),
6527 Path::new("/w/ws"),
6528 Path::new("/copy"),
6529 )
6530 .unwrap()
6531 .unwrap();
6532 assert!(
6533 out.contains(r#"helper = { path = "/copy/helper" }"#),
6534 "{out}"
6535 );
6536 }
6537
6538 #[test]
6539 fn pool_runs_every_job_once_and_keeps_the_order() {
6540 use std::sync::atomic::{AtomicUsize, Ordering};
6541 for workers in [0, 1, 2, 3, 8, 100] {
6542 for count in [0, 1, 2, 7, 50] {
6543 let calls: Vec<AtomicUsize> = (0..count).map(|_| AtomicUsize::new(0)).collect();
6544 let results = run_pool(count, workers, |i| {
6545 calls[i].fetch_add(1, Ordering::SeqCst);
6546 std::thread::yield_now();
6547 Ok(i * 10)
6548 })
6549 .unwrap();
6550 assert_eq!(
6551 results,
6552 (0..count).map(|i| i * 10).collect::<Vec<_>>(),
6553 "workers={workers}"
6554 );
6555 assert!(
6556 calls.iter().all(|c| c.load(Ordering::SeqCst) == 1),
6557 "workers={workers} count={count}"
6558 );
6559 }
6560 }
6561 let failed = run_pool(5, 3, |i| {
6562 if i == 3 {
6563 Err(anyhow!("job {i} broke"))
6564 } else {
6565 Ok(i)
6566 }
6567 });
6568 assert_eq!(failed.unwrap_err().to_string(), "job 3 broke");
6569 }
6570
6571 #[test]
6572 fn operand_ranges_ignore_wrapping_parentheses() {
6573 assert_eq!(core_range(10, "a > 0"), (10, 15));
6574 assert_eq!(core_range(10, "(a > 0)"), (11, 16));
6575 assert_eq!(core_range(10, " ( (a > 0) ) "), (14, 19));
6576 assert_eq!(core_range(0, "(a) && (b)"), (0, 10));
6578 assert_eq!(core_range(0, "f(a)"), (0, 4));
6579 assert_eq!(core_range(3, "()"), (4, 4));
6580 assert_eq!(core_range(0, "(a"), (0, 2));
6582 assert_eq!(core_range(0, "a)"), (0, 2));
6583 assert_eq!(core_range(0, ")"), (0, 1));
6584 }
6585
6586 #[test]
6587 fn pool_never_uses_more_threads_than_asked() {
6588 for workers in [1, 2] {
6589 let seen = std::sync::Mutex::new(HashSet::new());
6590 run_pool(6, workers, |_| {
6591 seen.lock().unwrap().insert(std::thread::current().id());
6592 std::thread::sleep(Duration::from_millis(30));
6594 Ok(())
6595 })
6596 .unwrap();
6597 assert_eq!(seen.lock().unwrap().len(), workers);
6598 }
6599 }
6600
6601 #[test]
6602 fn workspace_dependents() {
6603 let package = |name: &str, deps: &[&str]| Package {
6604 name: name.to_string(),
6605 features: BTreeMap::new(),
6606 dependencies: deps
6607 .iter()
6608 .map(|d| Dependency {
6609 name: d.to_string(),
6610 })
6611 .collect(),
6612 manifest_path: PathBuf::new(),
6613 targets: vec![],
6614 };
6615 let packages = [
6616 package("core", &["serde"]),
6617 package("mid", &["core"]),
6618 package("app", &["mid", "other"]),
6619 package("other", &[]),
6620 package("cycle", &["app", "core"]),
6621 ];
6622 assert_eq!(dependents_of("core", &packages), ["app", "cycle", "mid"]);
6623 assert_eq!(dependents_of("mid", &packages), ["app", "cycle"]);
6624 assert_eq!(dependents_of("other", &packages), ["app", "cycle"]);
6625 assert!(dependents_of("app", &packages) == ["cycle"]);
6626 assert!(dependents_of("nobody", &packages).is_empty());
6627 let mutual = [package("x", &["y"]), package("y", &["x"])];
6629 assert_eq!(dependents_of("x", &mutual), ["y"]);
6630 }
6631
6632 #[test]
6633 fn failure_lines_of_libtest() {
6634 assert!(is_failure_line("test tests::a ... FAILED"));
6635 assert!(is_failure_line(
6636 "test src/lib.rs - double (line 3) ... FAILED"
6637 ));
6638 assert!(!is_failure_line("test tests::a ... ok"));
6639 assert!(!is_failure_line("test result: FAILED. 1 passed; 1 failed"));
6640 assert!(!is_failure_line("my output says ... FAILED"));
6641 assert!(!is_failure_line(
6642 "test tests::a ... FAILED (but printed by the test)"
6643 ));
6644 }
6645
6646 #[test]
6647 fn effects_in_words() {
6648 let source = "fn f(s: &mut S) -> bool { s.reset(); s.count > 1 }";
6649 let mut found = instrument::discover(source, 0).unwrap().sites;
6650 found.retain(|s| !matches!(s.kind, SiteKind::Body { .. }));
6651 for (id, site) in found.iter_mut().enumerate() {
6652 site.id = id as u32;
6653 }
6654 let sites: BTreeMap<u32, (&str, &Site)> =
6655 found.iter().map(|s| (s.id, ("src/lib.rs", s))).collect();
6656 let texts: Vec<&str> = found.iter().map(|s| s.text.as_str()).collect();
6657 assert_eq!(
6658 texts,
6659 ["fn f(s: &mut S) -> bool", "s.reset();", "s.count > 1"]
6660 );
6661
6662 let set = |list: &[Change]| list.iter().cloned().collect::<BTreeSet<Change>>();
6663 let mut changes = BTreeMap::new();
6664 changes.insert(
6665 "tests::a".to_string(),
6666 set(&[
6667 Change::Returns {
6668 site: 0,
6669 value: true,
6670 },
6671 Change::NowRuns { site: 1 },
6672 ]),
6673 );
6674 changes.insert(
6675 "tests::b".to_string(),
6676 set(&[Change::NowRuns { site: 1 }, Change::NewOutcome { site: 2 }]),
6677 );
6678 changes.insert("?".to_string(), set(&[Change::NoLongerRuns { site: 2 }]));
6679 assert_eq!(
6680 describe_effects(&changes, &sites),
6681 [
6682 "with the mutant, `tests::a` gets `true` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
6683 "with the mutant, `tests::a` (and 1 more) now runs `s.reset();` (src/lib.rs:1)",
6684 "with the mutant, a test no longer runs `s.count > 1` (src/lib.rs:1)",
6685 "(and 1 more such changes)",
6686 ]
6687 );
6688 let mut many = BTreeMap::new();
6690 many.insert(
6691 "tests::a".to_string(),
6692 set(&[
6693 Change::NowRuns { site: 0 },
6694 Change::NowRuns { site: 1 },
6695 Change::NowRuns { site: 2 },
6696 Change::NoLongerRuns { site: 0 },
6697 Change::NoLongerRuns { site: 1 },
6698 Change::NoLongerRuns { site: 2 },
6699 ]),
6700 );
6701 assert_eq!(
6702 describe_effects(&many, &sites).last().map(String::as_str),
6703 Some("(and 3 more such changes)")
6704 );
6705 let mut few = BTreeMap::new();
6707 few.insert(
6708 "tests::a".to_string(),
6709 set(&[
6710 Change::NowRuns { site: 1 },
6711 Change::NewOutcome { site: 2 },
6712 Change::Returns {
6713 site: 0,
6714 value: false,
6715 },
6716 ]),
6717 );
6718 assert_eq!(
6719 describe_effects(&few, &sites),
6720 [
6721 "with the mutant, `tests::a` gets `false` from `fn f(s: &mut S) -> bool` (src/lib.rs:1)",
6722 "with the mutant, `tests::a` now runs `s.reset();` (src/lib.rs:1)",
6723 "with the mutant, `tests::a` takes `s.count > 1` (src/lib.rs:1) a way it did not before",
6724 ]
6725 );
6726 assert_eq!(
6727 describe_effects(&BTreeMap::new(), &sites),
6728 [
6729 "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"
6730 ]
6731 );
6732 }
6733
6734 #[test]
6735 fn mutant_timeout_scales_with_the_baseline() {
6736 assert_eq!(mutant_timeout(Duration::ZERO), Duration::from_secs(5));
6737 assert_eq!(
6738 mutant_timeout(Duration::from_secs(2)),
6739 Duration::from_secs(15)
6740 );
6741 }
6742
6743 #[cfg(unix)]
6744 #[test]
6745 fn stopping_nextest_reaps_a_runner_that_ignores_termination() {
6746 use std::io::Read as _;
6747 use std::os::unix::process::CommandExt as _;
6748
6749 let mut child = Command::new("sh")
6750 .args([
6752 "-c",
6753 "trap '' TERM; printf X; n=0; while [ $n -lt 60 ]; do sleep 1; n=$((n+1)); done",
6754 ])
6755 .process_group(0)
6756 .stdout(Stdio::piped())
6757 .spawn()
6758 .unwrap();
6759 child.stdout.take().unwrap().read_exact(&mut [0]).unwrap();
6760
6761 stop_nextest(&mut child, Duration::from_millis(10));
6762 let status = child.try_wait().unwrap().expect("runner was reaped");
6763 assert!(!status.success());
6764 }
6765
6766 #[test]
6767 fn nextest_counts_only_a_test_failure_as_a_kill() {
6768 assert_eq!(nextest_outcome(Some(0)).unwrap(), Outcome::Pass);
6769 assert_eq!(nextest_outcome(Some(100)).unwrap(), Outcome::Fail);
6770 for code in [Some(4), Some(101), Some(102), Some(105), None] {
6771 assert!(nextest_outcome(code).is_err(), "{code:?}");
6772 }
6773 }
6774
6775 #[test]
6776 fn test_polling_backs_off_and_respects_the_remaining_time() {
6777 let mut delay = TEST_POLL_INITIAL;
6778 for micros in [250, 500, 1_000, 2_000, 4_000, 5_000, 5_000] {
6779 assert_eq!(
6780 next_test_poll(&mut delay, Duration::from_secs(1)),
6781 Duration::from_micros(micros)
6782 );
6783 }
6784 let remaining = Duration::from_micros(120);
6785 assert_eq!(next_test_poll(&mut delay, remaining), remaining);
6786 assert_eq!(next_test_poll(&mut delay, Duration::ZERO), Duration::ZERO);
6787 assert_eq!(delay, Duration::from_millis(5));
6788 }
6789 fn scratch(name: &str) -> PathBuf {
6791 let dir = std::env::temp_dir().join(format!("tmt-{name}-{}", std::process::id()));
6792 let _ = fs::remove_dir_all(&dir);
6793 fs::create_dir_all(dir.join("ws/src")).unwrap();
6794 fs::create_dir_all(dir.join("work/src")).unwrap();
6795 dir.canonicalize().unwrap()
6796 }
6797
6798 #[cfg(unix)]
6799 #[test]
6800 fn a_descendant_cannot_keep_the_completed_runner_output_open() {
6801 use std::os::unix::fs::PermissionsExt as _;
6802
6803 let dir = scratch("descendant-output");
6804 let work = dir.join("work");
6805 let exe = work.join("runner");
6806 fs::write(&exe, "#!/bin/sh\nsleep 8 &\nexit 0\n").unwrap();
6807 fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
6808 let bin = TestBinary {
6809 name: "runner".into(),
6810 cwd: work.join("src"),
6811 marks: marks_dir(&work).unwrap(),
6812 git_ceiling: work,
6813 work_lock: None,
6814 tests: BTreeSet::new(),
6815 runner: Runner::Exe(exe),
6816 baseline: Duration::ZERO,
6817 untraced_baseline: None,
6818 timeout_diagnostic: std::sync::Once::new(),
6819 traced: Duration::ZERO,
6820 timeout: None,
6821 wrapper_grace: Duration::ZERO,
6822 report_slow: false,
6823 filtered_timings: Default::default(),
6824 trace: Trace::default(),
6825 effects_baseline: std::sync::OnceLock::new(),
6826 };
6827 let started = Instant::now();
6828 assert_eq!(
6829 run_binary(
6830 &bin,
6831 None,
6832 &[],
6833 Duration::from_secs(2),
6834 RunOutput::FirstFailure,
6835 1
6836 )
6837 .unwrap(),
6838 Outcome::Pass
6839 );
6840 assert!(
6841 started.elapsed() < Duration::from_secs(6),
6842 "a descendant held the output pipe open"
6843 );
6844 fs::remove_dir_all(dir).unwrap();
6845 }
6846
6847 #[cfg(unix)]
6848 #[test]
6849 fn a_detached_descendant_does_not_hold_the_runner_open() {
6850 let dir = scratch("detached-output");
6851 let work = dir.join("work");
6852 let source = work.join("runner.rs");
6853 let exe = work.join("runner");
6854 fs::write(
6855 &source,
6856 r#"
6857use std::os::unix::process::CommandExt;
6858fn main() {
6859 let child = std::process::Command::new("sleep").arg("8").process_group(0).spawn().unwrap();
6860 std::fs::write("child.pid", child.id().to_string()).unwrap();
6861}
6862"#,
6863 )
6864 .unwrap();
6865 let output = Command::new("rustc")
6866 .arg(&source)
6867 .arg("-o")
6868 .arg(&exe)
6869 .output()
6870 .unwrap();
6871 assert!(
6872 output.status.success(),
6873 "{}",
6874 String::from_utf8_lossy(&output.stderr)
6875 );
6876 let bin = TestBinary {
6877 name: "runner".into(),
6878 cwd: work.join("src"),
6879 marks: marks_dir(&work).unwrap(),
6880 git_ceiling: work,
6881 work_lock: None,
6882 tests: BTreeSet::new(),
6883 runner: Runner::Exe(exe),
6884 baseline: Duration::ZERO,
6885 untraced_baseline: None,
6886 timeout_diagnostic: std::sync::Once::new(),
6887 traced: Duration::ZERO,
6888 timeout: None,
6889 wrapper_grace: Duration::ZERO,
6890 report_slow: false,
6891 filtered_timings: Default::default(),
6892 trace: Trace::default(),
6893 effects_baseline: std::sync::OnceLock::new(),
6894 };
6895 let started = Instant::now();
6896 let outcome = run_binary(
6897 &bin,
6898 None,
6899 &[],
6900 Duration::from_secs(2),
6901 RunOutput::FirstFailure,
6902 1,
6903 );
6904 let elapsed = started.elapsed();
6905 let pid = fs::read_to_string(bin.cwd.join("child.pid"))
6907 .unwrap()
6908 .parse()
6909 .unwrap();
6910 kill_test_group(pid);
6911 fs::remove_dir_all(dir).unwrap();
6912 assert_eq!(outcome.unwrap(), Outcome::Pass);
6913 assert!(
6914 elapsed < Duration::from_secs(6),
6915 "a detached descendant held the output pipe open"
6916 );
6917 }
6918
6919 fn set_modified(path: &Path, time: std::time::SystemTime) {
6920 fs::File::options()
6921 .write(true)
6922 .open(path)
6923 .unwrap()
6924 .set_modified(time)
6925 .unwrap();
6926 }
6927
6928 fn modified(path: &Path) -> std::time::SystemTime {
6929 fs::metadata(path).unwrap().modified().unwrap()
6930 }
6931
6932 fn copy_run(dir: &Path, selected: &[&str], write: bool) -> WorkCopy {
6935 let (workspace, work) = (dir.join("ws"), dir.join("work"));
6936 let copy = work.join("src");
6937 let state = WorkCopy::open(&work, ©);
6938 copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
6939 prune(©, &state).unwrap();
6940 for name in selected {
6941 let path = copy.join(name);
6942 let original = state.original(&path, &workspace).unwrap().unwrap();
6943 assert_eq!(original, fs::read_to_string(workspace.join(name)).unwrap());
6944 if write {
6945 state
6946 .write(&path, &format!("instrumented {original}"))
6947 .unwrap();
6948 } else {
6949 state.record(&path).unwrap(); }
6951 }
6952 if write {
6953 state.settle(&workspace).unwrap();
6954 }
6955 state
6956 }
6957
6958 #[test]
6960 fn work_copy_table() {
6961 let table = include_str!("../tests/data/workcopy.pict.tsv");
6962 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
6963 let mut rows = 0;
6964 for (index, line) in table.lines().skip(1).enumerate() {
6965 let [earlier, source, selected] = line.split('\t').collect::<Vec<_>>()[..] else {
6966 panic!("bad row: {line}");
6967 };
6968 let dir = scratch(&format!("copy-table-{index}"));
6969 let (file, copied) = (dir.join("ws/src/a.rs"), dir.join("work/src/src/a.rs"));
6970 let log = dir.join("work").join(WRITTEN_LOG);
6971 fs::write(&file, "v1").unwrap();
6972 set_modified(&file, hour_ago);
6973 match earlier {
6974 "none" => {}
6975 "plain" => drop(copy_run(&dir, &[], true)),
6976 "written" => drop(copy_run(&dir, &["src/a.rs"], true)),
6977 "logged_only" => drop(copy_run(&dir, &["src/a.rs"], false)),
6978 _ => panic!("{line}"),
6979 }
6980 if copied.exists() {
6981 set_modified(&copied, hour_ago);
6982 }
6983 let before = fs::read_to_string(&copied).ok();
6984 match source {
6985 "same" => {}
6986 "edited" => fs::write(&file, "version 2").unwrap(),
6987 "deleted" => fs::remove_file(&file).unwrap(),
6988 _ => panic!("{line}"),
6989 }
6990 let selected = selected == "yes";
6991 copy_run(&dir, if selected { &["src/a.rs"] } else { &[] }, true);
6992
6993 let wanted = match (source, selected) {
6994 ("deleted", _) => None,
6995 ("same", true) => Some("instrumented v1".to_string()),
6996 ("same", false) => Some("v1".to_string()),
6997 (_, true) => Some("instrumented version 2".to_string()),
6998 (_, false) => Some("version 2".to_string()),
6999 };
7000 assert_eq!(fs::read_to_string(&copied).ok(), wanted, "{line}");
7001 assert_eq!(
7002 fs::read_to_string(&log).unwrap_or_default(),
7003 if selected { "src/a.rs\n" } else { "" },
7004 "{line}"
7005 );
7006 if before == wanted && wanted.is_some() && earlier != "logged_only" {
7009 assert_eq!(modified(&copied), hour_ago, "{line}");
7010 }
7011 if before != wanted && wanted.is_some() {
7014 assert!(
7015 modified(&copied) > hour_ago + Duration::from_secs(1800),
7016 "{line}"
7017 );
7018 }
7019 copy_run(&dir, &[], true);
7021 assert_eq!(
7022 fs::read_to_string(&copied).ok(),
7023 fs::read_to_string(&file).ok(),
7024 "{line}"
7025 );
7026 assert_eq!(fs::read_to_string(&log).unwrap(), "", "{line}");
7027 fs::remove_dir_all(&dir).unwrap();
7028 rows += 1;
7029 }
7030 assert_eq!(rows, 20);
7031 }
7032
7033 #[test]
7034 fn streaming_copy_comparison_matches_bytes() {
7035 use std::io::{self, Read};
7036
7037 struct Chunks<'a> {
7038 rest: &'a [u8],
7039 chunk: usize,
7040 interrupt: bool,
7041 fail: bool,
7042 }
7043
7044 impl Read for Chunks<'_> {
7045 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
7046 if self.interrupt {
7047 self.interrupt = false;
7048 return Err(io::ErrorKind::Interrupted.into());
7049 }
7050 if self.fail {
7051 self.fail = false;
7052 return Err(io::ErrorKind::PermissionDenied.into());
7053 }
7054 let limit = out.len().min(self.chunk);
7055 self.rest.read(&mut out[..limit])
7056 }
7057 }
7058
7059 for row in include_str!("../tests/data/workcopy-compare.pict.tsv")
7060 .lines()
7061 .skip(1)
7062 {
7063 let fields: Vec<_> = row.split('\t').collect();
7064 let [size, relation, reads] = fields.as_slice() else {
7065 panic!("{row}")
7066 };
7067 let size = match *size {
7068 "empty" => 0,
7069 "before" => 65535,
7070 "boundary" => 65536,
7071 "after" => 65537,
7072 "multi" => 131079,
7073 _ => panic!("{row}"),
7074 };
7075 let left: Vec<_> = (0..size).map(|i| (i % 251) as u8).collect();
7076 let mut right = left.clone();
7077 match *relation {
7078 "equal" => (),
7079 "early" => right[0] ^= 1,
7080 "late" => right[size - 1] ^= 1,
7081 "suffix" => right.push(1),
7082 "shorter" => {
7083 right.pop();
7084 }
7085 _ => panic!("{row}"),
7086 }
7087 let make_reader = |first, rest, fail_first| Chunks {
7088 rest,
7089 chunk: if *reads == "regular" {
7090 usize::MAX
7091 } else if first {
7092 1031
7093 } else {
7094 2063
7095 },
7096 interrupt: *reads == "interrupted",
7097 fail: first == fail_first && *reads == "failed",
7098 };
7099 for (a, b, fail_first) in [
7100 (&left[..], &right[..], true),
7101 (&right[..], &left[..], false),
7102 ] {
7103 let compared = compare_streams(
7104 make_reader(true, a, fail_first),
7105 make_reader(false, b, fail_first),
7106 );
7107 if *reads == "failed" {
7108 assert_eq!(
7109 compared.unwrap_err().kind(),
7110 io::ErrorKind::PermissionDenied,
7111 "{row}"
7112 );
7113 } else {
7114 assert_eq!(compared.unwrap(), a == b, "{row}");
7115 }
7116 }
7117 }
7118 }
7119
7120 #[test]
7121 fn work_copy_keeps_modification_times() {
7122 let dir = scratch("copy-times");
7123 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
7124 let names = ["src/lib.rs", "src/plain.rs", "src/edited.rs"];
7125 for name in names {
7126 fs::write(dir.join("ws").join(name), format!("// {name}")).unwrap();
7127 set_modified(&dir.join("ws").join(name), hour_ago);
7128 }
7129 let copy = dir.join("work/src");
7130 let runtime = copy.join("src/__tmt_rt.rs");
7131 let run = || {
7132 let state = copy_run(&dir, &[], false);
7133 for name in ["src/lib.rs", "src/edited.rs"] {
7134 let original = state.original(©.join(name), &dir.join("ws")).unwrap();
7135 state
7136 .write(©.join(name), &format!("probe {}", original.unwrap()))
7137 .unwrap();
7138 }
7139 assert_eq!(state.original(&runtime, &dir.join("ws")).ok(), {
7141 if runtime.exists() { Some(None) } else { None }
7142 });
7143 state.write(&runtime, "runtime").unwrap();
7144 state.settle(&dir.join("ws")).unwrap();
7145 };
7146 run();
7147 for name in names.iter().map(|n| copy.join(n)).chain([runtime.clone()]) {
7148 set_modified(&name, hour_ago);
7149 }
7150 fs::write(dir.join("ws/src/edited.rs"), "// edited since").unwrap();
7151 run();
7152 for name in ["src/lib.rs", "src/plain.rs", "src/__tmt_rt.rs"] {
7154 assert_eq!(modified(©.join(name)), hour_ago, "{name}");
7155 }
7156 assert_ne!(modified(©.join("src/edited.rs")), hour_ago);
7157 assert_eq!(
7158 fs::read_to_string(copy.join("src/edited.rs")).unwrap(),
7159 "probe // edited since"
7160 );
7161 assert_eq!(
7162 fs::read_to_string(copy.join("src/lib.rs")).unwrap(),
7163 "probe // src/lib.rs"
7164 );
7165 assert_eq!(
7166 fs::read_to_string(dir.join("work").join(WRITTEN_LOG)).unwrap(),
7167 "src/__tmt_rt.rs\nsrc/edited.rs\nsrc/lib.rs\n"
7168 );
7169 let later = hour_ago + Duration::from_secs(60);
7171 set_modified(&dir.join("ws/src/plain.rs"), later);
7172 run();
7173 assert_eq!(modified(©.join("src/plain.rs")), hour_ago);
7174 let plain = fs::read_to_string(dir.join("ws/src/plain.rs")).unwrap();
7177 fs::write(dir.join("ws/src/plain.rs"), plain.to_uppercase()).unwrap();
7178 set_modified(
7179 &dir.join("ws/src/plain.rs"),
7180 hour_ago - Duration::from_secs(60),
7181 );
7182 run();
7183 assert_eq!(
7184 fs::read_to_string(copy.join("src/plain.rs")).unwrap(),
7185 plain.to_uppercase()
7186 );
7187 assert!(modified(©.join("src/plain.rs")) > later);
7188 fs::remove_dir_all(&dir).unwrap();
7189 }
7190
7191 #[test]
7192 fn work_copy_log_is_not_trusted() {
7193 let dir = scratch("copy-log");
7194 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7195 let copy = work.join("src");
7196 let outside = dir.join("outside.txt");
7197 fs::write(&outside, "keep").unwrap();
7198 fs::write(workspace.join("src/a.rs"), "a").unwrap();
7199 fs::write(
7201 work.join(WRITTEN_LOG),
7202 format!(
7203 "../../outside.txt\n{}\n\nsrc/../../../outside.txt\nsrc/a.rs\n",
7204 outside.display()
7205 ),
7206 )
7207 .unwrap();
7208 let state = WorkCopy::open(&work, ©);
7209 assert_eq!(
7210 state.earlier,
7211 [copy.join("src/a.rs")].into_iter().collect::<HashSet<_>>()
7212 );
7213 copy_tree(&workspace, ©, &workspace, &|_| false, &state).unwrap();
7214 state.settle(&workspace).unwrap();
7215 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7216 assert_eq!(fs::read_to_string(copy.join("src/a.rs")).unwrap(), "a");
7217
7218 let state = WorkCopy::open(&work, ©);
7220 assert!(state.write(&outside, "x").is_err());
7221 assert!(state.write(©.join("src/a\nb.rs"), "x").is_err());
7222 assert!(!copy.join("src/a\nb.rs").exists());
7223 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7224 fs::remove_dir_all(&dir).unwrap();
7225 }
7226 #[test]
7227 fn work_copy_log_follows_every_write() {
7228 let dir = scratch("copy-log-order");
7229 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7230 let copy = work.join("src");
7231 let log = work.join(WRITTEN_LOG);
7232 let names = ["h", "c", "f", "a", "e", "b", "g", "d"].map(|n| format!("src/{n}.rs"));
7233 for name in &names {
7234 fs::write(workspace.join(name), "x").unwrap();
7235 }
7236 let state = copy_run(&dir, &[], false);
7237 state.record(©.join(&names[0])).unwrap();
7239 state.record(©.join(&names[0])).unwrap();
7240 assert_eq!(fs::read_to_string(&log).unwrap(), "src/h.rs\n");
7241 assert_eq!(fs::read_to_string(copy.join(&names[0])).unwrap(), "x");
7242 for name in &names {
7243 state.write(©.join(name), "probe").unwrap();
7244 }
7245 state.settle(&workspace).unwrap();
7246 let mut sorted = names.to_vec();
7247 sorted.sort();
7248 assert_eq!(
7249 fs::read_to_string(&log).unwrap(),
7250 sorted.iter().map(|n| format!("{n}\n")).collect::<String>()
7251 );
7252
7253 let state = copy_run(&dir, &[], false);
7255 state.settle(&workspace).unwrap();
7256 assert_eq!(fs::read_to_string(&log).unwrap(), "");
7257 state.write(©.join(&names[3]), "probe").unwrap();
7258 assert_eq!(fs::read_to_string(&log).unwrap(), "src/a.rs\n");
7259 fs::remove_dir_all(&dir).unwrap();
7260 }
7261
7262 #[test]
7263 fn sync_copies_what_is_not_up_to_date_and_nothing_else() {
7264 let dir = scratch("copy-sync");
7265 let (workspace, work) = (dir.join("ws"), dir.join("work"));
7266 let copy = work.join("src");
7267 let hour_ago = std::time::SystemTime::now() - Duration::from_secs(3600);
7268 for name in [
7269 "same",
7270 "longer",
7271 "newer",
7272 "was_dir",
7273 "was_link",
7274 "short_link",
7275 "twin_link",
7276 "shorter",
7277 ] {
7278 fs::write(workspace.join("src").join(name), "source").unwrap();
7279 set_modified(&workspace.join("src").join(name), hour_ago);
7280 }
7281 let locked = workspace.join("src/locked");
7283 fs::write(&locked, "read only").unwrap();
7284 let mut permissions = fs::metadata(&locked).unwrap().permissions();
7285 permissions.set_readonly(true);
7286 fs::set_permissions(&locked, permissions).unwrap();
7287 fs::create_dir_all(copy.join("src/was_dir/inner")).unwrap();
7288 fs::write(copy.join("src/same"), "SOURCE").unwrap();
7290 fs::write(workspace.join("src/copied"), "as it is").unwrap();
7292 fs::write(copy.join("src/copied"), "as it is").unwrap();
7293 let long_ago = hour_ago - Duration::from_secs(7200);
7294 set_modified(©.join("src/copied"), long_ago);
7295 let elsewhere = dir.join("elsewhere");
7297 fs::create_dir_all(&elsewhere).unwrap();
7298 std::os::unix::fs::symlink(&elsewhere, copy.join("linked")).unwrap();
7299 fs::create_dir_all(workspace.join("linked/deep")).unwrap();
7300 fs::write(workspace.join("linked/deep/z"), "z").unwrap();
7301 fs::write(copy.join("src/longer"), "SOURCE+").unwrap();
7302 fs::write(copy.join("src/newer"), "SOURCE").unwrap();
7303 set_modified(©.join("src/newer"), hour_ago - Duration::from_secs(60));
7304 let outside = dir.join("outside");
7306 fs::write(&outside, "keep").unwrap();
7307 std::os::unix::fs::symlink(&outside, copy.join("src/was_link")).unwrap();
7308 let twin = dir.join("twin");
7310 fs::write(&twin, "source").unwrap();
7311 std::os::unix::fs::symlink(&twin, copy.join("src/twin_link")).unwrap();
7312 fs::write(copy.join("src/shorter"), "sour").unwrap();
7314 std::os::unix::fs::symlink("abcdef", copy.join("src/short_link")).unwrap();
7316 fs::create_dir_all(copy.join("old/deep")).unwrap();
7318 fs::write(copy.join("old/deep/x"), "x").unwrap();
7319 fs::create_dir_all(workspace.join("keep/deep")).unwrap();
7320 fs::write(workspace.join("keep/deep/y"), "y").unwrap();
7321
7322 copy_run(&dir, &[], true);
7323 let read = |name: &str| fs::read_to_string(copy.join(name)).unwrap();
7324 assert_eq!(read("src/locked"), "read only");
7325 assert_eq!(read("src/copied"), "as it is");
7326 assert_eq!(
7327 fs::metadata(copy.join("src/copied"))
7328 .unwrap()
7329 .modified()
7330 .unwrap(),
7331 long_ago
7332 );
7333 assert_eq!(read("linked/deep/z"), "z");
7334 assert!(fs::symlink_metadata(copy.join("linked")).unwrap().is_dir());
7335 assert_eq!(
7336 fs::read_dir(&elsewhere).unwrap().count(),
7337 0,
7338 "nothing written through"
7339 );
7340 for name in [
7341 "src/same",
7342 "src/longer",
7343 "src/newer",
7344 "src/was_dir",
7345 "src/was_link",
7346 "src/short_link",
7347 "src/twin_link",
7348 "src/shorter",
7349 ] {
7350 assert_eq!(read(name), "source", "{name}");
7351 assert!(
7352 fs::symlink_metadata(copy.join(name)).unwrap().is_file(),
7353 "{name}"
7354 );
7355 }
7356 assert!(
7357 fs::symlink_metadata(copy.join("src/was_link"))
7358 .unwrap()
7359 .is_file()
7360 );
7361 assert_eq!(fs::read_to_string(&outside).unwrap(), "keep");
7362 assert!(!copy.join("old").exists());
7363 assert_eq!(read("keep/deep/y"), "y");
7364 fs::remove_dir_all(&dir).unwrap();
7365 }
7366 #[test]
7367 fn a_finding_keeps_its_number_when_the_one_before_it_is_closed() {
7368 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";
7369 let found = instrument::discover(source, 0).unwrap();
7370 let mut all: Vec<(usize, usize, String)> = found
7371 .sites
7372 .iter()
7373 .map(|site| {
7374 let at = report::location("", site);
7375 (at.line, at.column, at.code)
7376 })
7377 .collect();
7378 all.push(
7379 all.iter()
7380 .find(|(line, _, code)| *line == 3 && code == "a > b")
7381 .unwrap()
7382 .clone(),
7383 );
7384 all.reverse();
7385 let places = [FilePlaces {
7386 display: "src/lib.rs",
7387 source,
7388 lines: &scope::LineIndex::new(source),
7389 places: &all,
7390 }];
7391 let gap = |line: usize, column: usize, file: &str| Finding::InputGap {
7392 at: report::Location {
7393 file: file.to_string(),
7394 line,
7395 column,
7396 code: "a > b".to_string(),
7397 ..report::Location::default()
7398 },
7399 survivors: vec![],
7400 survivor_count: 0,
7401 add_tests: vec![],
7402 observed: None,
7403 verified: true,
7404 };
7405 let name = |finding: &Finding| {
7406 let at = finding.at();
7407 (at.item.clone(), at.id.clone())
7408 };
7409 let mut findings = [
7411 gap(4, 20, "src/lib.rs"),
7412 gap(9, 5, "src/lib.rs"),
7413 gap(9, 5, "src/other.rs"),
7414 gap(5, 9, "src/lib.rs"), ];
7416 name_findings(&mut findings, &places);
7417 assert_eq!(
7418 name(&findings[0]),
7419 (
7420 "S::f".to_string(),
7421 "input_gap|src/lib.rs|S::f|a > b|1".to_string()
7422 )
7423 );
7424 assert_eq!(
7425 name(&findings[1]),
7426 (
7427 "g".to_string(),
7428 "input_gap|src/lib.rs|g|a > b|0".to_string()
7429 )
7430 );
7431 assert_eq!(name(&findings[2]), (String::new(), String::new()));
7433 assert_eq!(
7434 name(&findings[3]),
7435 (
7436 "S::f".to_string(),
7437 "input_gap|src/lib.rs|S::f|a > b|2".to_string()
7438 )
7439 );
7440 }
7441
7442 #[test]
7443 fn an_audit_searches_only_the_jobs_for_its_site() {
7444 let jobs: Vec<_> = [1, 1, 3, 8, 8]
7445 .into_iter()
7446 .map(|site| Job {
7447 site,
7448 mutation: Mutation::Negate,
7449 tests: vec![],
7450 })
7451 .collect();
7452 for (site, range) in [
7453 (0, 0..0),
7454 (1, 0..2),
7455 (2, 2..2),
7456 (3, 2..3),
7457 (4, 3..3),
7458 (8, 3..5),
7459 (9, 5..5),
7460 ] {
7461 let found = jobs_for_site(&jobs, site);
7462 assert_eq!(found, range);
7463 assert_eq!(
7464 found
7465 .clone()
7466 .find(|&index| jobs[index].mutation == Mutation::Negate),
7467 jobs.iter()
7468 .position(|job| job.site == site && job.mutation == Mutation::Negate)
7469 );
7470 }
7471 }
7472
7473 #[test]
7474 fn an_audit_takes_its_sample_evenly_and_the_same_every_time() {
7475 assert_eq!(spread(0, 3), Vec::<usize>::new());
7476 assert_eq!(spread(5, 0), Vec::<usize>::new());
7477 assert_eq!(spread(3, 3), [0, 1, 2]);
7478 assert_eq!(spread(3, 10), [0, 1, 2]);
7479 assert_eq!(spread(10, 1), [0]);
7480 assert_eq!(spread(10, 3), [0, 3, 6]);
7481 assert_eq!(spread(10, 5), [0, 2, 4, 6, 8]);
7482 assert_eq!(spread(4, 3), [0, 1, 2]);
7483 assert_eq!(spread(7, 6), [0, 1, 2, 3, 4, 5]);
7484 }
7485
7486 #[test]
7487 fn a_mutant_of_the_source_is_the_mutation_its_probe_runs() {
7488 assert_ne!(crate::tmt_rt::CANNOT_EVALUATE, 0);
7491 let source = "fn f(a: i32, b: i32, ok: bool, k: Option<i32>, base: O) -> O { \
7492 go(); \
7493 let x = match k { Some(n) if n > 1 => !ok && a < b, _ => -a + b > 0 || ok }; \
7494 for _ in a..b {} for _ in a..=b {} \
7495 O { on: x, ..base } }";
7496 let found = instrument::discover(source, 0).unwrap().sites;
7497 let mut seen = BTreeSet::new();
7498 for site in &found {
7499 for mutant in instrument::source_mutants(site) {
7500 let kind = format!("{:?}", site.kind);
7501 let kind = kind.split([' ', '{', '(']).next().unwrap().to_string();
7502 seen.insert((
7503 kind,
7504 mutant.into.clone(),
7505 format!("{:?}", mutation_of(site, &mutant)),
7506 ));
7507 }
7508 }
7509 let expected = [
7510 ("Arith", "*", "ArithSwap2"),
7511 ("Arith", "-", "ArithSwap"),
7512 ("Arm", "Some(n) if n > 1", "Delete"),
7513 ("Body", "Default::default()", "Delete"),
7514 ("Cmp", "<", "Op(Lt)"),
7515 ("Cmp", "<=", "Op(Le)"),
7516 ("Cmp", "==", "Op(Eq)"),
7517 ("Cmp", ">", "Op(Gt)"),
7518 ("Cmp", ">=", "Op(Ge)"),
7519 ("Field", "on", "Delete"),
7520 ("Guard", "true", "Const(true)"),
7521 ("Logic", "&&", "LogicSwap"),
7522 ("Logic", "||", "LogicSwap"),
7523 ("Neg", "", "Delete"),
7524 ("Not", "", "DropNot"),
7525 ("Range", "..", "RangeEnd"),
7526 ("Range", "..=", "RangeEnd"),
7527 ("Stmt", "", "Delete"),
7528 ];
7529 let like = |source: &str, into: &str| -> Vec<Mutation> {
7532 let sites = instrument::discover(source, 0).unwrap().sites;
7533 let site = sites
7534 .iter()
7535 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
7536 .unwrap();
7537 let mutant = instrument::source_mutants(site)
7538 .into_iter()
7539 .find(|mutant| mutant.into == into)
7540 .unwrap();
7541 mutations_like(site, &mutant, true)
7542 };
7543 use plan::CmpOp::*;
7544 for (op, into, expected) in [
7545 ("==", "!=", vec![Mutation::Op(Ne), Mutation::Negate]),
7546 ("!=", "==", vec![Mutation::Op(Eq), Mutation::Negate]),
7547 ("<=", ">", vec![Mutation::Op(Gt), Mutation::Negate]),
7548 (">=", "<", vec![Mutation::Op(Lt), Mutation::Negate]),
7549 ("<", "<=", vec![Mutation::Op(Le), Mutation::Shift(1)]),
7550 (">", ">=", vec![Mutation::Op(Ge), Mutation::Shift(-1)]),
7551 ("<", "==", vec![Mutation::Op(Eq)]),
7552 ("<", ">", vec![Mutation::Op(Gt)]),
7553 (">", "==", vec![Mutation::Op(Eq)]),
7554 (">", "<", vec![Mutation::Op(Lt)]),
7555 ] {
7556 let source = format!("fn f(a: i32, b: i32) -> bool {{ a {op} b }}");
7557 assert_eq!(like(&source, into), expected, "{op} as {into}");
7558 }
7559 let unordered = |op: &str, into: &str| -> Vec<Mutation> {
7562 let source = format!("fn f(a: f64, b: f64) -> bool {{ a {op} b }}");
7563 let sites = instrument::discover(&source, 0).unwrap().sites;
7564 let site = sites
7565 .iter()
7566 .find(|site| matches!(site.kind, SiteKind::Cmp { .. }))
7567 .unwrap();
7568 let mutant = instrument::source_mutants(site)
7569 .into_iter()
7570 .find(|mutant| mutant.into == into)
7571 .unwrap();
7572 mutations_like(site, &mutant, false)
7573 };
7574 assert_eq!(unordered(">=", "<"), [Mutation::Op(Lt)]);
7575 assert_eq!(unordered("<=", ">"), [Mutation::Op(Gt)]);
7576 assert_eq!(unordered("==", "!="), [Mutation::Op(Ne), Mutation::Negate]);
7577 for d in -3..=3 {
7579 assert_eq!(
7580 plan::eval_mutated_d(Lt, Mutation::Shift(1), d),
7581 Le.eval_d(d)
7582 );
7583 assert_eq!(
7584 plan::eval_mutated_d(Gt, Mutation::Shift(-1), d),
7585 Ge.eval_d(d)
7586 );
7587 }
7588 let seen: Vec<(&str, &str, &str)> = seen
7589 .iter()
7590 .map(|(kind, into, mutation)| (kind.as_str(), into.as_str(), mutation.as_str()))
7591 .collect();
7592 assert_eq!(seen, expected);
7593 }
7594
7595 #[test]
7596 fn the_mark_of_a_run_is_a_new_file_and_says_one_of_three_things() {
7597 let dir = scratch("unable-mark");
7598 fs::create_dir_all(&dir).unwrap();
7599 let runs = std::sync::atomic::AtomicUsize::new(0);
7600 let name = |n: usize| dir.join(format!("tmt-unable-{}-{n}", std::process::id()));
7601 fs::write(name(0), "not ours").unwrap();
7604 fs::write(name(1), "nor this").unwrap();
7605 let mark = reserve_file(&dir, "unable", &runs).unwrap();
7606 assert_eq!(mark, name(2));
7607 assert!(mark.is_absolute());
7608 assert_eq!(fs::read_to_string(&mark).unwrap(), "");
7609 assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
7610 assert_eq!(fs::read_to_string(name(1)).unwrap(), "nor this");
7611 assert!(!release_mark(&mark).unwrap());
7613 assert!(!mark.exists());
7614 let mark = reserve_file(&dir, "unable", &runs).unwrap();
7616 assert_eq!(mark, name(3));
7617 fs::remove_file(&mark).unwrap();
7618 assert!(release_mark(&mark).unwrap());
7619 let in_the_way = dir.join("a-directory");
7622 fs::create_dir_all(&in_the_way).unwrap();
7623 let refused = format!("{:#}", release_mark(&in_the_way).unwrap_err());
7624 assert!(refused.contains("cannot tell whether"), "{refused}");
7625 assert!(refused.contains("a-directory"), "{refused}");
7626 assert!(in_the_way.is_dir());
7627 let unmade = format!("{:#}", reserve_file(&name(0), "unable", &runs).unwrap_err());
7629 assert!(unmade.contains("creating"), "{unmade}");
7630 assert_eq!(fs::read_to_string(name(0)).unwrap(), "not ours");
7631 fs::remove_dir_all(&dir).unwrap();
7632 }
7633
7634 #[test]
7635 fn the_directory_of_the_marks_is_made_or_used_and_nothing_is_removed_for_it() {
7636 let dir = scratch("marks-dir");
7637 let work = dir.join("work");
7638 assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
7640 assert!(work.join("marks").is_dir());
7641 fs::write(work.join("marks/left-over"), "x").unwrap();
7642 assert_eq!(marks_dir(&work).unwrap(), work.join("marks"));
7643 assert_eq!(
7644 fs::read_to_string(work.join("marks/left-over")).unwrap(),
7645 "x"
7646 );
7647 let taken = dir.join("taken");
7649 fs::create_dir_all(&taken).unwrap();
7650 fs::write(taken.join("marks"), "grades of the class").unwrap();
7651 let said = format!("{:#}", marks_dir(&taken).unwrap_err());
7652 assert!(
7653 said.contains("is in the way") && said.contains("marks"),
7654 "{said}"
7655 );
7656 assert_eq!(
7657 fs::read_to_string(taken.join("marks")).unwrap(),
7658 "grades of the class"
7659 );
7660 #[cfg(unix)]
7662 {
7663 let linked = dir.join("linked");
7664 let elsewhere = dir.join("elsewhere");
7665 fs::create_dir_all(&linked).unwrap();
7666 fs::create_dir_all(&elsewhere).unwrap();
7667 std::os::unix::fs::symlink(&elsewhere, linked.join("marks")).unwrap();
7668 assert!(marks_dir(&linked).is_err());
7669 assert!(
7670 fs::symlink_metadata(linked.join("marks"))
7671 .unwrap()
7672 .is_symlink()
7673 );
7674 assert_eq!(fs::read_dir(&elsewhere).unwrap().count(), 0);
7675 }
7676 fs::remove_dir_all(&dir).unwrap();
7677 }
7678
7679 #[test]
7680 fn what_the_runs_left_is_said_only_when_there_was_something() {
7681 assert_eq!(leftover_note(0, 0), None);
7682 assert_eq!(
7683 leftover_note(3, 0).unwrap(),
7684 "stopped 3 processes that the tests had left running after their run"
7685 );
7686 assert_eq!(
7687 leftover_note(0, 2).unwrap(),
7688 "after 2 runs something the tests started may still be running (it could not be \
7689 found or stopped)"
7690 );
7691 let both = leftover_note(1, 1).unwrap();
7692 assert!(both.starts_with("stopped 1 processes") && both.contains("; after 1 runs"));
7693 }
7694
7695 #[test]
7696 fn a_predicted_survivor_is_unstable_only_when_a_re_run_was_found_out() {
7697 let run = |survived: bool, unable: bool, unconfirmed_timeout: bool| JobResult {
7698 first_pass_timeout: unconfirmed_timeout,
7699 unconfirmed_timeout,
7700 survived: survived.then(Vec::new),
7701 timed_out: unconfirmed_timeout,
7702 unable,
7703 };
7704 let passed = || run(true, false, false);
7705 let found_out = || run(false, false, false);
7706 let unable = || run(false, true, false);
7707 let unconfirmed = || run(false, false, true);
7708 let of = |runs: Vec<JobResult>| Prediction::of(runs.iter());
7709 assert_eq!(of(vec![]), Prediction::Confirmed);
7710 assert_eq!(of(vec![passed(), passed()]), Prediction::Confirmed);
7711 assert_eq!(of(vec![passed(), found_out()]), Prediction::Refuted);
7712 assert_eq!(of(vec![found_out(), passed()]), Prediction::Refuted);
7713 assert_eq!(of(vec![unable(), found_out()]), Prediction::Refuted);
7715 assert_eq!(of(vec![found_out(), unconfirmed()]), Prediction::Refuted);
7716 assert_eq!(of(vec![passed(), unable()]), Prediction::Unknown);
7717 assert_eq!(of(vec![unable(), passed()]), Prediction::Unknown);
7718 assert_eq!(of(vec![unconfirmed()]), Prediction::Unknown);
7719 }
7720
7721 #[cfg(unix)]
7722 #[test]
7723 fn a_build_that_failed_is_not_code_the_compiler_refused() {
7724 use std::os::unix::process::ExitStatusExt;
7725 let output = |status: i32, stdout: &str, stderr: &str| std::process::Output {
7726 status: std::process::ExitStatus::from_raw(status),
7727 stdout: stdout.as_bytes().to_vec(),
7728 stderr: stderr.as_bytes().to_vec(),
7729 };
7730 let refusal = r#"{"reason":"compiler-message","message":{"level":"error","message":"mismatched types","rendered":"error: mismatched types","spans":[]}}"#;
7731 let warning = r#"{"reason":"compiler-message","message":{"level":"warning","message":"unused","rendered":"warning: unused","spans":[]}}"#;
7732 assert_eq!(source_build(&output(0, warning, "")), SourceBuild::Built);
7734 assert_eq!(
7735 source_build(&output(101 << 8, refusal, "error: could not compile")),
7736 SourceBuild::Refused
7737 );
7738 let killed = source_build(&output(9, warning, "Compiling x\nlast words"));
7740 assert!(
7741 matches!(&killed, SourceBuild::Failed(why) if why.contains("last words")),
7742 "{killed:?}"
7743 );
7744 let cargo = source_build(&output(
7745 101 << 8,
7746 "",
7747 "error: failed to open lock\nno space left on device",
7748 ));
7749 assert!(
7750 matches!(&cargo, SourceBuild::Failed(why) if why.contains("no space left")),
7751 "{cargo:?}"
7752 );
7753 }
7754
7755 #[test]
7756 fn concurrent_runs_share_the_cores() {
7757 assert_eq!(test_threads(16, 1), 16);
7759 assert_eq!(test_threads(16, 4), 4);
7760 assert_eq!(test_threads(18, 4), 4);
7761 assert_eq!(test_threads(16, 8), 2);
7763 assert_eq!(test_threads(16, 9), 2);
7764 assert_eq!(test_threads(4, 16), 2);
7765 assert_eq!(test_threads(1, 1), 2);
7766 assert_eq!(test_threads(8, 0), 8);
7767 }
7768
7769 #[test]
7770 fn cargo_is_told_the_same_everywhere() {
7771 assert!(CargoConfig::default().flags().is_empty());
7772 let some = CargoConfig {
7773 features: vec!["a".to_string(), "dep/b".to_string()],
7774 no_default_features: true,
7775 ..CargoConfig::default()
7776 };
7777 assert_eq!(
7778 some.flags(),
7779 ["--features", "a,dep/b", "--no-default-features"]
7780 );
7781 let all = CargoConfig {
7782 all_features: true,
7783 locked: true,
7784 ..CargoConfig::default()
7785 };
7786 assert_eq!(all.flags(), ["--all-features", "--locked"]);
7787 }
7788
7789 #[test]
7790 fn source_mutants_are_described_like_the_others() {
7791 let source = "fn f(a: i32, b: i32, k: Option<i32>) -> bool { \
7792 match k { Some(n) if n > 1 => !(a < b) || a + b == 0, _ => -a * b > 1 } }";
7793 let found = instrument::discover(source, 0).unwrap().sites;
7794 let described: Vec<String> = found
7795 .iter()
7796 .flat_map(|site| {
7797 instrument::source_mutants(site)
7798 .into_iter()
7799 .map(|mutant| report::describe(site, mutation_of(site, &mutant)))
7800 })
7801 .collect();
7802 assert_eq!(
7803 described,
7804 [
7805 "the body of `f` replaced by `true`",
7806 "the body of `f` replaced by `false`",
7807 "remove the arm `Some(n) if n > 1 => ..`",
7809 "the guard `n > 1` replaced by `true`",
7810 "`n == 1`",
7811 "`n < 1`",
7812 "`n >= 1`",
7813 "`!(a < b) && a + b == 0`",
7814 "`(a < b)`",
7815 "`a == b`",
7816 "`a > b`",
7817 "`a <= b`",
7818 "`a + b != 0`",
7819 "`a - b`",
7820 "`a * b`",
7821 "`-a * b == 1`",
7822 "`-a * b < 1`",
7823 "`-a * b >= 1`",
7824 "`-a / b`",
7825 "`-a + b`",
7826 "`a`",
7827 ]
7828 );
7829 let source = "fn f(k: K) -> u8 { match k { K::A(n) if n > 1 => 1, K::A(_) => 2 } }";
7831 let found = instrument::discover(source, 0).unwrap().sites;
7832 let guard = found
7833 .iter()
7834 .find(|s| matches!(s.kind, SiteKind::Guard { .. }))
7835 .unwrap();
7836 let described: Vec<String> = instrument::source_mutants(guard)
7837 .iter()
7838 .map(|mutant| report::describe(guard, mutation_of(guard, mutant)))
7839 .collect();
7840 assert_eq!(
7841 described,
7842 [
7843 "the guard `n > 1` replaced by `true`",
7844 "the guard `n > 1` replaced by `false`"
7845 ]
7846 );
7847 }
7848
7849 #[test]
7850 fn dependents_are_found_once_through_a_cycle_that_leaves_the_package_out() {
7851 let package = |name: &str, deps: &[&str]| Package {
7852 name: name.to_string(),
7853 features: BTreeMap::new(),
7854 dependencies: deps
7855 .iter()
7856 .map(|d| Dependency {
7857 name: d.to_string(),
7858 })
7859 .collect(),
7860 manifest_path: PathBuf::new(),
7861 targets: vec![],
7862 };
7863 let packages = [
7866 package("z", &[]),
7867 package("x", &["y", "z"]),
7868 package("y", &["x"]),
7869 ];
7870 assert_eq!(dependents_of("z", &packages), ["x", "y"]);
7871 }
7872
7873 #[test]
7874 fn an_error_is_said_once_and_only_when_it_says_something() {
7875 let stdout = r#"
7876{"reason":"compiler-message","message":{"level":"error","spans":[]}}
7877{"reason":"compiler-message","message":{"level":"error","message":"","rendered":null,"spans":[]}}
7878{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}
7879{"reason":"compiler-message","message":{"level":"error","rendered":"aborting","spans":[]}}
7880"#;
7881 assert_eq!(parse_build_output(stdout, &["p"]).diagnostics, ["aborting"]);
7882 }
7883
7884 #[cfg(unix)]
7886 fn script_binary(dir: &Path, body: &str) -> TestBinary {
7887 use std::os::unix::fs::PermissionsExt as _;
7888 let work = dir.join("work");
7889 let exe = work.join("runner");
7890 fs::write(&exe, format!("#!/bin/sh\n{body}\n")).unwrap();
7891 fs::set_permissions(&exe, fs::Permissions::from_mode(0o755)).unwrap();
7892 TestBinary {
7893 name: "runner".into(),
7894 cwd: work.join("src"),
7895 marks: marks_dir(&work).unwrap(),
7896 git_ceiling: work,
7897 work_lock: None,
7898 tests: BTreeSet::new(),
7899 runner: Runner::Exe(exe),
7900 baseline: Duration::ZERO,
7901 untraced_baseline: None,
7902 timeout_diagnostic: std::sync::Once::new(),
7903 traced: Duration::ZERO,
7904 timeout: None,
7905 wrapper_grace: Duration::ZERO,
7906 report_slow: false,
7907 filtered_timings: Default::default(),
7908 trace: Trace::default(),
7909 effects_baseline: std::sync::OnceLock::new(),
7910 }
7911 }
7912
7913 #[cfg(unix)]
7915 fn isolated(mut bin: TestBinary) -> TestBinary {
7916 let exe = bin.runner.executable().unwrap().to_path_buf();
7917 bin.runner = Runner::Isolated {
7918 exe,
7919 test: "t".to_string(),
7920 ignored: false,
7921 wrapper: None,
7922 };
7923 bin
7924 }
7925
7926 #[cfg(unix)]
7929 fn ends(pid: u32) -> bool {
7930 let deadline = Instant::now() + Duration::from_secs(10);
7931 loop {
7932 let state = Command::new("ps")
7933 .args(["-o", "stat=", "-p", &pid.to_string()])
7934 .output()
7935 .unwrap();
7936 let state = String::from_utf8_lossy(&state.stdout);
7937 if state.trim().is_empty() || state.trim().starts_with('Z') {
7938 return true;
7939 }
7940 if Instant::now() >= deadline {
7941 let _ = Command::new("kill").args(["-9", &pid.to_string()]).status();
7943 return false;
7944 }
7945 std::thread::sleep(Duration::from_millis(5));
7946 }
7947 }
7948
7949 #[cfg(unix)]
7952 fn nothing_runs(path: &Path) -> bool {
7953 let deadline = Instant::now() + Duration::from_secs(10);
7954 loop {
7955 let processes = Command::new("ps")
7956 .args(["-e", "-o", "args="])
7957 .output()
7958 .unwrap();
7959 let processes = String::from_utf8_lossy(&processes.stdout).into_owned();
7960 if !processes.contains(&*path.to_string_lossy()) {
7961 return true;
7962 }
7963 if Instant::now() >= deadline {
7964 return false;
7965 }
7966 std::thread::sleep(Duration::from_millis(5));
7967 }
7968 }
7969
7970 #[cfg(unix)]
7971 #[test]
7972 fn a_filter_is_timed_only_for_a_slow_libtest_binary_without_a_given_limit() {
7973 let dir = scratch("unmeasured-filters");
7974 let slow = Duration::from_secs(70);
7975 let fast = ["fast".to_string()];
7976 let all = ["fast".to_string(), "slow".to_string()];
7977 let binary = |baseline, timeout| {
7978 let mut bin = script_binary(&dir, "exit 0");
7979 bin.tests = all.iter().cloned().collect();
7980 bin.baseline = baseline;
7981 bin.timeout = timeout;
7982 bin
7983 };
7984 let timed = |bin: &TestBinary| bin.filtered_timings.lock().unwrap().len();
7985
7986 let given = binary(slow, Some(Duration::from_secs(8)));
7988 assert_eq!(
7989 given.filtered_limit(Some(&fast), false),
7990 Duration::from_secs(8)
7991 );
7992 assert_eq!(timed(&given), 0);
7993 let quick = binary(Duration::from_secs(1), None);
7995 assert_eq!(
7996 quick.filtered_limit(Some(&fast), false),
7997 Duration::from_secs(10)
7998 );
7999 assert_eq!(timed(&quick), 0);
8000 let at_the_threshold = binary(SLOW_TRACE, None);
8002 at_the_threshold.filtered_limit(Some(&fast), false);
8003 assert_eq!(timed(&at_the_threshold), 1);
8004 let one_by_one = isolated(binary(slow, None));
8006 assert_eq!(
8007 one_by_one.filtered_limit(Some(&fast), false),
8008 Duration::from_secs(355)
8009 );
8010 assert_eq!(timed(&one_by_one), 0);
8011 let whole = binary(slow, None);
8013 for filter in [&[][..], &all[..]] {
8014 assert_eq!(
8015 whole.filtered_limit(Some(filter), false),
8016 Duration::from_secs(355),
8017 "{filter:?}"
8018 );
8019 }
8020 assert_eq!(timed(&whole), 0);
8021 fs::remove_dir_all(dir).unwrap();
8022 }
8023
8024 #[test]
8025 fn a_command_in_the_copy_cannot_reach_the_repository_around_it() {
8026 use std::ffi::OsStr;
8027 let mut command = Command::new("git");
8028 isolate_copy_command(&mut command, Path::new("/work"));
8029 let set: Vec<_> = command.get_envs().collect();
8030 for removed in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"] {
8031 assert!(set.contains(&(OsStr::new(removed), None)), "{removed}");
8032 }
8033 assert!(set.contains(&(
8034 OsStr::new("GIT_CEILING_DIRECTORIES"),
8035 Some(OsStr::new("/work"))
8036 )));
8037 }
8038
8039 #[cfg(unix)]
8040 #[test]
8041 fn the_tests_are_given_the_mark_the_mutant_and_the_fence_for_git() {
8042 let dir = scratch("run-environment");
8043 let work = dir.join("work");
8044 let bin = script_binary(
8045 &dir,
8046 &format!(
8047 "[ -f \"$TMT_UNABLE\" ] && [ \"$TMT_MUTANT\" = 7 ] \
8048 && [ \"$GIT_CEILING_DIRECTORIES\" = '{}' ]",
8049 work.display()
8050 ),
8051 );
8052 assert_eq!(
8053 run_binary(
8054 &bin,
8055 None,
8056 &[("TMT_MUTANT", "7")],
8057 Duration::from_secs(60),
8058 RunOutput::Quiet,
8059 1
8060 )
8061 .unwrap(),
8062 Outcome::Pass
8063 );
8064 fs::remove_dir_all(dir).unwrap();
8065 }
8066
8067 #[cfg(unix)]
8068 #[test]
8069 fn a_failure_line_ends_the_run_before_the_tests_do() {
8070 let dir = scratch("first-failure");
8071 let bin = script_binary(
8074 &dir,
8075 "sleep 30 &\necho $! > child.pid\necho 'test tests::a ... FAILED'\nwait",
8076 );
8077 let outcome = run_binary(
8078 &bin,
8079 None,
8080 &[],
8081 Duration::from_secs(20),
8082 RunOutput::FirstFailure,
8083 1,
8084 );
8085 let pid = fs::read_to_string(bin.cwd.join("child.pid"))
8086 .unwrap()
8087 .trim()
8088 .parse()
8089 .unwrap();
8090 let stopped = ends(pid);
8091 fs::remove_dir_all(dir).unwrap();
8092 assert_eq!(outcome.unwrap(), Outcome::Fail);
8093 assert!(stopped, "the failed run left a process behind");
8094 }
8095
8096 #[cfg(unix)]
8097 #[test]
8098 fn failure_lines_are_found_in_output_that_comes_in_pieces() {
8099 use std::io::Write as _;
8100 let dir = scratch("failure-output");
8101 let path = dir.join("output");
8102 let mut written = fs::File::create(&path).unwrap();
8103 let mut output = FailureOutput::new(fs::File::open(&path).unwrap());
8104 let mut next = |text: &str| {
8105 written.write_all(text.as_bytes()).unwrap();
8106 output.failed().unwrap()
8107 };
8108 assert!(!next(""));
8109 assert!(!next("running 2 tests\ntest tests::a ... ok\n"));
8110 assert!(!next("test tests::b ... FA"));
8112 assert!(next("ILED\n"));
8113 let long = format!("test {} ... FAILED\n", "x".repeat(8 * 1024));
8116 assert!(!next(&long));
8117 assert!(!next("test tests::c ... ok\n"));
8118 assert!(next("test tests::d ... FAILED\n"));
8119 assert!(next(
8121 "noise\ntest tests::e ... FAILED\ntest tests::f ... ok\n"
8122 ));
8123
8124 let longest = format!("test {} ... FAILED\n", "x".repeat(8 * 1024 - 17));
8126 assert_eq!(longest.len(), 8 * 1024);
8127 for (pieces, found) in [(vec![&longest[..]], true), (vec!["t", &longest[1..]], true)] {
8128 let path = dir.join("longest");
8129 let mut written = fs::File::create(&path).unwrap();
8130 let mut output = FailureOutput::new(fs::File::open(&path).unwrap());
8131 let mut last = false;
8132 for piece in pieces {
8133 written.write_all(piece.as_bytes()).unwrap();
8134 last = output.failed().unwrap();
8135 }
8136 assert_eq!(last, found);
8137 }
8138 let over = format!("test {} ... FAILED\n", "x".repeat(8 * 1024 - 16));
8139 assert_eq!(over.len(), 8 * 1024 + 1);
8140 let path = dir.join("over");
8141 let mut written = fs::File::create(&path).unwrap();
8142 let mut output = FailureOutput::new(fs::File::open(&path).unwrap());
8143 written.write_all(b"t").unwrap();
8144 assert!(!output.failed().unwrap());
8145 written.write_all(&over.as_bytes()[1..]).unwrap();
8146 assert!(!output.failed().unwrap());
8147 fs::remove_dir_all(dir).unwrap();
8148 }
8149
8150 #[cfg(unix)]
8151 #[test]
8152 fn output_nobody_reads_is_discarded() {
8153 let dir = scratch("discarded-output");
8154 let nowhere = "[ /dev/stdout -ef /dev/null ] && [ /dev/stderr -ef /dev/null ]";
8155 let run = |bin: &TestBinary, output| {
8156 run_binary(bin, None, &[], Duration::from_secs(60), output, 1).unwrap()
8157 };
8158 let quiet = script_binary(&dir, nowhere);
8160 assert_eq!(run(&quiet, RunOutput::Quiet), Outcome::Pass);
8161 let one_by_one = isolated(script_binary(
8165 &dir,
8166 &format!(
8167 "{nowhere} && [ \"$*\" = '--exact --test-threads=1 t' ] && [ \"$TMT_TEST\" = t ]"
8168 ),
8169 ));
8170 assert_eq!(run(&one_by_one, RunOutput::FirstFailure), Outcome::Pass);
8171 let watched = script_binary(
8173 &dir,
8174 "[ ! /dev/stdout -ef /dev/null ] && [ /dev/stderr -ef /dev/null ]",
8175 );
8176 assert_eq!(run(&watched, RunOutput::FirstFailure), Outcome::Pass);
8177 fs::remove_dir_all(dir).unwrap();
8178 }
8179
8180 #[cfg(unix)]
8181 #[test]
8182 fn what_a_finished_run_left_running_is_stopped() {
8183 let left_running = "sleep 30 &\necho $! > child.pid";
8184 let check = |name: &str, one_by_one: bool, output| {
8185 let dir = scratch(name);
8186 let mut bin = script_binary(&dir, left_running);
8187 if one_by_one {
8188 bin = isolated(bin);
8189 }
8190 let outcome = run_binary(&bin, None, &[], Duration::from_secs(60), output, 1);
8191 let pid = fs::read_to_string(bin.cwd.join("child.pid"))
8192 .unwrap()
8193 .trim()
8194 .parse()
8195 .unwrap();
8196 let stopped = ends(pid);
8197 fs::remove_dir_all(dir).unwrap();
8198 assert_eq!(outcome.unwrap(), Outcome::Pass, "{name}");
8199 assert!(stopped, "{name}: the run left a process behind");
8200 };
8201 check("left-running-watched", false, RunOutput::FirstFailure);
8202 check("left-running-isolated", true, RunOutput::Quiet);
8203 }
8204
8205 #[cfg(unix)]
8206 #[test]
8207 fn tests_that_do_not_end_in_time_are_stopped_as_a_timeout() {
8208 let dir = scratch("run-timeout");
8209 let bin = script_binary(&dir, "sleep 20");
8210 let outcome = run_binary(
8211 &bin,
8212 None,
8213 &[],
8214 Duration::from_millis(100),
8215 RunOutput::Quiet,
8216 1,
8217 );
8218 let stopped = nothing_runs(bin.runner.executable().unwrap());
8220 fs::remove_dir_all(dir).unwrap();
8221 assert_eq!(outcome.unwrap(), Outcome::Timeout);
8222 assert!(stopped, "the tests went on after the timeout");
8223 }
8224
8225 #[cfg(unix)]
8226 #[test]
8227 fn stopping_nextest_asks_first_and_takes_the_answer() {
8228 use std::io::Read as _;
8229 use std::os::unix::process::CommandExt as _;
8230
8231 let mut child = Command::new("sh")
8233 .args(["-c", "trap 'exit 7' TERM; printf X; sleep 60; exit 3"])
8234 .process_group(0)
8235 .stdout(Stdio::piped())
8236 .spawn()
8237 .unwrap();
8238 child.stdout.take().unwrap().read_exact(&mut [0]).unwrap();
8239
8240 let grace = Duration::from_secs(30);
8241 let started = Instant::now();
8242 stop_nextest(&mut child, grace);
8243 let status = child.try_wait().unwrap().expect("runner was reaped");
8244 assert_eq!(status.code(), Some(7));
8247 assert!(started.elapsed() < grace);
8248 }
8249
8250 #[cfg(unix)]
8251 #[test]
8252 fn stopping_nextest_stops_the_groups_its_tests_run_in() {
8253 use std::io::BufRead as _;
8254 use std::os::unix::process::CommandExt as _;
8255
8256 let dir = scratch("nextest-groups");
8259 let source = dir.join("runner.rs");
8260 let exe = dir.join("runner");
8261 fs::write(
8262 &source,
8263 r#"
8264use std::os::unix::process::CommandExt;
8265extern "C" {
8266 fn signal(signal: i32, handler: usize) -> usize;
8267}
8268fn main() {
8269 // Ignored (SIG_IGN), which what is started from here inherits.
8270 unsafe { signal(15, 1) };
8271 let test = std::process::Command::new("sleep").arg("60").process_group(0).spawn().unwrap();
8272 println!("{}", test.id());
8273 std::thread::sleep(std::time::Duration::from_secs(60));
8274}
8275"#,
8276 )
8277 .unwrap();
8278 let output = Command::new("rustc")
8279 .arg(&source)
8280 .arg("-o")
8281 .arg(&exe)
8282 .output()
8283 .unwrap();
8284 assert!(
8285 output.status.success(),
8286 "{}",
8287 String::from_utf8_lossy(&output.stderr)
8288 );
8289 let mut child = Command::new(&exe)
8290 .process_group(0)
8291 .stdout(Stdio::piped())
8292 .spawn()
8293 .unwrap();
8294 let mut line = String::new();
8295 std::io::BufReader::new(child.stdout.take().unwrap())
8296 .read_line(&mut line)
8297 .unwrap();
8298 let test: u32 = line.trim().parse().unwrap();
8299
8300 stop_nextest(&mut child, Duration::from_millis(10));
8301 let reaped = child.try_wait().unwrap();
8302 let stopped = ends(test);
8303 fs::remove_dir_all(dir).unwrap();
8304 assert!(reaped.is_some(), "runner was not reaped");
8305 assert!(stopped, "the group of the test was left running");
8306 }
8307
8308 #[cfg(unix)]
8309 fn process(pid: u32, parent: u32, group: u32, started: &str) -> TestProcess {
8310 TestProcess {
8311 pid,
8312 parent,
8313 group,
8314 started: started.to_string(),
8315 }
8316 }
8317
8318 #[cfg(unix)]
8319 #[test]
8320 fn the_processes_of_a_runner_are_its_descendants_in_groups_they_lead() {
8321 let table = || {
8322 vec![
8323 process(30, 20, 30, "t"),
8325 process(20, 10, 10, "t"),
8326 process(10, 1, 10, "t"),
8327 process(40, 10, 77, "t"),
8329 process(77, 1, 77, "t"),
8330 process(50, 1, 10, "t"),
8332 process(60, 1, 60, "t"),
8333 ]
8334 };
8335 assert_eq!(
8336 owned_among(table(), 10),
8337 [
8338 process(30, 20, 30, "t"),
8339 process(20, 10, 10, "t"),
8340 process(10, 1, 10, "t")
8341 ]
8342 );
8343 assert!(owned_among(table(), 11).is_empty());
8345 }
8346
8347 #[cfg(unix)]
8348 #[test]
8349 fn a_group_survives_only_through_the_very_process_seen_in_it() {
8350 let owned = [process(10, 1, 10, "a"), process(30, 10, 30, "b")];
8351 let surviving = |current: &[TestProcess]| surviving_groups(&owned, current);
8352 assert_eq!(
8353 surviving(&[
8354 process(10, 1, 10, "a"),
8355 process(30, 1, 30, "b"),
8356 process(60, 1, 60, "a")
8357 ]),
8358 BTreeSet::from([10, 30])
8359 );
8360 assert_eq!(surviving(&[process(10, 1, 10, "later")]), BTreeSet::new());
8362 assert_eq!(surviving(&[process(30, 1, 99, "b")]), BTreeSet::new());
8364 assert_eq!(surviving(&[process(31, 1, 30, "b")]), BTreeSet::new());
8366 }
8367
8368 #[test]
8369 fn a_working_directory_that_cannot_be_inspected_is_not_created_over() {
8370 let dir = scratch("marks-below-a-file");
8371 let file = dir.join("file");
8372 fs::write(&file, "").unwrap();
8373 let error = work_directory(&file, "marks").unwrap_err();
8374 assert!(error.to_string().starts_with("inspecting "), "{error:#}");
8375 fs::remove_dir_all(dir).unwrap();
8376 }
8377
8378 #[test]
8379 fn an_error_is_blamed_on_the_file_it_names() {
8380 let copy = Path::new("/work");
8381 let make = |name: &str, source: &str, first_id| {
8382 let sites = instrument::discover(source, first_id).unwrap().sites;
8383 let rendered = instrument::render(source, &sites, &|_| true);
8384 SourceFile {
8385 display: name.to_string(),
8386 path: copy.join(name),
8387 owners: BTreeSet::new(),
8388 lines: scope::LineIndex::new(source),
8389 original: source.to_string(),
8390 places: vec![],
8391 sites,
8392 rebuild_sites: vec![],
8393 rendered: Some(rendered),
8394 }
8395 };
8396 let files = [
8397 make("first.rs", "pub fn f(n: u32) -> bool { n >= 4 }", 0),
8398 make("second.rs", "pub fn g(a: u8, b: u8) -> bool { a < b }", 100),
8399 ];
8400 let rendered = files[1].rendered.as_ref().unwrap();
8401 let probe = rendered.text.find("__tmt_rt::").unwrap();
8402 let blamed = rendered.inserted_by(probe).unwrap();
8403 assert!(blamed >= 100, "{blamed}");
8404 let error = CompileError {
8405 primary: vec![ErrorSpan {
8406 file: "second.rs".to_string(),
8407 byte_start: probe,
8408 line: 1,
8409 }],
8410 secondary: vec![],
8411 rendered: String::new(),
8412 };
8413 assert_eq!(blame_error(&error, &files, copy, &HashSet::new()), [blamed]);
8414 }
8415
8416 #[test]
8417 fn modules_are_followed_to_files_that_exist_in_the_copy() {
8418 let scratch = scratch("module-files");
8419 let copy = scratch.join("work/src");
8420 let library = copy.join("lib.rs");
8421 let directory_module = copy.join("nested/mod.rs");
8422 let outside = scratch.join("work/outside.rs");
8423 let sources = BTreeMap::from([
8424 (
8425 library.clone(),
8426 r#"mod nested; #[path = "../outside.rs"] mod outside;"#,
8427 ),
8428 (directory_module.clone(), "fn nested() {}"),
8429 (outside.clone(), "fn outside() {}"),
8430 ]);
8431 for path in sources.keys() {
8432 fs::create_dir_all(path.parent().unwrap()).unwrap();
8433 fs::File::create(path).unwrap();
8434 }
8435 let graph = source_graph([(library.clone(), true)], ©, |path| {
8436 Ok(sources.get(path).map(|source| (*source).to_string()))
8437 })
8438 .unwrap();
8439 fs::remove_dir_all(scratch).unwrap();
8440 assert_eq!(
8443 graph.keys().collect::<Vec<_>>(),
8444 [&library, &directory_module]
8445 );
8446 }
8447
8448 #[test]
8449 fn an_empty_directory_the_run_asked_for_is_not_pruned() {
8450 let dir = scratch("prune-kept-directory");
8451 let copy = dir.join("work/src");
8452 fs::create_dir(copy.join("fixture")).unwrap();
8453 fs::create_dir(copy.join("stale")).unwrap();
8454 let state = WorkCopy::open(&dir.join("work"), ©);
8455 state.kept.borrow_mut().insert(copy.join("fixture"));
8457 prune(©, &state).unwrap();
8458 assert!(copy.join("fixture").is_dir());
8459 assert!(!copy.join("stale").exists());
8460 fs::remove_dir_all(dir).unwrap();
8461 }
8462
8463 #[test]
8464 fn pool_with_one_worker_runs_nothing_after_the_first_error() {
8465 use std::sync::atomic::{AtomicUsize, Ordering};
8466 let calls = AtomicUsize::new(0);
8467 let failed = run_pool(3, 1, |index| {
8468 calls.fetch_add(1, Ordering::SeqCst);
8469 if index == 0 {
8470 Err(anyhow!("job {index} broke"))
8471 } else {
8472 Ok(index)
8473 }
8474 });
8475 assert_eq!(failed.unwrap_err().to_string(), "job 0 broke");
8476 assert_eq!(calls.load(Ordering::SeqCst), 1);
8477 }
8478
8479 #[test]
8480 fn a_checkpoint_gets_every_verdict_once_it_is_final() {
8481 use std::sync::atomic::{AtomicUsize, Ordering};
8482 let dir = scratch("checkpointed-verdicts");
8483 let keys = || vec!["first".to_string(), "second".to_string()];
8484 for serial in [false, true] {
8485 let checkpoint = Checkpoint::open(&dir.join(format!("checkpoint-{serial}"))).unwrap();
8486 let runs = AtomicUsize::new(0);
8487 let run = |index: usize, sharing: usize| {
8489 runs.fetch_add(1, Ordering::SeqCst);
8490 let timed_out = index == 0 && sharing > 1;
8491 Ok(JobResult {
8492 first_pass_timeout: false,
8493 unconfirmed_timeout: false,
8494 survived: (!timed_out).then(|| vec![index.to_string()]),
8495 timed_out,
8496 unable: false,
8497 })
8498 };
8499 checkpoint.start("campaign", serde_json::json!({})).unwrap();
8500 let phase = checkpoint.begin("mutants", "context", keys()).unwrap();
8501 let results = evaluate_jobs(2, 2, serial, false, "test", Some(&phase), &run).unwrap();
8504 assert_eq!(runs.load(Ordering::SeqCst), if serial { 3 } else { 2 });
8505 assert_eq!(results[0].unconfirmed_timeout, !serial);
8506 assert_eq!(results[0].survived.is_some(), serial);
8507 checkpoint.finish().unwrap();
8509
8510 checkpoint.start("campaign", serde_json::json!({})).unwrap();
8512 let phase = checkpoint.begin("mutants", "context", keys()).unwrap();
8513 let again = evaluate_jobs(2, 2, serial, false, "test", Some(&phase), &run).unwrap();
8514 assert_eq!(again, results);
8515 assert_eq!(runs.load(Ordering::SeqCst), if serial { 3 } else { 2 });
8516 checkpoint.finish().unwrap();
8517 }
8518 fs::remove_dir_all(dir).unwrap();
8519 }
8520}