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