Skip to main content

targeted_mutation/
driver.rs

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