Skip to main content

targeted_mutation/
driver.rs

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