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