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