Skip to main content

targeted_mutation/driver/
mod.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};
16
17use crate::checkpoint::{Checkpoint, Phase};
18use crate::instrument::{self, RUNTIME_MOD, Rendered, Site, SiteKind};
19use crate::output_fixture::{self, Fixture};
20use crate::plan::{self, Mutation};
21use crate::propagation::Change;
22use crate::report::{self, Finding, Report};
23use crate::scope::{self};
24use crate::trace::Trace;
25use crate::work_lock::WorkLock;
26use crate::{git_index, leftovers, progress, reverts, witness};
27
28#[derive(Clone)]
29pub struct Options {
30    /// Directory of the package (or workspace) to analyse.
31    pub dir: PathBuf,
32    pub package: Option<String>,
33    /// Return source candidates without running a build.
34    pub list: bool,
35    /// Run every member's tests against the selected package.
36    pub test_workspace: bool,
37    /// Re-run the tests against one survivor per input gap to confirm the prediction.
38    pub verify: bool,
39    /// Where to put the copy and its build. Default: `<target dir>/tmt`.
40    pub work_dir: Option<PathBuf>,
41    /// Progress lines on stderr.
42    pub progress: bool,
43    /// Analyse only code changed since this git revision (plus untracked files).
44    pub since: Option<String>,
45    /// Analyse only these lines: `FILE:FROM-TO`, with `FILE` relative to the package.
46    pub lines: Vec<String>,
47    /// Package-relative glob patterns of files to exclude from mutation.
48    pub exclude_files: Vec<String>,
49    /// Findings listed in this file are not reported.
50    pub baseline: Option<PathBuf>,
51    /// Write the findings of this run to this file, as a baseline for later runs.
52    pub write_baseline: Option<PathBuf>,
53    /// Other workspace packages whose tests are run too.
54    pub also_test: Vec<String>,
55    /// Run the tests of every workspace package that depends on the analysed one.
56    pub dependents: bool,
57    /// Trace surviving mutants to say what they change in the tests.
58    pub effects: bool,
59    /// Build and run, one by one, the mutants that cannot be switched at run time.
60    pub rebuild: bool,
61    /// Rust expressions used as the payload of a Result error mutation.
62    pub error_values: Vec<String>,
63    pub source_only: bool,
64    pub literal_operators: bool,
65    pub shard: Option<report::Shard>,
66    pub nextest: Option<report::Nextest>,
67    pub test_selection: TestSelection,
68    /// Optimisation level to build the tests with, instead of the profile's own.
69    pub opt_level: Option<u8>,
70    /// Override the time allowed for each test runner under a mutant.
71    pub timeout_seconds: Option<u64>,
72    /// Override the time allowed for each baseline trace invocation.
73    pub baseline_timeout_seconds: Option<u64>,
74    pub baseline_jobs: usize,
75    pub serial_timeout_rechecks: bool,
76    pub wrapper_grace: Duration,
77    /// Run this many surviving mutants against all tests and record the tests twice.
78    pub audit: Option<usize>,
79    /// Cargo's choice of features and of the lock file, the same for every cargo command.
80    pub cargo: CargoConfig,
81    /// How many mutants to run at the same time.
82    pub jobs: usize,
83    /// Copy every file of the workspace, including the ones git ignores.
84    pub all_files: bool,
85    pub git_index: bool,
86    pub copy_fixtures: Vec<PathBuf>,
87    pub copy_fixture_excludes: Vec<PathBuf>,
88    pub output_fixtures: Vec<Fixture>,
89    pub stage_external: Vec<StageExternal>,
90    pub checkpoint: bool,
91    /// Also run the doc tests (slow: rustdoc recompiles them for every mutant they reach).
92    pub doc: bool,
93}
94
95#[derive(Clone, Default)]
96pub struct TestSelection {
97    pub isolate: bool,
98    pub lib: bool,
99    pub bins: bool,
100    pub integration_tests: Vec<String>,
101    pub targets: Vec<String>,
102    pub include: Vec<String>,
103    pub filter: Vec<String>,
104    pub exclude: Vec<String>,
105    pub include_ignored: bool,
106    pub wrapper: Option<PathBuf>,
107}
108
109impl TestSelection {
110    pub(crate) fn has_target_filters(&self) -> bool {
111        self.lib || self.bins || !self.integration_tests.is_empty() || !self.targets.is_empty()
112    }
113
114    fn enabled(&self) -> bool {
115        self.isolate
116            || self.has_target_filters()
117            || !self.include.is_empty()
118            || !self.filter.is_empty()
119            || !self.exclude.is_empty()
120            || self.include_ignored
121            || self.wrapper.is_some()
122    }
123
124    pub(crate) fn matches_test(&self, test: &str, was_ignored: bool) -> bool {
125        if was_ignored && !self.include_ignored {
126            return false;
127        }
128        if self.exclude.iter().any(|name| name == test) {
129            return false;
130        }
131        if !self.include.is_empty() || !self.filter.is_empty() {
132            let exact = self.include.iter().any(|name| name == test);
133            let partial = self.filter.iter().any(|pat| test.contains(pat));
134            if !exact && !partial {
135                return false;
136            }
137        }
138        true
139    }
140}
141
142pub use crate::report::CargoConfig;
143pub use workcopy::StageExternal;
144
145impl CargoConfig {
146    /// The arguments that say the same to `cargo metadata`, `cargo test` and rustdoc.
147    pub fn flags(&self) -> Vec<String> {
148        let mut flags = vec![];
149        if !self.features.is_empty() {
150            flags.extend(["--features".to_string(), self.features.join(",")]);
151        }
152        for (on, flag) in [
153            (self.all_features, "--all-features"),
154            (self.no_default_features, "--no-default-features"),
155            (self.locked, "--locked"),
156        ] {
157            if on {
158                flags.push(flag.to_string());
159            }
160        }
161        flags
162    }
163}
164
165/// How far from an error to look for the probe that caused it (a probe can break type
166/// inference a few lines further down).
167const NEARBY_LINES: usize = 6;
168/// File that marks a directory as tmt's own working directory.
169const WORK_MARKER: &str = ".tmt-work-dir";
170/// Name under which the crate root re-declares `std` for the runtime module.
171const STD_ALIAS: &str = "__tmt_std";
172/// More rebuilds than this means the blame logic is not converging.
173const MAX_REPAIR_ROUNDS: usize = 40;
174/// Above this many tests, run the whole binary instead of passing names.
175const MAX_TEST_FILTERS: usize = 200;
176
177mod cargo;
178mod repair_cache;
179mod runner;
180mod scope_blame;
181mod session;
182mod witness_runner;
183mod workcopy;
184
185use cargo::*;
186use runner::*;
187use scope_blame::*;
188use session::*;
189use witness_runner::*;
190use workcopy::*;
191
192struct SourceFile {
193    /// Path relative to the package directory, for reports.
194    display: String,
195    /// Path inside the working copy.
196    path: PathBuf,
197    owners: BTreeSet<PathBuf>,
198    original: String,
199    lines: scope::LineIndex,
200    sites: Vec<Site>,
201    /// Sites whose mutants are built one by one.
202    rebuild_sites: Vec<Site>,
203    /// Where every site of the file is (line, column, code), also those a run of a part
204    /// leaves out: findings are numbered by these.
205    places: Vec<(usize, usize, String)>,
206    rendered: Option<Rendered>,
207}
208
209fn write_rendered(
210    file: &mut SourceFile,
211    state: &WorkCopy,
212    suffix: &str,
213    disabled: &HashSet<u32>,
214    newly_disabled: &HashSet<u32>,
215) -> Result<()> {
216    if file.rendered.is_none()
217        || file
218            .sites
219            .iter()
220            .any(|site| newly_disabled.contains(&site.id))
221    {
222        file.rendered = Some(instrument::render(&file.original, &file.sites, &|id| {
223            !disabled.contains(&id)
224        }));
225    }
226    let rendered = file.rendered.as_ref().expect("rendered before writing");
227    if suffix.is_empty() {
228        state.write(&file.path, &rendered.text)
229    } else {
230        state.write(&file.path, &format!("{}{suffix}", rendered.text))
231    }
232}
233
234#[derive(Clone, Copy)]
235struct WorkspaceShard {
236    offset: usize,
237    total: usize,
238    member_total: usize,
239}
240
241struct CatalogueSnapshot {
242    path: PathBuf,
243    ready: std::cell::Cell<bool>,
244    _lock: WorkLock,
245}
246
247struct WorkspaceBatch<'a> {
248    metadata: &'a Metadata,
249    work: &'a Path,
250    catalogue: Option<CatalogueSnapshot>,
251}
252
253/// Returns the Cargo package name that `run` would select for `dir` when no `--package`
254/// is given (including a single-member virtual workspace with glob `members`).
255pub fn select_single_package_name(dir: &Path, cargo: &CargoConfig) -> Option<String> {
256    let canon = dir.canonicalize().ok()?;
257    let metadata = cargo_metadata(&canon, cargo).ok()?;
258    metadata
259        .packages
260        .iter()
261        .find(|p| p.manifest_path.parent() == Some(canon.as_path()))
262        .or(match &metadata.packages[..] {
263            [only] => Some(only),
264            _ => None,
265        })
266        .map(|p| p.name.clone())
267}
268
269/// Collect the original aggregate report for callers that want it.
270pub fn run_packages(options: &Options, names: &[String]) -> Result<Vec<(String, Result<Report>)>> {
271    run_packages_with(options, names, |_, base| Ok(base.clone()))
272}
273
274/// Collect the aggregate report, allowing per-package option customisation (e.g. from `tmt.toml`).
275pub fn run_packages_with(
276    options: &Options,
277    names: &[String],
278    options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
279) -> Result<Vec<(String, Result<Report>)>> {
280    let mut reports = vec![];
281    run_packages_each_with(options, names, options_for_package, |name, result| {
282        reports.push((name, result));
283        Ok(())
284    })?;
285    Ok(reports)
286}
287
288/// Emit each completed package before starting the next one.
289pub fn run_packages_each(
290    options: &Options,
291    names: &[String],
292    completed: impl FnMut(String, Result<Report>) -> Result<()>,
293) -> Result<()> {
294    run_packages_each_with(options, names, |_, base| Ok(base.clone()), completed)
295}
296
297/// Emit each completed package before starting the next one, resolving per-package options
298/// via `options_for_package`.
299pub fn run_packages_each_with(
300    options: &Options,
301    names: &[String],
302    mut options_for_package: impl FnMut(&str, &Options) -> Result<Options>,
303    mut completed: impl FnMut(String, Result<Report>) -> Result<()>,
304) -> Result<()> {
305    let dir = options
306        .dir
307        .canonicalize()
308        .with_context(|| format!("no such directory: {}", options.dir.display()))?;
309    if dir.is_file() {
310        let given = crate::report::sanitize_inline(&options.dir.display().to_string());
311        bail!(
312            "`{given}` is a file, not a Cargo package directory; pass the workspace/package directory and `--lines <path-relative-to-package-or-workspace>` to analyse a single file"
313        );
314    }
315    let metadata = cargo_metadata(&dir, &options.cargo)?;
316    let all: BTreeSet<_> = metadata.packages.iter().map(|p| p.name.clone()).collect();
317    let selected = if names.is_empty() {
318        all.clone()
319    } else {
320        names.iter().cloned().collect()
321    };
322    if let Some(unknown) = selected.difference(&all).next() {
323        bail!("no package `{unknown}` in the workspace");
324    }
325    if !options.lines.is_empty() {
326        let selected_pkgs: Vec<&Package> = metadata
327            .packages
328            .iter()
329            .filter(|p| selected.contains(&p.name))
330            .collect();
331        validate_workspace_lines(&options.lines, &metadata.workspace_root, &selected_pkgs)?;
332    }
333    let base = options
334        .work_dir
335        .clone()
336        .unwrap_or_else(|| metadata.target_directory.join("tmt-workspace"));
337    fs::create_dir_all(&base).with_context(|| format!("creating {}", base.display()))?;
338    let base = base.canonicalize()?;
339    let workspace_canon = metadata.workspace_root.canonicalize()?;
340    if workspace_canon.starts_with(&base) {
341        bail!(
342            "the work directory {} contains the workspace",
343            base.display()
344        );
345    }
346    let mut member_options = Vec::with_capacity(selected.len());
347    let mut used_work_dirs: Vec<(String, PathBuf)> = Vec::new();
348    for name in selected {
349        let mut member = options_for_package(&name, options)?;
350        member.package = Some(name.clone());
351        let custom_work = member
352            .work_dir
353            .as_ref()
354            .is_some_and(|w| options.work_dir.as_ref() != Some(w));
355        let member_work = if custom_work {
356            let custom = member.work_dir.clone().expect("custom work_dir");
357            fs::create_dir_all(&custom)
358                .with_context(|| format!("creating {}", custom.display()))?;
359            let canon = custom.canonicalize()?;
360            if workspace_canon.starts_with(&canon) {
361                bail!(
362                    "the work directory {} for `{name}` contains the workspace",
363                    canon.display()
364                );
365            }
366            canon
367        } else {
368            base.join(&name)
369        };
370        for (other_name, other_dir) in &used_work_dirs {
371            if member_work == *other_dir
372                || member_work.starts_with(other_dir)
373                || other_dir.starts_with(&member_work)
374            {
375                bail!(
376                    "overlapping work directories for `{name}` ({}) and `{other_name}` ({})",
377                    member_work.display(),
378                    other_dir.display()
379                );
380            }
381        }
382        used_work_dirs.push((name.clone(), member_work.clone()));
383        member.work_dir = Some(member_work);
384        member_options.push((name, member));
385    }
386    let uniform_copy_settings = member_options
387        .first()
388        .map(|(_, first)| {
389            member_options.iter().all(|(_, m)| {
390                m.all_files == first.all_files
391                    && m.git_index == first.git_index
392                    && m.copy_fixtures == first.copy_fixtures
393                    && m.copy_fixture_excludes == first.copy_fixture_excludes
394                    && m.stage_external == first.stage_external
395            })
396        })
397        .unwrap_or(true);
398    let catalogue_dir = base.join(".catalogue");
399    let catalogue = if uniform_copy_settings && (options.list || options.shard.is_some()) {
400        for (name, member_dir) in &used_work_dirs {
401            if *member_dir == catalogue_dir
402                || member_dir.starts_with(&catalogue_dir)
403                || catalogue_dir.starts_with(member_dir)
404            {
405                bail!(
406                    "work directory {} for `{name}` overlaps shared workspace catalogue {}",
407                    member_dir.display(),
408                    catalogue_dir.display()
409                );
410            }
411        }
412        let path = work_directory(&base, ".catalogue")?;
413        Some(CatalogueSnapshot {
414            _lock: WorkLock::take(&path)?,
415            path,
416            ready: std::cell::Cell::new(false),
417        })
418    } else {
419        None
420    };
421    let batch = WorkspaceBatch {
422        metadata: &metadata,
423        work: &base,
424        catalogue,
425    };
426    let Some(shard) = options.shard else {
427        for (name, member) in member_options {
428            crate::interrupt::check()?;
429            let result = run_package(&member, Some(&batch), None);
430            if let Err(err) = &result
431                && crate::interrupt::is_interrupted_err(err)
432            {
433                return Err(crate::interrupt::Interrupted.into());
434            }
435            completed(name, result)?;
436        }
437        return Ok(());
438    };
439    if shard.index >= shard.count || member_options.iter().any(|(_, m)| !m.source_only) {
440        bail!("shards require --source-only and a valid shard index");
441    }
442    // A shard needs the counts of preceding members. For an executing batch
443    // retain counts only: the entire catalogue need not stay in memory.
444    let catalogues: Vec<_> = member_options
445        .into_iter()
446        .map(|(name, member)| {
447            let mut preview = member.clone();
448            preview.list = true;
449            preview.shard = None;
450            preview.progress = false;
451            let catalogue = run_package(&preview, Some(&batch), None).map(|mut report| {
452                let count = report.mutants.as_ref().map_or(0, Vec::len);
453                if !member.list {
454                    report.mutants = None;
455                }
456                (count, report)
457            });
458            (name, member, catalogue)
459        })
460        .collect();
461    let total = catalogues
462        .iter()
463        .filter_map(|(_, _, catalogue)| catalogue.as_ref().ok())
464        .map(|(count, _)| count)
465        .sum();
466    let mut offset = 0;
467    for (name, member, catalogue) in catalogues {
468        let result = catalogue.and_then(|(member_total, mut report)| {
469            let range = WorkspaceShard {
470                offset,
471                total,
472                member_total,
473            };
474            offset += member_total;
475            if member.list {
476                report.analysis.shard = Some(shard);
477                let mut index = range.offset;
478                report
479                    .mutants
480                    .as_mut()
481                    .expect("source catalogue")
482                    .retain(|_| {
483                        let keep = shard.contains(index, total);
484                        index += 1;
485                        keep
486                    });
487                Ok(report)
488            } else {
489                run_package(&member, Some(&batch), Some(range))
490            }
491        });
492        completed(name, result)?;
493    }
494    Ok(())
495}
496
497/// Says at the end of a package, however it ends, what its runs left behind.
498struct LeftoverNote(bool);
499
500impl Drop for LeftoverNote {
501    fn drop(&mut self) {
502        use std::sync::atomic::Ordering;
503        let stopped = leftovers::STOPPED.swap(0, Ordering::Relaxed);
504        let not_stopped = leftovers::NOT_STOPPED.swap(0, Ordering::Relaxed);
505        if let Some(text) = leftover_note(stopped, not_stopped)
506            && self.0
507        {
508            eprintln!("tmt: {text}");
509        }
510    }
511}
512
513fn leftover_note(stopped: usize, not_stopped: usize) -> Option<String> {
514    let stopped = (stopped > 0).then(|| {
515        format!("stopped {stopped} processes that the tests had left running after their run")
516    });
517    let not_stopped = (not_stopped > 0).then(|| {
518        format!(
519            "after {not_stopped} runs something the tests started may still be running \
520             (it could not be found or stopped)"
521        )
522    });
523    match (stopped, not_stopped) {
524        (None, None) => None,
525        (Some(one), None) | (None, Some(one)) => Some(one),
526        (Some(stopped), Some(not_stopped)) => Some(format!("{stopped}; {not_stopped}")),
527    }
528}
529
530pub fn run(options: &Options) -> Result<Report> {
531    run_package(options, None, None)
532}
533
534fn run_package(
535    options: &Options,
536    batch: Option<&WorkspaceBatch<'_>>,
537    workspace_shard: Option<WorkspaceShard>,
538) -> Result<Report> {
539    let _leftovers = LeftoverNote(options.progress);
540    let error_values = validate_package_options(options)?;
541    let selection = &options.test_selection;
542    let effective_jobs = if options.source_only { 1 } else { options.jobs };
543    let note = |text: &str| {
544        if options.progress {
545            eprintln!("tmt: {}", report::sanitize_inline(text));
546        }
547    };
548    let dir = options
549        .dir
550        .canonicalize()
551        .with_context(|| format!("no such directory: {}", options.dir.display()))?;
552    if dir.is_file() {
553        let given = crate::report::sanitize_inline(&options.dir.display().to_string());
554        bail!(
555            "`{given}` is a file, not a Cargo package directory; pass the package directory and `--lines <path-relative-to-package-or-workspace>` to analyse a single file"
556        );
557    }
558
559    let local_metadata;
560    let metadata = if let Some(batch) = batch {
561        batch.metadata
562    } else {
563        local_metadata = cargo_metadata(&dir, &options.cargo)?;
564        &local_metadata
565    };
566    let catalogue = batch
567        .and_then(|batch| batch.catalogue.as_ref())
568        .filter(|_| options.list);
569    let enclosing_package = metadata
570        .packages
571        .iter()
572        .filter(|p| {
573            p.manifest_path
574                .parent()
575                .is_some_and(|root| dir != root && dir.starts_with(root))
576        })
577        .max_by_key(|p| {
578            p.manifest_path
579                .parent()
580                .map_or(0, |root| root.as_os_str().len())
581        });
582    let package = match &options.package {
583        Some(name) => metadata.packages.iter().find(|p| &p.name == name),
584        None => metadata
585            .packages
586            .iter()
587            .find(|p| p.manifest_path.parent() == Some(dir.as_path()))
588            .or(match &metadata.packages[..] {
589                [only] => Some(only),
590                _ => None,
591            }),
592    }
593    .ok_or_else(|| {
594        if let Some(name) = &options.package {
595            anyhow!(
596                "no package `{}` in workspace",
597                crate::report::sanitize_inline(name)
598            )
599        } else if let Some(owner) = enclosing_package {
600            anyhow!(
601                "`{}` is a subdirectory of package `{}` (no Cargo.toml); pass `--package {}` from the workspace/package root (and `--lines <path-relative-to-package-or-workspace>` to narrow files)",
602                crate::report::sanitize_inline(&options.dir.display().to_string()),
603                crate::report::sanitize_inline(&owner.name),
604                crate::report::sanitize_inline(&owner.name),
605            )
606        } else {
607            anyhow!("cannot tell which package to analyse; pass --package <name>")
608        }
609    })?;
610    if options.package.is_none()
611        && !dir.join("Cargo.toml").is_file()
612        && package.manifest_path.parent() != Some(dir.as_path())
613        && options.progress
614    {
615        eprintln!(
616            "tmt: note: `{}` has no Cargo.toml; analysing package `{}` (use `--lines <file>` to scope to specific files)",
617            crate::report::sanitize_inline(&options.dir.display().to_string()),
618            crate::report::sanitize_inline(&package.name),
619        );
620    }
621    // The packages whose tests are built and run: the analysed one, and on request others
622    // of the workspace that use it.
623    let mut test_packages: Vec<&Package> = vec![package];
624    for name in &options.also_test {
625        let other = metadata
626            .packages
627            .iter()
628            .find(|p| &p.name == name)
629            .ok_or_else(|| anyhow!("--also-test: no package `{name}` in the workspace"))?;
630        if !test_packages.iter().any(|p| p.name == other.name) {
631            test_packages.push(other);
632        }
633    }
634    if options.test_workspace {
635        test_packages.extend(
636            metadata
637                .packages
638                .iter()
639                .filter(|other| {
640                    !test_packages
641                        .iter()
642                        .any(|selected| selected.name == other.name)
643                })
644                .collect::<Vec<_>>(),
645        );
646    }
647    if options.dependents {
648        for name in dependents_of(&package.name, &metadata.packages) {
649            if let Some(other) = metadata.packages.iter().find(|p| p.name == name)
650                && !test_packages.iter().any(|p| p.name == other.name)
651            {
652                test_packages.push(other);
653            }
654        }
655    }
656    if !options.list {
657        validate_target_selection(&test_packages, selection)?;
658    }
659    let is_kind = |t: &Target, kinds: &[&str]| t.kind.iter().any(|k| kinds.contains(&k.as_str()));
660    let root_target = package
661        .targets
662        .iter()
663        .find(|t| {
664            is_kind(
665                t,
666                &["lib", "rlib", "cdylib", "staticlib", "dylib", "proc-macro"],
667            )
668        })
669        .or_else(|| package.targets.iter().find(|t| is_kind(t, &["bin"])))
670        .ok_or_else(|| anyhow!("package `{}` has no lib or bin target", package.name))?;
671
672    // 2. Copy the workspace.
673    let PreparedWorkCopy {
674        workspace,
675        work,
676        work_lock,
677        copy,
678        state,
679        external_deps,
680    } = prepare_work_copy(options, metadata, batch, catalogue, &note)?;
681
682    let in_copy = |path: &Path| -> Result<PathBuf> {
683        let canonical = path.canonicalize()?;
684        let relative = canonical
685            .strip_prefix(&workspace)
686            .with_context(|| format!("{} is outside the workspace", path.display()))?;
687        Ok(copy.join(relative))
688    };
689    let package_dir = in_copy(
690        package
691            .manifest_path
692            .parent()
693            .expect("manifest has a parent"),
694    )?;
695    let root_file = in_copy(&root_target.src_path)?;
696    let source_dir = root_file
697        .parent()
698        .expect("source file has a parent")
699        .to_path_buf();
700
701    // 3. Walk all production roots. Other Cargo targets can include a production
702    // module by path, so record them as consumers when deciding what can be probed.
703    let mut roots = BTreeMap::new();
704    for owner in &metadata.packages {
705        for target in &owner.targets {
706            let production = owner.name == package.name && target.is_production();
707            if let Ok(path) = in_copy(&target.src_path)
708                && path.is_file()
709            {
710                let selected = roots.entry(path).or_insert(false);
711                *selected |= production;
712            }
713        }
714    }
715    let paths = source_graph(roots, &copy, |path| state.original(path, &workspace))?;
716    let package_orig_dir = package
717        .manifest_path
718        .parent()
719        .expect("manifest has a parent");
720    let scope = requested_scope(
721        options,
722        &workspace,
723        package_orig_dir,
724        &package.name,
725        batch.is_some(),
726    )?;
727    let mut skipped = vec![];
728    let mut files = vec![];
729    let mut excluded_any = false;
730    let mut next_id = 0u32;
731    let want_witnesses = (options.list || options.rebuild || options.source_only)
732        && root_target.test_build_arg() == Some(("--lib", None));
733    let count_rebuild_witnesses =
734        !want_witnesses && root_target.test_build_arg() == Some(("--lib", None));
735    let mut witness_candidates = vec![];
736    let mut unbuilt_witness_candidates = vec![];
737    for (path, owners) in paths {
738        let Some(original) = state.original(&path, &workspace)? else {
739            continue; // left by an earlier run; gone or rewritten before the build
740        };
741        let display = relative_source(&path, &package_dir).display().to_string();
742        if scope::matches_any_glob(&options.exclude_files, &display) {
743            excluded_any = true;
744            continue;
745        }
746        let selected_file = scope.as_ref().is_none_or(|scope| {
747            let relative = path.strip_prefix(&copy).unwrap_or(&path).to_string_lossy();
748            scope.touches(&relative, 1, usize::MAX)
749        });
750        if !selected_file && path != root_file {
751            continue;
752        }
753        match instrument::parse_source(&original) {
754            Ok(parsed) => {
755                let mut found =
756                    instrument::discover_parsed(&original, &parsed, next_id, &error_values);
757                // A test can be put into a file that the library alone builds.
758                if (want_witnesses || count_rebuild_witnesses)
759                    && selected_file
760                    && owners.consumers.len() == 1
761                    && owners.consumers.contains(&root_file)
762                {
763                    let discovered = witness::discover_parsed(
764                        &original,
765                        &parsed,
766                        want_witnesses && !options.list,
767                    )
768                    .into_iter()
769                    .map(|mut candidate| {
770                        candidate.file = path.clone();
771                        candidate
772                    });
773                    if want_witnesses {
774                        witness_candidates.extend(discovered);
775                    } else {
776                        unbuilt_witness_candidates.extend(discovered);
777                    }
778                    // With `--literal-operators` the mutant that was built is not the
779                    // one these candidates write.
780                    if want_witnesses && !options.list && !options.literal_operators {
781                        witness_candidates.extend(
782                            // Also for what is mutated by building it only (the
783                            // product of two literals).
784                            stronger_assertions(
785                                &original,
786                                &parsed,
787                                found.sites.iter().chain(&found.rebuild_sites),
788                            )
789                            .into_iter()
790                            .map(|mut candidate| {
791                                candidate.file = path.clone();
792                                candidate
793                            }),
794                        );
795                    }
796                }
797                next_id += found.sites.len() as u32;
798                if owners.consumers.len() != 1 || !owners.consumers.contains(&root_file) {
799                    found.rebuild_sites.append(&mut found.sites);
800                }
801                let places = if options.list {
802                    vec![]
803                } else {
804                    found
805                        .sites
806                        .iter()
807                        .chain(&found.rebuild_sites)
808                        .map(|site| (site.line, site.column, report::one_line(&site.text)))
809                        .collect()
810                };
811                files.push(SourceFile {
812                    display,
813                    path,
814                    owners: owners.production,
815                    lines: scope::LineIndex::new(&original),
816                    original,
817                    places,
818                    sites: found.sites,
819                    rebuild_sites: found.rebuild_sites,
820                    rendered: None,
821                });
822            }
823            Err(err) => {
824                if selected_file {
825                    let diagnostic = format!("{err:#}");
826                    note(&format!("skipping {display}: {diagnostic}"));
827                    let end_line = scope::line_of(&original, original.len());
828                    let end_column = original.rsplit('\n').next().unwrap_or("").chars().count() + 1;
829                    skipped.push(report::SkippedSite::new(
830                        report::Location {
831                            file: display,
832                            line: 1,
833                            column: 1,
834                            ..Default::default()
835                        },
836                        (end_line, end_column),
837                        report::SkipReason::UnparseableSource,
838                        Some(diagnostic),
839                    ));
840                }
841            }
842        }
843    }
844
845    // Where the tests of a file changed and nothing else says so, the whole program of
846    // the file is looked at: what they found out before and let through now is theirs.
847    let since_hunks = match options.since.as_deref() {
848        Some(revision) if !options.list && options.shard.is_none() => {
849            scope::hunks(&since_diff(&workspace, revision)?)
850        }
851        _ => vec![],
852    };
853    let mut tests_changed: Vec<(PathBuf, Vec<scope::Hunk>)> = vec![];
854    // Files with a change that is tried undone: they are looked at even with no site.
855    let mut undo_paths: HashSet<PathBuf> = HashSet::new();
856    let mut not_built_reverts: usize = 0;
857    let mut beyond_places: HashSet<(PathBuf, usize, usize)> = HashSet::new();
858    // Only the requested lines, if any were requested.
859    if let Some(scope) = &scope {
860        for file in &mut files {
861            let relative = file
862                .path
863                .strip_prefix(&copy)
864                .unwrap_or(&file.path)
865                .to_string_lossy()
866                .into_owned();
867            let in_scope = |site: &Site| {
868                scope.touches(&relative, file.lines.line_of(site.start), file.lines.line_of(site.end))
869                    // A function is in scope by its signature line too.
870                    || scope.touches(&relative, site.line, site.line)
871            };
872            let of_file: Vec<scope::Hunk> = since_hunks
873                .iter()
874                .filter(|hunk| hunk.file == relative)
875                .cloned()
876                .collect();
877            let changes_count = reverts::changes(&file.original, &of_file).len();
878            if options.rebuild || options.source_only {
879                if changes_count > 0 || reverts::mixed(&file.original, &of_file) > 0 {
880                    undo_paths.insert(file.path.clone());
881                }
882            } else {
883                not_built_reverts += changes_count;
884            }
885            let of_tests = reverts::test_hunks(&file.original, &of_file);
886            if of_tests.is_empty() {
887                file.sites.retain(in_scope);
888            } else {
889                beyond_places.extend(
890                    file.sites
891                        .iter()
892                        .filter(|site| !in_scope(site))
893                        .map(|site| (file.path.clone(), site.start, site.end)),
894                );
895                tests_changed.push((file.path.clone(), of_tests));
896            }
897            file.rebuild_sites.retain(in_scope);
898        }
899        files.retain(|f| {
900            !f.sites.is_empty()
901                || !f.rebuild_sites.is_empty()
902                || f.path == root_file
903                || witness_candidates.iter().any(|c| c.file == f.path)
904                || unbuilt_witness_candidates.iter().any(|c| c.file == f.path)
905                || undo_paths.contains(&f.path)
906        });
907    }
908    if !options.list {
909        for candidate in witness_candidates.iter().filter(|c| !c.existing) {
910            if let Some(file) = files.iter_mut().find(|file| file.path == candidate.file) {
911                let at = witness_location(file, candidate);
912                file.places.push((at.line, at.column, at.code));
913            }
914        }
915    }
916    let witness_in_scope = |candidate: &witness::Candidate| {
917        let Some(file) = files.iter().find(|file| file.path == candidate.file) else {
918            return false;
919        };
920        let relative = file
921            .path
922            .strip_prefix(&copy)
923            .unwrap_or(&file.path)
924            .to_string_lossy();
925        scope.as_ref().is_none_or(|scope| {
926            let site_in_scope = if candidate.edits.len() == 1 {
927                scope.touches(&relative, *candidate.scope.start(), *candidate.scope.end())
928            } else {
929                candidate.edits.iter().any(|edit| {
930                    scope.touches(
931                        &relative,
932                        file.lines.line_of(edit.span.start),
933                        file.lines.line_of(edit.span.end),
934                    )
935                })
936            };
937            site_in_scope
938                || candidate
939                    .signature_lines
940                    .iter()
941                    .any(|&line| scope.touches(&relative, line, line))
942        })
943    };
944    witness_candidates.retain(&witness_in_scope);
945    unbuilt_witness_candidates.retain(&witness_in_scope);
946    let not_built_witnesses = unbuilt_witness_candidates
947        .iter()
948        .filter(|candidate| !candidate.existing)
949        .count();
950
951    let unassessed_test_changes: Vec<String> = if let Some(revision) = options.since.as_deref()
952        && !options.list
953    {
954        let integration_prefixes: Vec<String> = test_packages
955            .iter()
956            .flat_map(|pkg| {
957                let pkg_dir = pkg.manifest_path.parent().unwrap_or(&workspace);
958                let pkg_rel = pkg_dir.strip_prefix(&workspace).ok();
959                let pkg_tests_dir = pkg_rel.map(|rel| {
960                    let s = rel.join("tests").to_string_lossy().replace('\\', "/");
961                    format!("{s}/")
962                });
963                let workspace_ref = &workspace;
964                let explicit_targets = pkg.targets.iter().flat_map(move |t| {
965                    if !t.kind.iter().any(|k| k == "test") {
966                        return vec![];
967                    }
968                    let Ok(rel) = t.src_path.strip_prefix(workspace_ref) else {
969                        return vec![];
970                    };
971                    let mut out = vec![rel.to_string_lossy().replace('\\', "/")];
972                    // Include helper submodules living in a dedicated custom test directory
973                    // (e.g. `[[test]] path = "checks/main.rs"` -> `checks/`), excluding
974                    // the package root itself or `src/`.
975                    if let (Some(parent), Some(pkg_r)) = (rel.parent(), pkg_rel) {
976                        let is_pkg_root = parent == pkg_r;
977                        let is_src = parent == pkg_r.join("src");
978                        if !is_pkg_root && !is_src && !parent.as_os_str().is_empty() {
979                            out.push(format!("{}/", parent.to_string_lossy().replace('\\', "/")));
980                        }
981                    }
982                    out
983                });
984                pkg_tests_dir.into_iter().chain(explicit_targets)
985            })
986            .collect();
987        let is_integration_test = |ws_rel: &str| {
988            ws_rel.ends_with(".rs")
989                && integration_prefixes.iter().any(|prefix| {
990                    if prefix.ends_with('/') {
991                        ws_rel.starts_with(prefix)
992                    } else {
993                        ws_rel == prefix
994                    }
995                })
996        };
997        since_changed_files(&workspace, revision)?
998            .into_iter()
999            .filter(|f| is_integration_test(f))
1000            .collect()
1001    } else {
1002        vec![]
1003    };
1004    let total_sites: usize = files
1005        .iter()
1006        .map(|f| f.sites.len() + f.rebuild_sites.len())
1007        .sum::<usize>()
1008        + witness_candidates
1009            .iter()
1010            .filter(|candidate| !candidate.existing)
1011            .count();
1012    let files_with_sites = files
1013        .iter()
1014        .filter(|f| {
1015            !f.sites.is_empty()
1016                || !f.rebuild_sites.is_empty()
1017                || witness_candidates
1018                    .iter()
1019                    .any(|c| !c.existing && c.file == f.path)
1020        })
1021        .count();
1022    note(&format!(
1023        "{total_sites} sites in {files_with_sites} {}",
1024        if files_with_sites == 1 {
1025            "file"
1026        } else {
1027            "files"
1028        }
1029    ));
1030    if options.source_only {
1031        for file in &mut files {
1032            file.rebuild_sites.append(&mut file.sites);
1033        }
1034    }
1035
1036    let source_mutants = |file: &SourceFile, site: &Site, include_boundary: bool| {
1037        let mut mutants = instrument::source_mutants(site);
1038        if include_boundary {
1039            mutants.extend(instrument::source_boundary_mutant(site));
1040        }
1041        if options.literal_operators {
1042            instrument::literal_operator_mutants(&file.original, site, &mut mutants);
1043        }
1044        instrument::keep_line_ends(&file.original, &mut mutants);
1045        mutants
1046    };
1047    let counts = options.shard.map(|_| {
1048        let regular: usize = files
1049            .iter()
1050            .map(|file| {
1051                file.rebuild_sites
1052                    .iter()
1053                    .map(|site| source_mutants(file, site, true).len())
1054                    .sum::<usize>()
1055            })
1056            .sum();
1057        let total = regular
1058            + witness_candidates
1059                .iter()
1060                .filter(|candidate| !candidate.existing)
1061                .count();
1062        (regular, total)
1063    });
1064    if let (Some(range), Some((_, local_total))) = (workspace_shard, counts)
1065        && range.member_total != local_total
1066    {
1067        bail!("package catalogue changed while preparing its workspace shard");
1068    }
1069    let in_shard = |index| match (options.shard, counts, workspace_shard) {
1070        (Some(shard), _, Some(range)) => shard.contains(range.offset + index, range.total),
1071        (Some(shard), Some((_, total)), _) => shard.contains(index, total),
1072        _ => true,
1073    };
1074    if let Some((mut index, _)) = counts {
1075        witness_candidates.retain(|candidate| {
1076            if candidate.existing {
1077                return true;
1078            }
1079            let selected = in_shard(index);
1080            index += 1;
1081            selected
1082        });
1083    }
1084    let empty_shard = counts.is_some_and(|(_, total)| !(0..total).any(in_shard));
1085
1086    let package_path = package.manifest_path.parent().unwrap_or(Path::new("."));
1087    let mut report_path = repository_prefix(package_path);
1088    if report_path.is_empty()
1089        && batch.is_some()
1090        && let Ok(relative) = package_path.strip_prefix(&workspace)
1091    {
1092        report_path = workspace_report_prefix(relative);
1093    }
1094    let mut report = Report {
1095        package: package.name.clone(),
1096        sites: if empty_shard { 0 } else { total_sites },
1097        analysis: report::Analysis {
1098            package_path: report_path,
1099            since: options.since.clone(),
1100            lines: options.lines.clone(),
1101            exclude_files: options.exclude_files.clone(),
1102            tests_of: test_packages.iter().map(|p| p.name.clone()).collect(),
1103            cargo: options.cargo.clone(),
1104            opt_level: options.opt_level,
1105            timeout_seconds: options.timeout_seconds,
1106            baseline_timeout_seconds: options.baseline_timeout_seconds,
1107            baseline_jobs: (options.baseline_jobs > 1).then_some(options.baseline_jobs),
1108            timeout_recheck: if options.serial_timeout_rechecks {
1109                "serial"
1110            } else {
1111                "none"
1112            },
1113            wrapper_grace_seconds: selection
1114                .wrapper
1115                .as_ref()
1116                .map(|_| options.wrapper_grace.as_secs()),
1117            rebuild: options.rebuild || options.source_only,
1118            verified: options.verify && !options.source_only,
1119            doc_tests: options.doc,
1120            source_only: options.source_only,
1121            literal_operators: options.literal_operators,
1122            shard: options.shard,
1123            nextest: options.nextest.clone(),
1124            error_values: error_values
1125                .iter()
1126                .map(|value| (*value).to_owned())
1127                .collect(),
1128            test_selection: None,
1129            git_index: options.git_index,
1130            copy_fixtures: options.copy_fixtures.clone(),
1131            copy_fixture_excludes: options.copy_fixture_excludes.clone(),
1132            output_fixtures: options.output_fixtures.clone(),
1133            stage_external: options.stage_external.clone(),
1134            checkpoint: (options.checkpoint && !options.list)
1135                .then(|| work.join("checkpoint.jsonl")),
1136        },
1137        skipped,
1138        baseline: if options.list {
1139            None
1140        } else {
1141            options.baseline.clone()
1142        },
1143        unassessed_test_changes,
1144        ..Report::default()
1145    };
1146    if options.list {
1147        if catalogue.is_none() {
1148            state.settle(&workspace)?;
1149        }
1150        let mut candidates = vec![];
1151        let mut index = 0;
1152        for file in &files {
1153            let sites = file
1154                .sites
1155                .iter()
1156                .map(|site| (site, false))
1157                .chain(file.rebuild_sites.iter().map(|site| (site, true)));
1158            for (site, requires_rebuild) in sites {
1159                for mutant in source_mutants(file, site, true) {
1160                    if in_shard(index) {
1161                        candidates.push(report::Candidate {
1162                            what: mutant.what,
1163                            into: mutant.into,
1164                            requires_rebuild,
1165                            edits: vec![candidate_edit(
1166                                file,
1167                                mutant.start,
1168                                mutant.end,
1169                                mutant.replacement,
1170                            )],
1171                        });
1172                    }
1173                    index += 1;
1174                }
1175            }
1176        }
1177        candidates.extend(
1178            witness_candidates
1179                .iter()
1180                .filter(|candidate| !candidate.existing)
1181                .filter_map(|candidate| {
1182                    let file = files.iter().find(|file| file.path == candidate.file)?;
1183                    Some(report::Candidate {
1184                        what: "witness".into(),
1185                        into: candidate.description.clone(),
1186                        requires_rebuild: true,
1187                        edits: candidate
1188                            .edits
1189                            .iter()
1190                            .map(|edit| {
1191                                candidate_edit(
1192                                    file,
1193                                    edit.span.start,
1194                                    edit.span.end,
1195                                    edit.replacement.clone(),
1196                                )
1197                            })
1198                            .collect(),
1199                    })
1200                }),
1201        );
1202        report.mutants = Some(candidates);
1203        return Ok(report);
1204    }
1205    let ws_package_prefix = package_dir
1206        .strip_prefix(&copy)
1207        .unwrap_or(Path::new(""))
1208        .to_string_lossy()
1209        .replace('\\', "/");
1210    let all_files_excluded = excluded_any && files.is_empty();
1211    let is_partial_scope =
1212        scope.is_some() || !options.exclude_files.is_empty() || options.shard.is_some();
1213    if empty_shard
1214        || ((scope.is_some() || all_files_excluded) && total_sites == 0 && undo_paths.is_empty())
1215    {
1216        // Restore files changed by a previous run before reporting a selection with no work.
1217        state.settle(&workspace)?;
1218        if let Some(path) = &options.baseline {
1219            let loaded = crate::baseline::load(path)?;
1220            loaded.validate_for_package(&package.name, path)?;
1221        }
1222        if let Some(path) = &options.write_baseline {
1223            let partial = crate::baseline::PartialScope {
1224                scope: scope.as_ref(),
1225                exclude_files: &options.exclude_files,
1226                preserve_all_existing: true,
1227            };
1228            let single_pkg = batch.is_none().then_some(package.name.as_str());
1229            let summary = crate::baseline::write_scoped(
1230                path,
1231                &package.name,
1232                &ws_package_prefix,
1233                &[],
1234                Some(&partial),
1235                single_pkg,
1236            )?;
1237            if summary.preserved > 0 {
1238                note(&format!(
1239                    "baseline {}: preserved {} out-of-scope entries (no sites evaluated)",
1240                    path.display(),
1241                    summary.preserved
1242                ));
1243            }
1244        }
1245        if !empty_shard {
1246            report.mutants_not_built += not_built_reverts + not_built_witnesses;
1247        }
1248        report.record_evaluation();
1249        if let Some(path) = report.analysis.checkpoint.as_deref() {
1250            let checkpoint = Checkpoint::open(path)?;
1251            let settings =
1252                serde_json::json!({"analysis": &report.analysis, "package": &package.name});
1253            let identity = crate::campaign_identity::compute(&copy, &settings, [], false)?;
1254            checkpoint.start(&identity, settings)?;
1255            checkpoint.finish()?;
1256        }
1257        return Ok(report);
1258    }
1259
1260    // The injected runtime indexes its per-thread arrays by probe ID. Number the
1261    // retained probes together so a narrow scope does not allocate slots for omitted sites.
1262    for (id, site) in files
1263        .iter_mut()
1264        .flat_map(|file| &mut file.sites)
1265        .enumerate()
1266    {
1267        site.id = id as u32;
1268    }
1269    // The sites outside of what changed, looked at for the sake of the tests that did.
1270    let beyond: HashSet<u32> = files
1271        .iter()
1272        .flat_map(|file| {
1273            file.sites
1274                .iter()
1275                .filter(|site| beyond_places.contains(&(file.path.clone(), site.start, site.end)))
1276                .map(|site| site.id)
1277        })
1278        .collect();
1279
1280    let root_source = state
1281        .original(&root_file, &workspace)?
1282        .with_context(|| format!("{} is missing", root_target.src_path.display()))?;
1283    let root_suffix = if options.source_only || files.iter().all(|file| file.sites.is_empty()) {
1284        String::new()
1285    } else {
1286        state.write(
1287            &source_dir.join(format!("{RUNTIME_MOD}.rs")),
1288            crate::RUNTIME_SOURCE,
1289        )?;
1290        let std_alias = format!("extern crate std as {STD_ALIAS};");
1291        if root_source.contains(&std_alias) {
1292            format!("\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1293        } else {
1294            format!("\n#[doc(hidden)]\n{std_alias}\n#[doc(hidden)]\nmod {RUNTIME_MOD};\n")
1295        }
1296    };
1297
1298    // 4. Build, disabling the sites whose probe does not compile (formal/tla/RepairLoop.tla).
1299    let mut disabled: HashSet<u32> = HashSet::new();
1300    let mut repairs = BTreeMap::new();
1301    let build_target = work_directory(&work, "target")?;
1302    let target_flags = test_build_flags(&test_packages, selection, &workspace, &options.cargo);
1303    let build_scope = if target_flags.is_some() {
1304        report::TestBuildScope::SelectedTargets
1305    } else {
1306        report::TestBuildScope::PackageWide
1307    };
1308    let build_note = if selection.has_target_filters() && target_flags.is_none() {
1309        "Cargo is using a package-wide build because the selected test targets cannot be expressed exactly.\n"
1310    } else {
1311        ""
1312    };
1313    if !build_note.is_empty() {
1314        note(build_note.trim_end());
1315    }
1316    // An observation uses only the library's unit-test artifact. The baseline and
1317    // source mutants still need the normal library build to check cfg(not(test)).
1318    let can_build_only_observer = !options.doc
1319        && target_flags.is_none()
1320        && test_packages.len() == 1
1321        && package.targets.len() == 1
1322        && root_target.test
1323        && root_target.test_build_arg() == Some(("--lib", None));
1324    let build_test_binaries = |observer: bool| {
1325        let mut command = Command::new("cargo");
1326        isolate_copy_command(&mut command, &work);
1327        if let Some(lock) = &work_lock {
1328            lock.retain_for(&mut command);
1329        }
1330        command
1331            .args(["test", "--no-run", "--message-format=json"])
1332            .args(test_packages.iter().flat_map(|p| ["-p", p.name.as_str()]))
1333            .args(target_flags.as_deref().unwrap_or_default())
1334            .args((observer && can_build_only_observer).then_some("--lib"))
1335            .args(options.cargo.flags())
1336            .current_dir(&copy)
1337            .env("CARGO_TARGET_DIR", &build_target)
1338            .env("CARGO_BUILD_BUILD_DIR", &build_target)
1339            .envs(profile_env(options.opt_level));
1340        run_cargo_with_progress(&mut command, options.progress && !observer)
1341    };
1342    let cargo_build = || build_test_binaries(false);
1343    let has_probe_sites = !options.source_only && files.iter().any(|f| !f.sites.is_empty());
1344    let repair_fingerprint = has_probe_sites.then(|| {
1345        let test_pkg_names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1346        repair_cache::compute_fingerprint(
1347            &state.root,
1348            &copy,
1349            &workspace,
1350            &state,
1351            &external_deps,
1352            &package.name,
1353            &test_pkg_names,
1354            &options.cargo,
1355            options.opt_level,
1356            target_flags.as_deref(),
1357            &error_values,
1358            options.doc,
1359            &files,
1360        )
1361    });
1362    if let Some(fingerprint) = &repair_fingerprint {
1363        let cached = repair_cache::load(&work, fingerprint);
1364        if !cached.is_empty() {
1365            for entry in cached {
1366                if let Some(file) = files.iter().find(|f| f.display == entry.file)
1367                    && let Some(site) = file.sites.get(entry.site_index)
1368                    && site.start == entry.start
1369                    && site.end == entry.end
1370                    && site.text == entry.text
1371                    && format!("{:?}", site.kind) == entry.kind
1372                {
1373                    disabled.insert(site.id);
1374                    repairs.entry(site.id).or_insert(entry.reason);
1375                }
1376            }
1377            if !disabled.is_empty() {
1378                note(&format!(
1379                    "reusing {} cached repair exclusion(s)",
1380                    disabled.len()
1381                ));
1382            }
1383        }
1384    }
1385    let mut rounds = 0;
1386    let mut newly_disabled = HashSet::new();
1387    let build = loop {
1388        for file in &mut files {
1389            let suffix = if file.path == root_file {
1390                root_suffix.as_str()
1391            } else {
1392                ""
1393            };
1394            write_rendered(file, &state, suffix, &disabled, &newly_disabled)?;
1395        }
1396        if !files.iter().any(|f| f.path == root_file) {
1397            state.write(&root_file, &format!("{root_source}{root_suffix}"))?;
1398        }
1399        if rounds == 0 {
1400            state.settle(&workspace)?;
1401        }
1402        note(if rounds == 0 {
1403            "building the instrumented crate"
1404        } else {
1405            "rebuilding without the sites that failed to compile"
1406        });
1407        let output = cargo_build()?;
1408        let names: Vec<&str> = test_packages.iter().map(|p| p.name.as_str()).collect();
1409        let build = parse_build_output(&String::from_utf8_lossy(&output.stdout), &names);
1410        if output.status.success() {
1411            if let Some(fingerprint) = &repair_fingerprint {
1412                let cached_entries: Vec<repair_cache::CachedSite> = files
1413                    .iter()
1414                    .flat_map(|file| {
1415                        file.sites
1416                            .iter()
1417                            .enumerate()
1418                            .filter(|(_, site)| disabled.contains(&site.id))
1419                            .map(|(site_index, site)| repair_cache::CachedSite {
1420                                file: file.display.clone(),
1421                                site_index,
1422                                start: site.start,
1423                                end: site.end,
1424                                text: site.text.clone(),
1425                                kind: format!("{:?}", site.kind),
1426                                reason: repairs.get(&site.id).cloned().unwrap_or_default(),
1427                            })
1428                    })
1429                    .collect();
1430                let _ = repair_cache::save(&work, fingerprint, &cached_entries);
1431            }
1432            break build;
1433        }
1434        let diagnostics = || {
1435            [
1436                build.diagnostics.join("\n"),
1437                String::from_utf8_lossy(&output.stderr).into_owned(),
1438            ]
1439            .into_iter()
1440            .filter(|part| !part.trim().is_empty())
1441            .collect::<Vec<_>>()
1442            .join("\n")
1443        };
1444        if build.errors.is_empty() {
1445            bail!("the build failed:\n{build_note}{}", diagnostics());
1446        }
1447        if build
1448            .errors
1449            .iter()
1450            .any(|error| is_non_probe_error(error, &files, &copy))
1451        {
1452            bail!(
1453                "the build failed with an error unrelated to instrumentation:\n{build_note}{}",
1454                diagnostics()
1455            );
1456        }
1457        rounds += 1;
1458        let before = disabled.len();
1459        let mut blamed_now: HashSet<u32> = HashSet::new();
1460        for error in &build.errors {
1461            let blamed = blame_error(error, &files, &copy, &disabled);
1462            if std::env::var_os("TMT_DEBUG").is_some() {
1463                eprintln!(
1464                    "tmt: debug: blaming {blamed:?} for\n{}",
1465                    report::sanitize_terminal(&error.rendered)
1466                );
1467            }
1468            for id in blamed {
1469                repairs
1470                    .entry(id)
1471                    .or_insert_with(|| error.rendered.lines().next().unwrap_or("").to_string());
1472                blamed_now.insert(id);
1473            }
1474        }
1475        disabled.extend(blamed_now.iter().copied());
1476        newly_disabled = blamed_now;
1477        if disabled.len() == before || rounds > MAX_REPAIR_ROUNDS {
1478            bail!(
1479                "the crate does not build after instrumentation.\n\
1480                 {build_note}Does `cargo test --no-run` pass on the original for the same targets?\n{}",
1481                diagnostics()
1482            );
1483        }
1484    };
1485    let built_sources = if options.rebuild || options.source_only || options.audit.is_some() {
1486        // A feature can also be turned on behind cargo's back: by compiler flags (in
1487        // the environment or a configuration file) and by a build script.
1488        // Every variable of flags for the compiler: also those of one target
1489        // (`CARGO_TARGET_<TRIPLE>_RUSTFLAGS`).
1490        let behind_cargo = features_from_flags(
1491            std::env::vars_os()
1492                .filter(|(name, _)| name.to_string_lossy().ends_with("RUSTFLAGS"))
1493                .map(|(_, value)| Some(value)),
1494        ) || build.build_scripts.iter().any(|script| {
1495            script["cfgs"].as_array().is_some_and(|cfgs| {
1496                cfgs.iter()
1497                    .any(|cfg| cfg.as_str().is_some_and(|cfg| cfg.contains("feature")))
1498            })
1499        }) || configuration_names_a_feature(
1500            &copy,
1501            std::env::var_os("CARGO_HOME").map(PathBuf::from),
1502        );
1503        BuiltSources::from_artifacts(&build.artifacts, &build.features, !behind_cargo, &copy)
1504    } else {
1505        BuiltSources::default()
1506    };
1507    output_fixture::stage(&workspace, &work, &build_target, &options.output_fixtures)?;
1508    let checkpoint_path = report.analysis.checkpoint.as_deref();
1509    let checkpoint = checkpoint_path.map(Checkpoint::open).transpose()?;
1510    let doc_packages = test_packages
1511        .iter()
1512        .filter(|p| options.doc && p.targets.iter().any(|target| target.doctest));
1513    if build.test_binaries.is_empty() && doc_packages.clone().next().is_none() {
1514        bail!("{build_note}`{}` has no test binaries", package.name);
1515    }
1516
1517    // 5. Trace run: what does each test observe?
1518    let mut session = Session {
1519        progress: options.progress,
1520        serial_timeout_rechecks: options.serial_timeout_rechecks,
1521        package_dir,
1522        binaries: vec![],
1523    };
1524    let wrapper = selection
1525        .wrapper
1526        .as_ref()
1527        .map(|path| {
1528            let relative = wrapper_relative(path)?;
1529            let copied = copy.join(&relative);
1530            if !copied.is_file() {
1531                bail!(
1532                    "test wrapper is missing from the work copy: {}",
1533                    copied.display()
1534                );
1535            }
1536            Ok(copied)
1537        })
1538        .transpose()?;
1539    let mut runners: Vec<(String, Runner, PathBuf)> = vec![];
1540    let root_test_exe = |built: &BuildOutput| {
1541        built
1542            .test_binaries
1543            .iter()
1544            .find(|(name, _, owner, kind)| {
1545                *name == root_target.name && *owner == package.name && *kind == root_target.kind
1546            })
1547            .map(|(_, exe, _, _)| exe.clone())
1548    };
1549    let root_exe = (!witness_candidates.is_empty())
1550        .then(|| root_test_exe(&build))
1551        .flatten();
1552    let mut discovered_tests: Vec<String> = vec![];
1553    let mut empty_bin_targets: Vec<(String, String)> = vec![];
1554    if let Some(nextest) = &options.nextest {
1555        let mut flags: Vec<_> = test_packages
1556            .iter()
1557            .flat_map(|p| ["-p".to_owned(), p.name.clone()])
1558            .collect();
1559        flags.extend(options.cargo.flags());
1560        runners.push((
1561            "nextest".to_owned(),
1562            Runner::Nextest {
1563                copy: copy.clone(),
1564                target_dir: build_target.clone(),
1565                profile: nextest.profile.clone(),
1566                opt_level: options.opt_level,
1567                flags,
1568            },
1569            session.package_dir.clone(),
1570        ));
1571    } else {
1572        for (name, exe, owner, kind) in build.test_binaries {
1573            if !artifact_target_selected(&name, &kind, selection) {
1574                continue;
1575            }
1576            let owner_package = test_packages
1577                .iter()
1578                .find(|p| p.name == owner)
1579                .expect("binaries are filtered by these packages");
1580            let cwd = in_copy(
1581                owner_package
1582                    .manifest_path
1583                    .parent()
1584                    .expect("manifest has a parent"),
1585            )?;
1586            if selection.enabled() {
1587                let all = list_tests(&exe, &cwd, &work, false, true, work_lock.as_deref())?;
1588                if all.is_empty() && kind.first().map(String::as_str) == Some("bin") {
1589                    empty_bin_targets.push((owner.clone(), name.clone()));
1590                }
1591                let ignored = list_tests(&exe, &cwd, &work, true, true, work_lock.as_deref())?;
1592                for test in all {
1593                    let was_ignored = ignored.contains(&test);
1594                    if (!was_ignored || selection.include_ignored)
1595                        && !selection.exclude.iter().any(|name| name == &test)
1596                    {
1597                        discovered_tests.push(test.clone());
1598                    }
1599                    if !selection.matches_test(&test, was_ignored) {
1600                        continue;
1601                    }
1602                    runners.push((
1603                        format!("{owner}::{}::{name}::{test}", kind.join("+")),
1604                        Runner::Isolated {
1605                            exe: exe.clone(),
1606                            test,
1607                            ignored: was_ignored,
1608                            wrapper: wrapper.clone(),
1609                        },
1610                        cwd.clone(),
1611                    ));
1612                }
1613                continue;
1614            }
1615            // Tests of other packages are named after their package.
1616            let name = if owner == package.name {
1617                name
1618            } else {
1619                format!("{owner}::{name}")
1620            };
1621            runners.push((name, Runner::Exe(exe), cwd));
1622        }
1623    }
1624    if selection.enabled() && runners.is_empty() {
1625        let hint = no_tests_matched_hint(
1626            &test_packages,
1627            selection,
1628            &empty_bin_targets,
1629            &discovered_tests,
1630        );
1631        bail!("{build_note}no tests matched the requested selection{hint}");
1632    }
1633    let selected_tests = selection.enabled().then(|| report::TestSelection {
1634        build_scope,
1635        wrapper: selection
1636            .wrapper
1637            .as_ref()
1638            .map(|path| path.display().to_string()),
1639        tests: runners.iter().map(|(name, _, _)| name.clone()).collect(),
1640    });
1641    for owner in doc_packages {
1642        let doc = Runner::Doc {
1643            copy: copy.clone(),
1644            target_dir: build_target.clone(),
1645            package: owner.name.clone(),
1646            opt_level: options.opt_level,
1647            flags: options.cargo.flags(),
1648        };
1649        let name = if owner.name == package.name {
1650            "doc tests".to_owned()
1651        } else {
1652            format!("{}::doc tests", owner.name)
1653        };
1654        let cwd = in_copy(owner.manifest_path.parent().expect("manifest has a parent"))?;
1655        runners.push((name, doc, cwd));
1656    }
1657    report.analysis.test_selection = selected_tests;
1658    let identity = if checkpoint.is_some() {
1659        let mut build_inputs: Vec<_> = build
1660            .build_scripts
1661            .iter()
1662            .map(serde_json::Value::to_string)
1663            .collect();
1664        build_inputs.sort();
1665        // Build script outputs can contain secrets. Only their digest enters
1666        // the checkpoint, never the Cargo event payload.
1667        let settings = serde_json::json!({
1668            "build_scripts": build_inputs,
1669            "analysis": &report.analysis, "package": &package.name, "jobs": effective_jobs,
1670            "verify": options.verify, "audit": options.audit, "effects": options.effects,
1671            "all_files": options.all_files, "build_scope": build_scope,
1672            "runners": runners.iter().map(|(name, runner, cwd)| (name, runner.executable(), cwd)).collect::<Vec<_>>()
1673        });
1674        let mut inputs = BTreeSet::new();
1675        for (root, artifacts) in &build.artifacts {
1676            inputs.insert(root.clone());
1677            if let Some(dependencies) = artifacts
1678                .iter()
1679                .map(|artifact| artifact_inputs(artifact, root, &copy))
1680                .find(|deps| !deps.is_empty())
1681            {
1682                inputs.extend(dependencies);
1683            } else {
1684                // An unfamiliar Cargo output layout cannot hide changed
1685                // compilation inputs behind a stable artifact name.
1686                inputs.extend(artifacts.iter().cloned());
1687            }
1688        }
1689        inputs.extend(
1690            build
1691                .build_scripts
1692                .iter()
1693                .filter_map(|script| script.get("out_dir")?.as_str().map(PathBuf::from)),
1694        );
1695        // The snapshot is already included. The paths outside it include
1696        // dependency sources, generated build inputs, and staged fixtures.
1697        inputs.retain(|path| !path.starts_with(&copy));
1698        inputs.extend(
1699            options
1700                .output_fixtures
1701                .iter()
1702                .map(|fixture| build_target.join(&fixture.to)),
1703        );
1704        inputs.extend(
1705            options
1706                .stage_external
1707                .iter()
1708                .map(|entry| normalize(&copy.join(&entry.rel))),
1709        );
1710        Some(crate::campaign_identity::compute(
1711            &copy,
1712            &settings,
1713            inputs,
1714            options.nextest.is_some(),
1715        )?)
1716    } else {
1717        None
1718    };
1719    // The marks by which a run says that it gave up are made where nothing else makes
1720    // files: the working directory is this analysis's alone while it is locked. A
1721    // directory shared with others (the temporary one, between containers that count
1722    // their processes alike) could hand one run's mark to another.
1723    let marks = marks_dir(&work)?;
1724    let baseline_jobs = if selection.enabled() {
1725        options.baseline_jobs
1726    } else {
1727        1
1728    };
1729    if options.progress {
1730        eprintln!(
1731            "tmt: baselines: 0/{} completed ({} workers)",
1732            runners.len(),
1733            baseline_jobs
1734        );
1735    }
1736
1737    let baseline_budget = options
1738        .baseline_timeout_seconds
1739        .map(Duration::from_secs)
1740        .unwrap_or(DEFAULT_BASELINE_TIMEOUT);
1741    let baseline_stage = if options.source_only {
1742        "baseline_untraced"
1743    } else {
1744        "baseline_trace"
1745    };
1746    let diagnostic_path = work.join("baseline-timeout.json");
1747    let _ = fs::remove_file(&diagnostic_path);
1748    let completed_baselines = std::sync::atomic::AtomicUsize::new(0);
1749    let total_baselines = runners.len();
1750
1751    #[derive(Debug)]
1752    struct BaselineTimeoutError(Box<report::BaselineTimeoutDiagnostic>);
1753
1754    impl std::fmt::Display for BaselineTimeoutError {
1755        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1756            write!(
1757                f,
1758                "baseline timeout in stage `{}` for `{}`",
1759                self.0.stage, self.0.runner
1760            )
1761        }
1762    }
1763
1764    impl std::error::Error for BaselineTimeoutError {}
1765
1766    let baseline_result = progress::track_baselines(options.progress, runners.len(), |progress| {
1767        run_pool(runners.len(), baseline_jobs, |slot| {
1768            let index = slot;
1769            let (name, runner, cwd) = runners[index].clone();
1770            let result = (|| {
1771                let trace_path = work.join(format!("trace-{index}.tsv"));
1772                let _ = fs::remove_file(&trace_path);
1773                let mut bin = TestBinary {
1774                    name,
1775                    cwd,
1776                    marks: marks.clone(),
1777                    git_ceiling: work.clone(),
1778                    work_lock: work_lock.clone(),
1779                    tests: BTreeSet::new(),
1780                    runner,
1781                    baseline: Duration::ZERO,
1782                    untraced_baseline: None,
1783                    timeout_diagnostic: std::sync::Once::new(),
1784                    traced: Duration::ZERO,
1785                    timeout: options.timeout_seconds.map(Duration::from_secs),
1786                    wrapper_grace: options.wrapper_grace,
1787                    report_slow: options.progress,
1788                    filtered_timings: Default::default(),
1789                    trace: Trace::default(),
1790                    effects_baseline: std::sync::OnceLock::new(),
1791                };
1792                session.note(&format!("tracing `{}`", bin.name));
1793                let started = Instant::now();
1794                let trace_env = trace_path.to_string_lossy().into_owned();
1795                let trace = [("TMT_TRACE", trace_env.as_str())];
1796                match run_baseline(
1797                    &bin,
1798                    if options.source_only { &[] } else { &trace },
1799                    baseline_budget,
1800                    &work.join(format!("baseline-{index}.log")),
1801                    false,
1802                )? {
1803                    BaselineRun::Passed => {}
1804                    BaselineRun::TimedOut { elapsed, log } => {
1805                        let log_path =
1806                            log.unwrap_or_else(|| work.join(format!("baseline-{index}.log")));
1807                        let isolated_test = match &bin.runner {
1808                            Runner::Isolated { test, .. } => Some(test.clone()),
1809                            _ => None,
1810                        };
1811                        let (rerun_args, exclude_args) = match &bin.runner {
1812                            Runner::Isolated { test, .. } => (
1813                                vec!["--include-test".to_string(), test.clone()],
1814                                vec!["--exclude-test".to_string(), test.clone()],
1815                            ),
1816                            Runner::Exe(_) => {
1817                                let target = bin
1818                                    .name
1819                                    .rsplit_once("::")
1820                                    .map_or(bin.name.as_str(), |(_, t)| t)
1821                                    .to_string();
1822                                (vec!["--test-target".to_string(), target], vec![])
1823                            }
1824                            Runner::Nextest { .. } | Runner::Doc { .. } => (vec![], vec![]),
1825                        };
1826                        let completed =
1827                            completed_baselines.load(std::sync::atomic::Ordering::Acquire);
1828                        let diagnostic = report::BaselineTimeoutDiagnostic {
1829                            schema_version: report::SCHEMA_VERSION,
1830                            package: package.name.clone(),
1831                            stage: baseline_stage,
1832                            runner: bin.name.clone(),
1833                            test: isolated_test,
1834                            elapsed_seconds: (elapsed.as_secs_f64() * 1000.0).round() / 1000.0,
1835                            budget_seconds: baseline_budget.as_secs(),
1836                            completed_baselines: completed,
1837                            total_baselines,
1838                            partial_baseline: true,
1839                            log: log_path,
1840                            lines: options.lines.clone(),
1841                            rerun_args,
1842                            exclude_args,
1843                        };
1844                        return Err(BaselineTimeoutError(Box::new(diagnostic)).into());
1845                    }
1846                }
1847                bin.traced = started.elapsed();
1848                bin.baseline = bin.traced;
1849                if options.source_only {
1850                    bin.untraced_baseline = Some(BaselineTiming::Completed(bin.baseline));
1851                }
1852                // Recording slows code in loops down a lot, and the time limit of every mutant
1853                // is a multiple of this: where it matters, time the tests as the mutants run them.
1854                if !options.source_only && bin.traced > SLOW_TRACE {
1855                    let started = Instant::now();
1856                    let passed = matches!(
1857                        run_baseline(
1858                            &bin,
1859                            &[],
1860                            bin.traced,
1861                            &work.join(format!("baseline-{index}-untraced.log")),
1862                            true,
1863                        )?,
1864                        BaselineRun::Passed
1865                    );
1866                    let elapsed = started.elapsed();
1867                    if passed {
1868                        bin.untraced_baseline = Some(BaselineTiming::Completed(elapsed));
1869                        bin.baseline = elapsed;
1870                    } else {
1871                        bin.untraced_baseline = Some(BaselineTiming::StillRunning(bin.traced));
1872                    }
1873                }
1874                // No file means no probe was reached. Anything else unreadable or malformed means
1875                // the evidence is incomplete, and conclusions drawn from it would be wrong.
1876                let text = match fs::read_to_string(&trace_path) {
1877                    Ok(text) => text,
1878                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(),
1879                    Err(err) => bail!("cannot read the trace of `{}`: {err}", bin.name),
1880                };
1881                bin.trace = Trace::parse(&text);
1882                if bin.trace.malformed_lines > 0 {
1883                    bail!(
1884                        "the trace of `{}` has {} malformed lines; not drawing conclusions from it",
1885                        bin.name,
1886                        bin.trace.malformed_lines
1887                    );
1888                }
1889                if let Runner::Exe(exe) = &bin.runner {
1890                    bin.tests =
1891                        list_tests(exe, &bin.cwd, &work, false, false, work_lock.as_deref())?;
1892                }
1893                completed_baselines.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
1894                Ok(bin)
1895            })();
1896            progress.complete(if result.is_ok() {
1897                progress::Outcome::Survived
1898            } else {
1899                progress::Outcome::Failed
1900            });
1901            result
1902        })
1903    });
1904    session.binaries = match baseline_result {
1905        Ok(binaries) => binaries,
1906        Err(err) => match err.downcast::<BaselineTimeoutError>() {
1907            Ok(BaselineTimeoutError(mut diagnostic)) => {
1908                // Record the final completed count after all parallel baseline workers joined
1909                // so stderr and baseline-timeout.json always describe the exact same failure.
1910                diagnostic.completed_baselines =
1911                    completed_baselines.load(std::sync::atomic::Ordering::Acquire);
1912                let write_status = serde_json::to_string_pretty(&diagnostic)
1913                    .map_err(anyhow::Error::from)
1914                    .and_then(|json| {
1915                        use std::io::Write as _;
1916                        static NEXT_DIAG_TMP: std::sync::atomic::AtomicUsize =
1917                            std::sync::atomic::AtomicUsize::new(0);
1918                        let seq = NEXT_DIAG_TMP.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1919                        let tmp = work.join(format!(
1920                            ".baseline-timeout.{}.{seq}.tmp",
1921                            std::process::id()
1922                        ));
1923                        let mut file = fs::OpenOptions::new()
1924                            .write(true)
1925                            .create_new(true)
1926                            .open(&tmp)?;
1927                        if let Err(err) = file
1928                            .write_all(format!("{json}\n").as_bytes())
1929                            .and_then(|()| file.flush())
1930                        {
1931                            drop(file);
1932                            let _ = fs::remove_file(&tmp);
1933                            return Err(err.into());
1934                        }
1935                        drop(file);
1936                        if let Err(rename_err) = fs::rename(&tmp, &diagnostic_path) {
1937                            let _ = fs::remove_file(&tmp);
1938                            return Err(rename_err.into());
1939                        }
1940                        Ok(())
1941                    });
1942                let diag_note = match write_status {
1943                    Ok(()) => format!("diagnostic: {}", diagnostic_path.display()),
1944                    Err(write_err) => format!(
1945                        "failed to write diagnostic {}: {write_err}",
1946                        diagnostic_path.display()
1947                    ),
1948                };
1949                let subject = match &diagnostic.test {
1950                    Some(test) => format!("`{}` (test `{test}`)", diagnostic.runner),
1951                    None => format!("`{}`", diagnostic.runner),
1952                };
1953                let hint =
1954                    if !diagnostic.rerun_args.is_empty() && !diagnostic.exclude_args.is_empty() {
1955                        format!(
1956                            "; rerun separately with `{}` or exclude with `{}`",
1957                            diagnostic.rerun_args.join(" "),
1958                            diagnostic.exclude_args.join(" ")
1959                        )
1960                    } else if !diagnostic.rerun_args.is_empty() {
1961                        format!(
1962                            "; rerun separately with `{}`",
1963                            diagnostic.rerun_args.join(" ")
1964                        )
1965                    } else {
1966                        String::new()
1967                    };
1968                bail!(
1969                    "baseline timeout in stage `{}` for {subject}: elapsed {:.3}s exceeded budget {}s (increase with --baseline-timeout <SECONDS>; completed {}/{} baselines; partial baseline was not used as a complete trace); {diag_note}; log: {}{hint}",
1970                    diagnostic.stage,
1971                    diagnostic.elapsed_seconds,
1972                    diagnostic.budget_seconds,
1973                    diagnostic.completed_baselines,
1974                    diagnostic.total_baselines,
1975                    diagnostic.log.display()
1976                );
1977            }
1978            Err(other) => return Err(other),
1979        },
1980    };
1981
1982    // 6. Plan every site, run the mutants, and put the findings together.
1983    for file in &files {
1984        for site in &file.sites {
1985            if disabled.contains(&site.id) {
1986                let fallback = options.rebuild
1987                    && !matches!(site.kind, SiteKind::Body { .. })
1988                    && !instrument::source_mutants(site).is_empty();
1989                match site.kind {
1990                    SiteKind::Body { .. } => report.unviable_mutants += 1,
1991                    _ if fallback => {}
1992                    _ => report.skipped_sites += 1,
1993                }
1994                report.skipped.push(report::SkippedSite::new(
1995                    report::location(&file.display, site),
1996                    file.lines.position(&file.original, site.end),
1997                    if fallback {
1998                        report::SkipReason::ProbeReplacedBySourceRebuild
1999                    } else {
2000                        report::SkipReason::ProbeCompileError
2001                    },
2002                    repairs.get(&site.id).cloned(),
2003                ));
2004            }
2005        }
2006        if !options.rebuild && !options.source_only {
2007            report.skipped.extend(file.rebuild_sites.iter().map(|site| {
2008                report::SkippedSite::new(
2009                    report::location(&file.display, site),
2010                    file.lines.position(&file.original, site.end),
2011                    report::SkipReason::RequiresSourceRebuild,
2012                    None,
2013                )
2014            }));
2015        }
2016    }
2017    if let (Some(checkpoint), Some(identity)) = (&checkpoint, &identity) {
2018        checkpoint.start(
2019            identity,
2020            serde_json::json!({
2021                "package": &package.name, "analysis": &report.analysis,
2022                "runners": session.binaries.iter().map(|bin| &bin.name).collect::<Vec<_>>(),
2023                "jobs": effective_jobs, "tool_version": env!("CARGO_PKG_VERSION")
2024            }),
2025        )?;
2026    }
2027    let phase = |name: &str, keys: Vec<String>| {
2028        checkpoint
2029            .as_ref()
2030            .zip(identity.as_deref())
2031            .map(|(checkpoint, identity)| checkpoint.begin(name, identity, keys))
2032            .transpose()
2033    };
2034    let probe_phase = |name: &str, jobs: &[Job]| -> Result<Option<Phase<'_>>> {
2035        if checkpoint.is_none() {
2036            return Ok(None);
2037        }
2038        let locations: BTreeMap<_, _> = files
2039            .iter()
2040            .flat_map(|file| {
2041                file.sites
2042                    .iter()
2043                    .map(|site| (site.id, (&file.display, site.line, site.column, &site.text)))
2044            })
2045            .collect();
2046        let keys = jobs
2047            .iter()
2048            .map(|job| {
2049                let tests = job
2050                    .tests
2051                    .iter()
2052                    .map(|(bin, selected)| (&session.binaries[*bin].name, selected))
2053                    .collect::<Vec<_>>();
2054                serde_json::to_string(&(locations.get(&job.site), job.mutation.encode(), tests))
2055            })
2056            .collect::<std::result::Result<Vec<_>, _>>()?;
2057        phase(name, keys)
2058    };
2059    let scratch = work.clone();
2060    let mut jobs: Vec<Job> = vec![];
2061    // Sites whose mutant could not be run as a probe for what it is. With `--rebuild`
2062    // they are built from the source instead; without, they are counted.
2063    let mut not_evaluated: HashSet<u32> = HashSet::new();
2064    let mut site_work: Vec<SiteWork> = vec![];
2065    // `(index of the finding, job of its first surviving mutant)`.
2066    let mut effect_jobs: Vec<(usize, usize)> = vec![];
2067    for file in &files {
2068        // Pre-index active arithmetic and cast-probe spans once per file to avoid O(sites^2)
2069        // linear scans and repeated `syn::parse_str` during site planning.
2070        let mut primitive_arith_spans: HashSet<(usize, usize)> = HashSet::new();
2071        let mut primitive_cmp_spans: HashSet<(usize, usize)> = HashSet::new();
2072        let mut cast_probe_spans: std::collections::HashMap<(usize, usize), (u32, u32)> =
2073            std::collections::HashMap::new();
2074        for other in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2075            if matches!(other.kind, SiteKind::Cmp { .. })
2076                && session
2077                    .binaries
2078                    .iter()
2079                    .any(|b| b.trace.bounds.contains_key(&other.id))
2080            {
2081                primitive_cmp_spans.insert((other.start, other.end));
2082            }
2083            if let SiteKind::Arith { cast_probes, .. } = &other.kind {
2084                let seen = session.merged(|t| t.arith.get(&other.id), plan::ArithObs::merge);
2085                if !seen.opaque && (seen.same || seen.differs || seen.same2 || seen.differs2) {
2086                    primitive_arith_spans.insert((other.start, other.end));
2087                }
2088                for &(slot, start, end) in cast_probes {
2089                    cast_probe_spans
2090                        .entry((start, end))
2091                        .or_insert((other.id, slot));
2092                }
2093            }
2094        }
2095        let primitive = |from: usize, to: usize| {
2096            let Some(mut text) = file.original.get(from..to) else {
2097                return false;
2098            };
2099            let mut start = from;
2100            loop {
2101                let trimmed = text.trim_start();
2102                start += text.len() - trimmed.len();
2103                text = trimmed.trim_end();
2104                if text.starts_with('(')
2105                    && text.ends_with(')')
2106                    && matches!(syn::parse_str::<syn::Expr>(text), Ok(syn::Expr::Paren(_)))
2107                    && let Some(inner) = text
2108                        .strip_prefix('(')
2109                        .and_then(|inner| inner.strip_suffix(')'))
2110                {
2111                    start += 1;
2112                    text = inner;
2113                } else {
2114                    break;
2115                }
2116            }
2117            primitive_arith_spans.contains(&(start, start + text.len()))
2118        };
2119        let cast_bounds = |from: usize, to: usize| -> Option<(i128, i128)> {
2120            let &(owner_id, slot) = cast_probe_spans.get(&(from, to))?;
2121            let mut recorded = session
2122                .binaries
2123                .iter()
2124                .filter_map(|b| b.trace.cast_bounds.get(&(owner_id, slot)));
2125            let first = recorded.next()?;
2126            if recorded.all(|other| other == first) {
2127                *first
2128            } else {
2129                None
2130            }
2131        };
2132        let primitive_cmp = |from: usize, to: usize| primitive_cmp_spans.contains(&(from, to));
2133        for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2134            let plan = match session.plan(
2135                &file.display,
2136                site,
2137                options.verify,
2138                &primitive,
2139                &primitive_cmp,
2140                &cast_bounds,
2141            ) {
2142                // Code that did not change is not said to be unreached here: that takes
2143                // a run of the whole.
2144                Planned::Unreached if beyond.contains(&site.id) => continue,
2145                Planned::Unreached => {
2146                    // A function is one place, however many sites it is.
2147                    let at = report::location(&file.display, site);
2148                    if report.unreached.last() != Some(&at) {
2149                        report.unreached.push(at);
2150                    }
2151                    continue;
2152                }
2153                Planned::Nothing => continue,
2154                Planned::NotEvaluated => {
2155                    not_evaluated.insert(site.id);
2156                    continue;
2157                }
2158                Planned::Plan(plan) => plan,
2159            };
2160            let mut add =
2161                |mutation: Mutation, tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>| {
2162                    jobs.push(session.job(site.id, mutation, tests_of));
2163                    jobs.len() - 1
2164                };
2165            let gaps = plan
2166                .gaps
2167                .into_iter()
2168                .map(
2169                    |PlannedGap {
2170                         finding,
2171                         survivors,
2172                         constant_expr,
2173                     }| {
2174                        // The trace says no test can notice. Confirm by running every test
2175                        // that reaches the site against the listed survivors.
2176                        let confirm = if options.verify {
2177                            survivors
2178                                .into_iter()
2179                                .map(|m| add(m, &*plan.reaching))
2180                                .collect()
2181                        } else {
2182                            vec![]
2183                        };
2184                        (finding, confirm, constant_expr)
2185                    },
2186                )
2187                .collect();
2188            let infected = &plan.infected;
2189            let runs = plan
2190                .run
2191                .iter()
2192                .map(|m| (*m, add(*m, &|bin| infected(bin, *m))))
2193                .collect();
2194            site_work.push(SiteWork {
2195                file: &file.display,
2196                site,
2197                gaps,
2198                constant: plan.constant,
2199                cannot_differ: plan.cannot_differ,
2200                redundant_logic_swap: plan.redundant_logic_swap,
2201                runs,
2202            });
2203        }
2204    }
2205    session.note(&format!(
2206        "running {} mutants on {} thread(s)",
2207        jobs.len(),
2208        options.jobs.max(1)
2209    ));
2210    let probe_checkpoint = probe_phase("probe", &jobs)?;
2211    let mut results =
2212        session.run_jobs(&jobs, options.jobs, "mutants", probe_checkpoint.as_ref())?;
2213    for result in &results {
2214        report.timeout_rechecks.include(result);
2215    }
2216
2217    // 6b. On request, check what the run rests on: that the tests chosen for a mutant
2218    // are the ones that could fail with it, and that the tests do the same twice.
2219    if let Some(wanted) = options.audit {
2220        report.audit = Some(run_audit_phase(
2221            &session,
2222            &files,
2223            &jobs,
2224            &mut results,
2225            &mut report.timeout_rechecks,
2226            &scratch,
2227            wanted,
2228            options.jobs,
2229            &probe_phase,
2230        )?);
2231    }
2232    // 6c. In code that did not change, a mutant that passes says something about this
2233    // change only if the tests as they were found it out. They are built once, with
2234    // the program as it is, and run against those mutants.
2235    #[derive(Clone, Copy, PartialEq, Eq)]
2236    enum EarlierVerdict {
2237        Killed,
2238        Survived,
2239        Unknown,
2240    }
2241    let mut earlier_verdict: BTreeMap<usize, EarlierVerdict> = BTreeMap::new();
2242    let asked: Vec<usize> = site_work
2243        .iter()
2244        .filter(|item| beyond.contains(&item.site.id))
2245        .flat_map(|item| {
2246            item.gaps
2247                .iter()
2248                .flat_map(|(_, confirm, _)| confirm.iter().copied())
2249                .chain(
2250                    item.runs
2251                        .iter()
2252                        .filter(|(m, _)| !(*m == Mutation::LogicSwap && item.redundant_logic_swap))
2253                        .map(|(_, job)| *job),
2254                )
2255        })
2256        .filter(|job| results[*job].survived.is_some())
2257        .collect();
2258    if !asked.is_empty() {
2259        let revision = report::short_revision(options.since.as_deref().unwrap_or_default());
2260        session.note(&format!(
2261            "running {} surviving mutants against the tests as they were at {revision}",
2262            asked.len()
2263        ));
2264        let suffix = |file: &SourceFile| {
2265            if file.path == root_file {
2266                root_suffix.as_str()
2267            } else {
2268                ""
2269            }
2270        };
2271        // The instrumented files with the old lines of their tests.
2272        let earlier: Option<Vec<(&SourceFile, String)>> = tests_changed
2273            .iter()
2274            .map(|(path, hunks)| {
2275                let file = files.iter().find(|file| file.path == *path)?;
2276                let rendered = file.rendered.as_ref()?;
2277                let mut places = hunks
2278                    .iter()
2279                    .map(|hunk| {
2280                        let (from, to) = scope::range_of(&file.original, hunk);
2281                        Some((rendered.copied(from, to)?, hunk.old.as_str()))
2282                    })
2283                    .collect::<Option<Vec<_>>>()?;
2284                places.sort_by_key(|((from, _), _)| std::cmp::Reverse(*from));
2285                let mut text = rendered.text.clone();
2286                for ((from, to), old) in places {
2287                    text.replace_range(from..to, old);
2288                }
2289                Some((file, text))
2290            })
2291            .collect();
2292        let attempted = if let Some(earlier) = earlier {
2293            let attempted = (|| -> Result<Option<Vec<JobResult>>> {
2294                for (file, text) in &earlier {
2295                    state.write(&file.path, &format!("{text}{}", suffix(file)))?;
2296                }
2297                if !cargo_build()?.status.success() {
2298                    session.note(
2299                        "the tests as they were do not build with the code as it is: what they found out is not known",
2300                    );
2301                    return Ok(None);
2302                }
2303                // They have to pass as they are, or a failure says nothing of a mutant.
2304                let all: Vec<&TestBinary> = session.binaries.iter().collect();
2305                if run_source_tests(&all)? != Outcome::Pass {
2306                    session.note(
2307                        "the tests as they were fail on the code as it is: what they found out is not known",
2308                    );
2309                    return Ok(None);
2310                }
2311                let against_all: Vec<Job> = asked
2312                    .iter()
2313                    .map(|job| Job {
2314                        site: jobs[*job].site,
2315                        mutation: jobs[*job].mutation,
2316                        tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
2317                    })
2318                    .collect();
2319                session
2320                    .run_jobs(&against_all, options.jobs, "mutants, earlier tests", None)
2321                    .map(Some)
2322            })();
2323            // The files and the binaries as they were, whatever went wrong.
2324            for (file, _) in &earlier {
2325                let rendered = file.rendered.as_ref().expect("rendered before building");
2326                state.write(&file.path, &format!("{}{}", rendered.text, suffix(file)))?;
2327            }
2328            if !cargo_build()?.status.success() {
2329                bail!("the crate does not build once its tests are put back as they are");
2330            }
2331            attempted
2332        } else {
2333            session.note(
2334                "not all changed test files could be restored as they were: what they found out is not known",
2335            );
2336            Ok(None)
2337        };
2338        if let Some(again) = attempted? {
2339            for (job, result) in asked.iter().zip(again) {
2340                let verdict = if result.unable || result.unconfirmed_timeout {
2341                    EarlierVerdict::Unknown
2342                } else if result.survived.is_none() {
2343                    EarlierVerdict::Killed
2344                } else {
2345                    EarlierVerdict::Survived
2346                };
2347                earlier_verdict.insert(*job, verdict);
2348            }
2349        } else {
2350            for job in &asked {
2351                earlier_verdict.insert(*job, EarlierVerdict::Unknown);
2352            }
2353        }
2354    }
2355    let unable = results
2356        .iter()
2357        .filter(|r| r.unable || r.unconfirmed_timeout)
2358        .count();
2359    not_evaluated.extend(
2360        jobs.iter()
2361            .zip(&results)
2362            .filter(|(_, result)| result.unable || result.unconfirmed_timeout)
2363            .map(|(job, _)| job.site),
2364    );
2365    if !options.rebuild {
2366        report.mutants_not_evaluated = not_evaluated.len();
2367    }
2368    report.mutants_run = results.len() - unable;
2369    report.mutants_killed = results.iter().filter(|r| r.survived.is_none()).count() - unable;
2370    report.mutants_survived = report.mutants_run - report.mutants_killed;
2371    report.mutants_timed_out = results
2372        .iter()
2373        .filter(|r| r.timed_out && !r.unconfirmed_timeout)
2374        .count();
2375
2376    // Parallel to `report.findings`: how many executed surviving mutants each finding
2377    // represents (`0` for unverified predicted input gaps under `--no-verify`).
2378    let mut finding_run_survivors: Vec<usize> = vec![];
2379
2380    // Expressions known to be constant in the tests: comparisons with a confirmed
2381    // one-sided gap or that cannot differ at all, and `&&` / `||` with a single value.
2382    let confirmed = |w: &SiteWork| {
2383        w.gaps
2384            .iter()
2385            .all(|(_, confirm, _)| confirm.iter().all(|j| results[*j].survived.is_some()))
2386    };
2387    let constants: BTreeSet<(&str, usize, usize)> = site_work
2388        .iter()
2389        .filter(|w| w.cannot_differ || (w.constant && confirmed(w)))
2390        .map(|w| (w.file, w.site.start, w.site.end))
2391        .collect();
2392    for item in &site_work {
2393        let at = report::location(item.file, item.site);
2394        for (finding, confirm, constant_expr) in &item.gaps {
2395            // Already said by the site of the expression itself (or, for a comparison that
2396            // cannot differ, not worth saying at all).
2397            let repeats = constant_expr
2398                .is_some_and(|(start, end)| constants.contains(&(item.file, start, end)));
2399            let survived_count = confirm
2400                .iter()
2401                .filter(|j| results[**j].survived.is_some())
2402                .count();
2403            if beyond.contains(&item.site.id) {
2404                // Said only when the tests found it out before their change.
2405                let confirmed = confirm.iter().all(|j| results[*j].survived.is_some());
2406                let killed_before = confirm
2407                    .iter()
2408                    .any(|j| earlier_verdict.get(j) == Some(&EarlierVerdict::Killed));
2409                if confirmed && !repeats && killed_before {
2410                    report.weakened.push(finding.at().clone());
2411                    report.findings.push(finding.clone());
2412                    finding_run_survivors.push(survived_count);
2413                } else if !confirmed {
2414                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2415                } else if repeats {
2416                    report.survivor_breakdown.redundant_constant += survived_count;
2417                } else {
2418                    for job in confirm {
2419                        if results[*job].survived.is_some() {
2420                            if earlier_verdict.get(job) == Some(&EarlierVerdict::Survived) {
2421                                report.survivor_breakdown.preexisting_unchanged += 1;
2422                            } else {
2423                                report.survivor_breakdown.unchanged_not_compared += 1;
2424                            }
2425                        }
2426                    }
2427                }
2428                continue;
2429            }
2430            match Prediction::of(confirm.iter().map(|j| &results[*j])) {
2431                Prediction::Refuted => {
2432                    report.unstable.push(at.clone());
2433                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2434                }
2435                Prediction::Confirmed if !repeats => {
2436                    report.findings.push(finding.clone());
2437                    finding_run_survivors.push(survived_count);
2438                }
2439                Prediction::Confirmed => {
2440                    report.survivor_breakdown.redundant_constant += survived_count;
2441                }
2442                // Not evaluated (counted above), or said elsewhere.
2443                Prediction::Unknown => {
2444                    report.survivor_breakdown.unconfirmed_gap += survived_count;
2445                }
2446            }
2447        }
2448        // A body that is one expression, constant in the tests: replacing the body by
2449        // that constant was said at the expression (or cannot be told apart at all).
2450        if let SiteKind::Body {
2451            sole_expr: Some((start, end)),
2452            ..
2453        } = item.site.kind
2454            && constants.contains(&(item.file, start, end))
2455        {
2456            report.survivor_breakdown.redundant_constant += item
2457                .runs
2458                .iter()
2459                .filter(|(_, job)| results[*job].survived.is_some())
2460                .count();
2461            continue;
2462        }
2463        let mut survivors = vec![];
2464        let mut passing_tests = BTreeSet::new();
2465        for (mutation, job) in &item.runs {
2466            if let Some(tests) = &results[*job].survived {
2467                if *mutation == Mutation::LogicSwap && item.redundant_logic_swap {
2468                    report.survivor_breakdown.redundant_constant += 1;
2469                    continue;
2470                }
2471                if beyond.contains(&item.site.id) {
2472                    match earlier_verdict.get(job) {
2473                        Some(EarlierVerdict::Killed) => {}
2474                        Some(EarlierVerdict::Survived) => {
2475                            report.survivor_breakdown.preexisting_unchanged += 1;
2476                            continue;
2477                        }
2478                        Some(EarlierVerdict::Unknown) | None => {
2479                            report.survivor_breakdown.unchanged_not_compared += 1;
2480                            continue;
2481                        }
2482                    }
2483                }
2484                survivors.push(report::describe(item.site, *mutation));
2485                passing_tests.extend(tests.iter().cloned());
2486            }
2487        }
2488        if !survivors.is_empty() {
2489            // The first survivor is traced below to see what it changes.
2490            let first = item.runs.iter().find(|(mutation, job)| {
2491                !(*mutation == Mutation::LogicSwap && item.redundant_logic_swap)
2492                    && results[*job].survived.is_some()
2493                    && (!beyond.contains(&item.site.id)
2494                        || earlier_verdict.get(job) == Some(&EarlierVerdict::Killed))
2495            });
2496            if beyond.contains(&item.site.id) {
2497                report.weakened.push(at.clone());
2498            }
2499            effect_jobs.push((report.findings.len(), first.expect("a survivor").1));
2500            finding_run_survivors.push(survivors.len());
2501            report.findings.push(Finding::AssertionGap {
2502                at,
2503                survivors,
2504                tests: passing_tests.into_iter().collect(),
2505                effects: vec![],
2506                effects_of: None,
2507                witness: None,
2508            });
2509        }
2510    }
2511
2512    // 7. What do the surviving mutants change in the tests that let them through?
2513    if options.effects && !effect_jobs.is_empty() {
2514        run_effects_phase(
2515            &session,
2516            &files,
2517            &jobs,
2518            &effect_jobs,
2519            &scratch,
2520            options.jobs,
2521            &mut report.findings,
2522        )?;
2523    }
2524
2525    // 7b. What a probe cannot be put in is mutated in the source, built and run: code in
2526    // a `const fn`, and the sites whose probe did not compile.
2527    // The last of the four: for an audit, the job that ran the same mutant as a probe.
2528    let mut built: Vec<(&SourceFile, &Site, instrument::SourceMutant, Option<usize>)> = vec![];
2529    let build_regular_mutants = options.rebuild || options.source_only;
2530    let mut index = 0;
2531    for file in &files {
2532        // Tried again as the source says them: what did not compile as a probe, and
2533        // what a probe could not be (a range that ends at the top of its type).
2534        let retried = file.sites.iter().filter(|site| {
2535            (disabled.contains(&site.id) && !matches!(site.kind, SiteKind::Body { .. }))
2536                || not_evaluated.contains(&site.id)
2537        });
2538        for site in file.rebuild_sites.iter().chain(retried) {
2539            let mutants = source_mutants(file, site, true);
2540            if build_regular_mutants {
2541                built.extend(mutants.into_iter().filter_map(|mutant| {
2542                    let selected = in_shard(index);
2543                    index += 1;
2544                    selected.then_some((file, site, mutant, None))
2545                }));
2546            } else {
2547                report.mutants_not_built += mutants.len();
2548            }
2549        }
2550    }
2551    if !build_regular_mutants {
2552        report.mutants_not_built += not_built_witnesses;
2553    }
2554    // An audit also builds some of the mutants that were run as probes, from the source
2555    // as a person would write them, to see whether a probe and the real thing agree.
2556    if let (Some(wanted), Some(audit)) = (options.audit, report.audit.as_mut()) {
2557        let mut twins = vec![];
2558        for file in &files {
2559            for site in file.sites.iter().filter(|s| !disabled.contains(&s.id)) {
2560                // Only integers are known to always have an order.
2561                let integers = session.binaries.iter().all(|bin| {
2562                    let seen = bin.trace.merged(site.id);
2563                    !seen.reached() || seen.valued()
2564                });
2565                let candidates = jobs_for_site(&jobs, site.id);
2566                let job_of = |mutation: Mutation| {
2567                    candidates
2568                        .clone()
2569                        .find(|&index| jobs[index].mutation == mutation)
2570                };
2571                let mut compared = vec![];
2572                let mut mutants = instrument::source_mutants(site);
2573                instrument::keep_line_ends(&file.original, &mut mutants);
2574                for mutant in mutants {
2575                    // The first of the mutations that are this change and that was run.
2576                    let job = mutations_like(site, &mutant, integers)
2577                        .into_iter()
2578                        .find_map(job_of);
2579                    if let Some(job) = job {
2580                        compared.push(job);
2581                        twins.push((file, site, mutant, Some(job)));
2582                    }
2583                }
2584                // A negated comparison that no mutant of the source stands for (on
2585                // floats `<` is not "not `>=`") is compared with the negation written out.
2586                if let (SiteKind::Cmp { op, .. }, Some(job)) =
2587                    (&site.kind, job_of(Mutation::Negate))
2588                    && !compared.contains(&job)
2589                {
2590                    let negated = instrument::SourceMutant {
2591                        start: site.start,
2592                        end: site.end,
2593                        replacement: format!("!({})", site.text),
2594                        what: op.symbol().to_string(),
2595                        into: "!".to_string(),
2596                    };
2597                    twins.push((file, site, negated, Some(job)));
2598                }
2599            }
2600        }
2601        let chosen = spread(twins.len(), wanted);
2602        audit.rebuilt = chosen.len();
2603        let mut twins: Vec<Option<_>> = twins.into_iter().map(Some).collect();
2604        built.extend(chosen.into_iter().filter_map(|nth| twins[nth].take()));
2605    }
2606    let mut by_speed: Vec<&TestBinary> = session.binaries.iter().collect();
2607    by_speed.sort_by_key(|bin| bin.baseline);
2608    // A root replacement removes all of its probes. Other files may still use the runtime.
2609    let root_mutant_suffix = if files.iter().any(|file| {
2610        file.path != root_file
2611            && file
2612                .rendered
2613                .as_ref()
2614                .is_some_and(|rendered| rendered.text != file.original)
2615    }) {
2616        root_suffix.as_str()
2617    } else {
2618        ""
2619    };
2620    if !built.is_empty() {
2621        if options.timeout_seconds.is_some()
2622            && built
2623                .iter()
2624                .any(|(file, _, _, _)| built_sources.contains(file))
2625        {
2626            for bin in &by_speed {
2627                bin.warn_timeout_conflict(None);
2628            }
2629        }
2630        let source_checkpoint = if checkpoint.is_some() {
2631            let keys = built
2632                .iter()
2633                .map(|(file, _, mutation, twin)| {
2634                    serde_json::to_string(&(
2635                        &file.display,
2636                        mutation.start,
2637                        mutation.end,
2638                        &mutation.replacement,
2639                        twin,
2640                    ))
2641                })
2642                .collect::<std::result::Result<Vec<_>, _>>()?;
2643            phase("source", keys)?
2644        } else {
2645            None
2646        };
2647        session.note(&format!(
2648            "building {} mutants one by one (code a probe cannot be put in, or to compare with the probe)",
2649            built.len()
2650        ));
2651        let instrumented = |file: &SourceFile, text: &str, suffix: &str| {
2652            if file.path == root_file {
2653                format!("{text}{suffix}")
2654            } else {
2655                text.to_string()
2656            }
2657        };
2658        // All tests are run against each of them; the quick ones first, since one
2659        // failure is enough.
2660        let mut skipped_targets = BTreeSet::new();
2661        // Per file, the code its builds leave out.
2662        let mut left_out: BTreeMap<&PathBuf, Vec<(usize, usize)>> = BTreeMap::new();
2663        let mut survivors: Vec<(report::Location, Vec<String>)> = vec![];
2664        progress::track(
2665            options.progress,
2666            "source mutants",
2667            built.len(),
2668            |progress| -> Result<()> {
2669                for (index, (file, site, mutant, twin)) in built.iter().enumerate() {
2670                    let cached = source_checkpoint
2671                        .as_ref()
2672                        .map(|phase| phase.get::<Option<Outcome>>(index))
2673                        .transpose()?
2674                        .flatten();
2675                    let left_out = left_out
2676                        .entry(&file.path)
2677                        .or_insert_with(|| built_sources.left_out(file))
2678                        .iter()
2679                        .any(|(from, to)| *from <= site.start && site.end <= *to);
2680                    if left_out || !built_sources.contains(file) {
2681                        if let Some(phase) = source_checkpoint.as_ref().filter(|_| cached.is_none())
2682                        {
2683                            phase.record(index, &Some(Outcome::Unable))?;
2684                        }
2685                        if twin.is_none() {
2686                            report.mutants_not_evaluated += 1;
2687                            report.mutants_not_compiled += 1;
2688                            if skipped_targets.insert((&file.path, site.start, site.end)) {
2689                                report.skipped.push(report::SkippedSite::new(
2690                                    report::location(&file.display, site),
2691                                    file.lines.position(&file.original, site.end),
2692                                    report::SkipReason::SourceNotBuilt,
2693                                    left_out.then(|| {
2694                                        "under a `cfg` that the features of this build turn off"
2695                                            .to_string()
2696                                    }),
2697                                ));
2698                            }
2699                        } else if let Some(audit) = report.audit.as_mut() {
2700                            audit.not_compared += 1;
2701                        }
2702                        progress.complete(progress::Outcome::Unable);
2703                        continue;
2704                    }
2705                    let outcome = if let Some(cached) = cached {
2706                        cached
2707                    } else {
2708                        let mutated = format!(
2709                            "{}{}{}",
2710                            &file.original[..mutant.start],
2711                            mutant.replacement,
2712                            &file.original[mutant.end..]
2713                        );
2714                        // `None`: it does not build. Otherwise what stopped it, if anything did.
2715                        let attempt = || -> Result<Option<Outcome>> {
2716                            state.write(
2717                                &file.path,
2718                                &instrumented(file, &mutated, root_mutant_suffix),
2719                            )?;
2720                            match source_build(&cargo_build()?) {
2721                                SourceBuild::Built => run_source_tests(&by_speed).map(Some),
2722                                SourceBuild::Refused => Ok(None),
2723                                // Nothing is known of the mutant: not one that does not
2724                                // compile, and not one to remember as such.
2725                                SourceBuild::Failed(why) => {
2726                                    session.note(&format!(
2727                                        "a build failed without the compiler refusing the code; its mutant is not evaluated: {why}"
2728                                    ));
2729                                    Ok(Some(Outcome::Unable))
2730                                }
2731                            }
2732                        };
2733                        let attempted = attempt();
2734                        // The file as it was, before another one is changed and whatever went wrong.
2735                        let rendered = file.rendered.as_ref().expect("rendered before building");
2736                        state.write(
2737                            &file.path,
2738                            &instrumented(file, &rendered.text, &root_suffix),
2739                        )?;
2740                        let outcome = attempted?;
2741                        // A run that could not be judged is tried again when the campaign
2742                        // is taken up: only what was established is kept.
2743                        if let Some(phase) = &source_checkpoint
2744                            && outcome != Some(Outcome::Unable)
2745                        {
2746                            phase.record(index, &outcome)?;
2747                        }
2748                        outcome
2749                    };
2750                    progress.complete(outcome.map_or(progress::Outcome::Unable, Into::into));
2751                    if let Some(job) = twin {
2752                        // Only compared: the probe's run is the one that is counted and reported.
2753                        let as_probe = results[*job].survived.is_some();
2754                        let Some(audit) = report.audit.as_mut() else {
2755                            continue;
2756                        };
2757                        // What does not build, what could not be evaluated, and an unconfirmed
2758                        // parallel timeout say nothing about agreement between probe and source.
2759                        match audit_source_comparison(&results[*job], outcome) {
2760                            Some(disagrees) => {
2761                                audit.compared += 1;
2762                                if disagrees {
2763                                    let verdict =
2764                                        |passes: bool| if passes { "passes" } else { "fails" };
2765                                    audit.source_disagreements.push(report::SourceDisagreement {
2766                                        at: report::location(&file.display, site),
2767                                        mutant: report::describe(site, mutation_of(site, mutant)),
2768                                        as_probe: verdict(as_probe).to_string(),
2769                                        built: verdict(!as_probe).to_string(),
2770                                    });
2771                                }
2772                            }
2773                            None => audit.not_compared += 1,
2774                        }
2775                        continue;
2776                    }
2777                    match outcome {
2778                        None => report.unviable_mutants += 1,
2779                        Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2780                        Some(outcome) => {
2781                            report.mutants_run += 1;
2782                            report.mutants_killed += (outcome != Outcome::Pass) as usize;
2783                            report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2784                            report.mutants_survived += (outcome == Outcome::Pass) as usize;
2785                        }
2786                    }
2787                    let survived = outcome == Some(Outcome::Pass);
2788                    if survived {
2789                        let at = report::location(&file.display, site);
2790                        // Nothing but the line ends of what was there.
2791                        let removed = mutant.replacement.trim().is_empty();
2792                        let text = match (&site.kind, removed) {
2793                            (SiteKind::Field { .. }, true) => {
2794                                format!("without the field `{}`", report::one_line(&site.text))
2795                            }
2796                            (
2797                                SiteKind::LiteralSet {
2798                                    receiver, argument, ..
2799                                },
2800                                true,
2801                            ) => format!(
2802                                "without `{}` in `{}.contains({})`",
2803                                report::one_line(&mutant.into),
2804                                report::one_line(receiver),
2805                                report::one_line(argument)
2806                            ),
2807                            _ => report::describe(site, mutation_of(site, mutant)),
2808                        };
2809                        match survivors.last_mut() {
2810                            Some((last, texts)) if *last == at => texts.push(text),
2811                            _ => survivors.push((at, vec![text])),
2812                        }
2813                    }
2814                }
2815                Ok(())
2816            },
2817        )?;
2818        if let Some(phase) = &source_checkpoint {
2819            phase.finish_if_complete()?;
2820        }
2821        for (at, survivors) in survivors {
2822            finding_run_survivors.push(survivors.len());
2823            report.findings.push(Finding::Survivor {
2824                at,
2825                survivors,
2826                witness: None,
2827                change_since: None,
2828                advice: None,
2829            });
2830        }
2831    }
2832
2833    // Each change since the revision, undone: do the tests tell it from what was there?
2834    if let Some(revision) = options
2835        .since
2836        .as_deref()
2837        .filter(|_| !options.list && options.shard.is_none())
2838    {
2839        let hunks = scope::hunks(&since_diff(&workspace, revision)?);
2840        let not_built_changes = std::cell::Cell::new(0usize);
2841        let changed: Vec<(&SourceFile, Vec<reverts::Change>)> = files
2842            .iter()
2843            .filter(|file| built_sources.contains(file) || !options.source_only && !options.rebuild)
2844            .filter_map(|file| {
2845                let relative = file
2846                    .path
2847                    .strip_prefix(&copy)
2848                    .ok()?
2849                    .to_string_lossy()
2850                    .replace('\\', "/");
2851                let of_file: Vec<_> = hunks
2852                    .iter()
2853                    .filter(|hunk| hunk.file == relative)
2854                    .cloned()
2855                    .collect();
2856                let mut changes = reverts::changes(&file.original, &of_file);
2857                // Code this build leaves out (a feature that is off) is the same
2858                // program with its change undone: nothing to try.
2859                if options.rebuild || options.source_only {
2860                    for change in &mut changes {
2861                        // The same program undone, in every build: a `cfg` that
2862                        // changed may turn code on or off.
2863                        change.outside = change.undone.as_deref().is_some_and(|undone| {
2864                            built_sources.same_program(file, &file.original, undone)
2865                        });
2866                    }
2867                    not_built_changes.set(
2868                        not_built_changes.get()
2869                            + changes.iter().filter(|change| change.outside).count(),
2870                    );
2871                }
2872                (!changes.is_empty()).then_some((file, changes))
2873            })
2874            .collect();
2875        let not_built_changes = not_built_changes.get();
2876        report.mutants_not_evaluated += not_built_changes;
2877        report.mutants_not_compiled += not_built_changes;
2878        // Those are not tried alone, and still go back with the others.
2879        let total: usize = changed
2880            .iter()
2881            .map(|(_, changes)| changes.iter().filter(|change| !change.outside).count())
2882            .sum();
2883        // A change of the program and its tests in lines that cannot be told apart
2884        // would be undone with the tests: nothing is said of it.
2885        let mixed: usize = files
2886            .iter()
2887            .map(|file| {
2888                let relative = file
2889                    .path
2890                    .strip_prefix(&copy)
2891                    .unwrap_or(&file.path)
2892                    .to_string_lossy()
2893                    .replace('\\', "/");
2894                let of_file: Vec<_> = hunks
2895                    .iter()
2896                    .filter(|hunk| hunk.file == relative)
2897                    .cloned()
2898                    .collect();
2899                reverts::mixed(&file.original, &of_file)
2900            })
2901            .sum();
2902        if mixed > 0 && (options.rebuild || options.source_only) {
2903            report.mutants_not_evaluated += mixed;
2904            session.note(&format!(
2905                "{mixed} changes are of the program and its tests in the same lines: they are not tried undone"
2906            ));
2907        }
2908        if !(options.rebuild || options.source_only) {
2909            report.mutants_not_built += not_built_reverts;
2910        } else if total > 0
2911            || changed.iter().any(|(_, changes)| {
2912                changes.iter().filter(|change| !change.is_subhunk()).count() > 1
2913            })
2914        {
2915            // Also with nothing to try alone: several changes of code that is left out
2916            // may be a change of the build together.
2917            session.note(&format!(
2918                "building {total} changes undone, one by one (the code as it was at {})",
2919                report::short_revision(revision)
2920            ));
2921            let write = |file: &SourceFile, text: &str, suffix: &str| -> Result<()> {
2922                let suffix = if file.path == root_file { suffix } else { "" };
2923                state.write(&file.path, &format!("{text}{suffix}"))
2924            };
2925            // `None`: it does not build.
2926            let undone = |edits: &[(&SourceFile, &str)]| -> Result<Option<Outcome>> {
2927                let attempted = (|| -> Result<Option<Outcome>> {
2928                    for (file, text) in edits {
2929                        write(file, text, root_mutant_suffix)?;
2930                    }
2931                    Ok(match source_build(&cargo_build()?) {
2932                        SourceBuild::Built => Some(run_source_tests(&by_speed)?),
2933                        SourceBuild::Refused => None,
2934                        SourceBuild::Failed(why) => {
2935                            session.note(&format!(
2936                                "a build failed without the compiler refusing the code; the change undone is not evaluated: {why}"
2937                            ));
2938                            Some(Outcome::Unable)
2939                        }
2940                    })
2941                })();
2942                // The files as they were, whatever went wrong.
2943                for (file, _) in edits {
2944                    let rendered = file.rendered.as_ref().expect("rendered before building");
2945                    write(file, &rendered.text, &root_suffix)?;
2946                }
2947                attempted
2948            };
2949            let mut judged = |outcome: Option<Outcome>, at: report::Location, what: String| {
2950                match outcome {
2951                    None => report.unviable_mutants += 1,
2952                    Some(Outcome::Unable) => report.mutants_not_evaluated += 1,
2953                    Some(outcome) => {
2954                        report.mutants_run += 1;
2955                        report.mutants_killed += (outcome != Outcome::Pass) as usize;
2956                        report.mutants_timed_out += (outcome == Outcome::Timeout) as usize;
2957                        report.mutants_survived += (outcome == Outcome::Pass) as usize;
2958                    }
2959                }
2960                if outcome == Some(Outcome::Pass) {
2961                    finding_run_survivors.push(1);
2962                    report.findings.push(Finding::Survivor {
2963                        at,
2964                        survivors: vec![what],
2965                        witness: None,
2966                        advice: None,
2967                        change_since: Some(revision.to_string()),
2968                    });
2969                }
2970            };
2971            let place = |file: &SourceFile, change: &reverts::Change| report::Location {
2972                file: file.display.clone(),
2973                line: change.line,
2974                column: 1,
2975                code: change.code.clone(),
2976                ..Default::default()
2977            };
2978            // A change that does not build alone may be one part of several that belong
2979            // together: then all of the file's are undone at once, and at last all of all.
2980            let mut stuck_files = 0;
2981            for (file, changes) in &changed {
2982                let mut stuck = false;
2983                let whole_total = changes.iter().filter(|change| !change.is_subhunk()).count();
2984                let whole_alone = changes
2985                    .iter()
2986                    .filter(|change| !change.is_subhunk() && !change.outside)
2987                    .count();
2988                for change in changes.iter().filter(|change| !change.outside) {
2989                    let outcome = match &change.undone {
2990                        Some(text) => undone(&[(file, text.as_str())])?,
2991                        None => None,
2992                    };
2993                    if !change.is_subhunk() {
2994                        stuck |= outcome.is_none();
2995                    }
2996                    judged(outcome, place(file, change), change.describe());
2997                }
2998                // All together: where one does not build alone, and where what is left
2999                // out now is built once the others are undone (a `cfg` that changed
3000                // along with the code under it), which shows as another program with
3001                // those changes undone too than without them.
3002                let whole = reverts::all_undone(&file.original, changes);
3003                let same = |a: &str, b: &str| built_sources.same_program(file, a, b);
3004                let tried: Vec<reverts::Change> = changes
3005                    .iter()
3006                    .filter(|change| !change.outside)
3007                    .cloned()
3008                    .collect();
3009                let left_out_matter = whole_alone < whole_total
3010                    && match (&whole, reverts::all_undone(&file.original, &tried)) {
3011                        (Some(all), Some(without)) => !same(all, &without),
3012                        _ => true,
3013                    };
3014                // And never a program that is the one that is there.
3015                let another = whole
3016                    .as_deref()
3017                    .is_none_or(|all| !same(all, &file.original));
3018                if whole_total > 1 && another && (stuck || left_out_matter) {
3019                    let outcome = match &whole {
3020                        Some(text) => undone(&[(file, text.as_str())])?,
3021                        None => None,
3022                    };
3023                    stuck = outcome.is_none();
3024                    let first_whole = changes
3025                        .iter()
3026                        .find(|change| !change.is_subhunk())
3027                        .unwrap_or(&changes[0]);
3028                    judged(
3029                        outcome,
3030                        place(file, first_whole),
3031                        format!("with all {whole_total} changes to this file undone"),
3032                    );
3033                }
3034                stuck_files += usize::from(stuck);
3035            }
3036            // All files together: where a file's changes do not build even together,
3037            // and where code that is left out changed, which may count only with the
3038            // changes of another file undone.
3039            let with_left_out = changed.iter().any(|(_, changes)| {
3040                changes
3041                    .iter()
3042                    .any(|change| !change.is_subhunk() && change.outside)
3043            });
3044            if (stuck_files > 0 || with_left_out) && changed.len() > 1 {
3045                let whole: Option<Vec<String>> = changed
3046                    .iter()
3047                    .map(|(file, changes)| reverts::all_undone(&file.original, changes))
3048                    .collect();
3049                let same =
3050                    |file: &SourceFile, a: &str, b: &str| built_sources.same_program(file, a, b);
3051                // Never the program that is there: in some file it has to be another.
3052                let another = whole.as_ref().is_none_or(|texts| {
3053                    changed
3054                        .iter()
3055                        .zip(texts)
3056                        .any(|((file, _), text)| !same(file, text, &file.original))
3057                });
3058                // And what is left out has to count: another program with it undone
3059                // too than with the other changes alone.
3060                let left_out_matter = whole.as_ref().is_none_or(|texts| {
3061                    changed.iter().zip(texts).any(|((file, changes), text)| {
3062                        let tried: Vec<reverts::Change> = changes
3063                            .iter()
3064                            .filter(|change| !change.outside)
3065                            .cloned()
3066                            .collect();
3067                        reverts::all_undone(&file.original, &tried)
3068                            .is_none_or(|without| !same(file, text, &without))
3069                    })
3070                });
3071                if another && (stuck_files > 0 || (with_left_out && left_out_matter)) {
3072                    let outcome = match &whole {
3073                        Some(texts) => {
3074                            let edits: Vec<(&SourceFile, &str)> = changed
3075                                .iter()
3076                                .zip(texts)
3077                                .map(|((file, _), text)| (*file, text.as_str()))
3078                                .collect();
3079                            undone(&edits)?
3080                        }
3081                        None => None,
3082                    };
3083                    let (file, changes) = &changed[0];
3084                    judged(
3085                        outcome,
3086                        place(file, &changes[0]),
3087                        format!("with every change undone, in all {} files", changed.len()),
3088                    );
3089                }
3090            }
3091        }
3092    }
3093
3094    // File by file: the test that shows a difference is put at the end of the file the
3095    // candidate is of, where the names of the file are in scope.
3096    let mut witness_files: Vec<&PathBuf> = vec![];
3097    for candidate in &witness_candidates {
3098        if !witness_files.contains(&&candidate.file) {
3099            witness_files.push(&candidate.file);
3100        }
3101    }
3102    for witness_file in witness_files {
3103        let in_root = *witness_file == root_file;
3104        let witness_candidates: Vec<&witness::Candidate> = witness_candidates
3105            .iter()
3106            .filter(|candidate| candidate.file == *witness_file)
3107            .collect();
3108        let file = files
3109            .iter()
3110            .find(|file| file.path == *witness_file)
3111            .expect("witness candidates are of files that are analysed");
3112        let rendered = file.rendered.as_ref().expect("rendered before building");
3113        let left_out_here = built_sources.left_out(file);
3114        let restore = if in_root {
3115            format!("{}{root_suffix}", rendered.text)
3116        } else {
3117            rendered.text.clone()
3118        };
3119        let library_runners: Vec<_> = session
3120            .binaries
3121            .iter()
3122            .filter(|bin| {
3123                root_exe
3124                    .as_deref()
3125                    .is_some_and(|exe| bin.runner.executable() == Some(exe))
3126            })
3127            .collect();
3128        let ignored = library_runners
3129            .iter()
3130            .find_map(|bin| match &bin.runner {
3131                Runner::Exe(exe) => Some(list_tests(
3132                    exe,
3133                    &bin.cwd,
3134                    &bin.git_ceiling,
3135                    true,
3136                    false,
3137                    bin.work_lock.as_deref(),
3138                )),
3139                _ => None,
3140            })
3141            .transpose()?
3142            .unwrap_or_default();
3143        let runner_for = |scenario: &witness::Scenario| {
3144            library_runners.iter().copied().find(|bin| {
3145                scenario
3146                    .source_test
3147                    .as_ref()
3148                    .is_none_or(|required| match &bin.runner {
3149                        // In a file that is a module, the test's name comes after the
3150                        // module's.
3151                        Runner::Exe(_) if !in_root => {
3152                            let inner = format!("::{required}");
3153                            bin.tests
3154                                .iter()
3155                                .any(|test| test.ends_with(&inner) && !ignored.contains(test))
3156                        }
3157                        Runner::Exe(_) => {
3158                            bin.tests.contains(required) && !ignored.contains(required)
3159                        }
3160                        Runner::Isolated { test, .. } if !in_root => {
3161                            test.ends_with(&format!("::{required}"))
3162                        }
3163                        Runner::Isolated { test, .. } => test == required,
3164                        Runner::Doc { .. } | Runner::Nextest { .. } => false,
3165                    })
3166            })
3167        };
3168        let write_edits = |edits: &[witness::Edit]| -> Result<bool> {
3169            let Some(source) = witness::render_edits(&file.original, edits, None) else {
3170                return Ok(false);
3171            };
3172            let suffix = if in_root { root_mutant_suffix } else { "" };
3173            state.write(&file.path, &format!("{source}{suffix}"))?;
3174            Ok(true)
3175        };
3176        let suite = |edits: &[witness::Edit]| -> Result<Option<Outcome>> {
3177            if !write_edits(edits)? {
3178                return Ok(None);
3179            }
3180            Ok(match source_build(&cargo_build()?) {
3181                SourceBuild::Built => Some(run_source_tests(&by_speed)?),
3182                SourceBuild::Refused => None,
3183                SourceBuild::Failed(why) => {
3184                    session.note(&format!(
3185                        "a build failed without the compiler refusing the code; the mutant is not evaluated: {why}"
3186                    ));
3187                    Some(Outcome::Unable)
3188                }
3189            })
3190        };
3191        let compile_observer = |edits: &[witness::Edit]| -> Result<Option<PathBuf>> {
3192            if !write_edits(edits)? {
3193                return Ok(None);
3194            }
3195            let build = build_test_binaries(true)?;
3196            if !build.status.success() {
3197                return Ok(None);
3198            }
3199            let artifacts = parse_build_output(
3200                &String::from_utf8_lossy(&build.stdout),
3201                &[package.name.as_str()],
3202            );
3203            Ok(root_test_exe(&artifacts))
3204        };
3205        let observe = |scenario: &witness::Scenario,
3206                       baseline: &TestBinary,
3207                       edits: &[witness::Edit],
3208                       field_path: Option<&str>,
3209                       expected: Option<&str>|
3210         -> Result<Option<witness::Observation>> {
3211            let test = scenario.test_edit_with_field(
3212                &file.original,
3213                witness::TEST_NAME,
3214                field_path,
3215                expected,
3216            );
3217            let edits: Vec<_> = edits.iter().cloned().chain([test]).collect();
3218            let Some(exe) = compile_observer(&edits)? else {
3219                return Ok(None);
3220            };
3221            observe_witness(
3222                baseline,
3223                exe,
3224                wrapper.as_deref(),
3225                scenario,
3226                witness::TEST_NAME,
3227                expected.is_some(),
3228                in_root,
3229            )
3230        };
3231        let witness_checkpoint = if checkpoint.is_some() {
3232            let keys = witness_candidates
3233                .iter()
3234                .map(|candidate| {
3235                    let edits = candidate
3236                        .edits
3237                        .iter()
3238                        .map(|edit| (&edit.span, &edit.replacement))
3239                        .collect::<Vec<_>>();
3240                    serde_json::to_string(&(&candidate.description, edits))
3241                })
3242                .collect::<std::result::Result<Vec<_>, _>>()?;
3243            let name = if in_root {
3244                "witness".to_string()
3245            } else {
3246                format!("witness:{}", file.display)
3247            };
3248            phase(&name, keys)?
3249        } else {
3250            None
3251        };
3252        let mut survivors = vec![];
3253        let mut claimed = BTreeSet::new();
3254        progress::track(
3255            options.progress,
3256            "source witness mutants",
3257            witness_candidates.len(),
3258            |progress| -> Result<()> {
3259                for (index, candidate) in witness_candidates.iter().copied().enumerate() {
3260                    let cached = witness_checkpoint
3261                        .as_ref()
3262                        .map(|phase| phase.get::<WitnessTrial>(index))
3263                        .transpose()?
3264                        .flatten();
3265                    let at = witness_location(file, candidate);
3266                    // Code this build leaves out has no mutant to run.
3267                    if !built_sources.contains(file)
3268                        || candidate.edits.iter().any(|edit| {
3269                            left_out_here
3270                                .iter()
3271                                .any(|(from, to)| *from <= edit.span.start && edit.span.end <= *to)
3272                        })
3273                    {
3274                        if let Some(phase) =
3275                            witness_checkpoint.as_ref().filter(|_| cached.is_none())
3276                        {
3277                            phase.record(index, &WitnessTrial::Inapplicable)?;
3278                        }
3279                        if !candidate.existing {
3280                            report.mutants_not_evaluated += 1;
3281                            report.mutants_not_compiled += 1;
3282                            let span = &candidate.edits[0].span;
3283                            report.skipped.push(report::SkippedSite::new(
3284                                at,
3285                                file.lines.position(&file.original, span.end),
3286                                report::SkipReason::SourceNotBuilt,
3287                                Some(
3288                                    "under a `cfg` that the features of this build turn off"
3289                                        .to_string(),
3290                                ),
3291                            ));
3292                        }
3293                        progress.complete(progress::Outcome::Unable);
3294                        continue;
3295                    }
3296                    let existing = candidate
3297                        .existing
3298                        .then(|| {
3299                            report.findings.iter().position(|finding| {
3300                                let location = finding.at();
3301                                location.file == at.file
3302                                    && location.line == at.line
3303                                    && location.column == at.column
3304                                    && finding.survivors().contains(&candidate.description)
3305                                    && (candidate.finding_at.is_none()
3306                                        || !matches!(finding, Finding::InputGap { .. }))
3307                            })
3308                        })
3309                        .flatten();
3310                    // One stronger assertion is enough for a finding, but wait until a
3311                    // witness actually verifies before claiming it so later surviving
3312                    // mutants on the same finding still get a turn if an earlier one fails.
3313                    let existing = existing
3314                        .filter(|index| candidate.finding_at.is_none() || !claimed.contains(index));
3315                    let scenarios: Vec<_> = candidate
3316                        .scenarios
3317                        .iter()
3318                        .filter_map(|scenario| {
3319                            runner_for(scenario).map(|runner| (scenario, runner))
3320                        })
3321                        .take(4)
3322                        .collect();
3323                    let paired = candidate.edits.len() > 1;
3324                    if (candidate.existing && (existing.is_none() || scenarios.is_empty()))
3325                        || (paired && scenarios.is_empty())
3326                    {
3327                        if let Some(phase) =
3328                            witness_checkpoint.as_ref().filter(|_| cached.is_none())
3329                        {
3330                            phase.record(index, &WitnessTrial::Inapplicable)?;
3331                        }
3332                        progress.complete(progress::Outcome::Unable);
3333                        continue;
3334                    }
3335                    // A compound survivor is interesting only if each component fails on
3336                    // its own. Test the source edits without any generated witness tests.
3337                    let trial = if let Some(cached) = cached {
3338                        cached
3339                    } else {
3340                        let attempted = (|| -> Result<WitnessTrial> {
3341                            if paired {
3342                                for edit in &candidate.edits {
3343                                    match suite(std::slice::from_ref(edit))? {
3344                                        Some(Outcome::Fail) => {}
3345                                        Some(Outcome::Unable) => {
3346                                            return Ok(WitnessTrial::Evaluated(Outcome::Unable));
3347                                        }
3348                                        _ => return Ok(WitnessTrial::Inapplicable),
3349                                    }
3350                                }
3351                            }
3352                            Ok(suite(&candidate.edits)?
3353                                .map_or(WitnessTrial::Unviable, WitnessTrial::Evaluated))
3354                        })();
3355                        state.write(&file.path, &restore)?;
3356                        let trial = attempted?;
3357                        if let Some(phase) = &witness_checkpoint
3358                            && !matches!(trial, WitnessTrial::Evaluated(Outcome::Unable))
3359                        {
3360                            phase.record(index, &trial)?;
3361                        }
3362                        trial
3363                    };
3364                    let outcome = match trial {
3365                        WitnessTrial::Inapplicable => {
3366                            progress.complete(progress::Outcome::Unable);
3367                            continue;
3368                        }
3369                        WitnessTrial::Unviable => {
3370                            progress.complete(progress::Outcome::Unable);
3371                            report.unviable_mutants += usize::from(!candidate.existing);
3372                            continue;
3373                        }
3374                        WitnessTrial::Evaluated(outcome) => outcome,
3375                    };
3376                    progress.complete(outcome.into());
3377                    if !candidate.existing {
3378                        match outcome {
3379                            Outcome::Unable => report.mutants_not_evaluated += 1,
3380                            Outcome::Pass => {
3381                                report.mutants_run += 1;
3382                                report.mutants_survived += 1;
3383                            }
3384                            Outcome::Fail => {
3385                                report.mutants_run += 1;
3386                                report.mutants_killed += 1;
3387                            }
3388                            Outcome::Timeout => {
3389                                report.mutants_run += 1;
3390                                report.mutants_killed += 1;
3391                                report.mutants_timed_out += 1;
3392                            }
3393                        }
3394                    }
3395                    if outcome == Outcome::Pass {
3396                        survivors.push(WitnessSurvivor {
3397                            candidate,
3398                            at,
3399                            existing,
3400                            scenarios,
3401                        });
3402                    }
3403                }
3404                Ok(())
3405            },
3406        )?;
3407
3408        if let Some(phase) = &witness_checkpoint {
3409            phase.finish()?;
3410        }
3411        let originals = shared_witnesses(
3412            &file.original,
3413            &survivors,
3414            wrapper.as_deref(),
3415            in_root,
3416            compile_observer,
3417            note,
3418        );
3419        if !survivors.is_empty() {
3420            state.write(&file.path, &restore)?;
3421        }
3422        let originals = originals?;
3423
3424        progress::track(
3425            options.progress,
3426            "distinguishing tests",
3427            survivors.len(),
3428            |progress| -> Result<()> {
3429                for (survivor, original) in survivors.into_iter().zip(originals) {
3430                    if survivor.existing.is_some_and(|index| {
3431                        survivor.candidate.finding_at.is_some() && claimed.contains(&index)
3432                    }) {
3433                        progress.complete(progress::Outcome::Unable);
3434                        continue;
3435                    }
3436                    let mut evidence = None;
3437                    let mut original = original;
3438                    for (scenario, baseline) in survivor.scenarios {
3439                        let shared = original.take();
3440                        let distinction = (|| -> Result<_> {
3441                            if let Some(shared) = shared {
3442                                // Keep the harness and test name identical on both sides.
3443                                let edits: Vec<_> = survivor
3444                                    .candidate
3445                                    .edits
3446                                    .iter()
3447                                    .chain(shared.tests.iter())
3448                                    .cloned()
3449                                    .collect();
3450                                if let Some(exe) = compile_observer(&edits)?
3451                                    && let Some(mutant) = observe_witness(
3452                                        baseline,
3453                                        exe,
3454                                        wrapper.as_deref(),
3455                                        scenario,
3456                                        &shared.name,
3457                                        true,
3458                                        in_root,
3459                                    )
3460                                    .ok()
3461                                    .flatten()
3462                                    && mutant.equals_expected == Some(false)
3463                                    // Re-check the preserved original binary after the mutant
3464                                    // run to reject monotonic external-state drift without rebuilding.
3465                                    && observe_witness(
3466                                        baseline,
3467                                        shared.original_exe.path.clone(),
3468                                        wrapper.as_deref(),
3469                                        scenario,
3470                                        &shared.name,
3471                                        true,
3472                                        in_root,
3473                                    )
3474                                    .ok()
3475                                    .flatten()
3476                                    .is_some_and(|rechecked| {
3477                                        rechecked.equals_expected == Some(true)
3478                                            && rechecked.value == shared.value
3479                                    })
3480                                    && let Some(verified) =
3481                                        scenario.verified(shared.value, mutant.value)
3482                                {
3483                                    return Ok(Some(verified));
3484                                }
3485                                // A combined build can fail or the code can depend on
3486                                // the harness. Retry the original input in isolation.
3487                            }
3488                            let Some(original) = observe(scenario, baseline, &[], None, None)?
3489                            else {
3490                                return Ok(None);
3491                            };
3492                            let value = original.value;
3493                            if witness::is_expected_literal(&value) {
3494                                let Some(mutant) = observe(
3495                                    scenario,
3496                                    baseline,
3497                                    &survivor.candidate.edits,
3498                                    None,
3499                                    Some(&value),
3500                                )?
3501                                else {
3502                                    return Ok(None);
3503                                };
3504                                if mutant.equals_expected != Some(false) || value == mutant.value {
3505                                    return Ok(None);
3506                                }
3507                                let Some(checked) =
3508                                    observe(scenario, baseline, &[], None, Some(&value))?
3509                                else {
3510                                    return Ok(None);
3511                                };
3512                                if checked.equals_expected != Some(true) || checked.value != value {
3513                                    return Ok(None);
3514                                }
3515                                return Ok(scenario.verified(value, mutant.value));
3516                            }
3517                            // Multi-field Debug struct: narrow to a single differing public
3518                            // literal field and compiler-verify `&result.<path> == &(<val>)`.
3519                            if witness::parse_debug_struct(&value).is_none() {
3520                                return Ok(None);
3521                            }
3522                            let Some(raw_mutant) =
3523                                observe(scenario, baseline, &survivor.candidate.edits, None, None)?
3524                            else {
3525                                return Ok(None);
3526                            };
3527                            let Some((path, field_orig, _)) =
3528                                witness::narrow_struct_field(&value, &raw_mutant.value)
3529                            else {
3530                                return Ok(None);
3531                            };
3532                            if !witness::is_expected_literal(&field_orig) {
3533                                return Ok(None);
3534                            }
3535                            let field_path = path.join(".");
3536                            let Some(mutant) = observe(
3537                                scenario,
3538                                baseline,
3539                                &survivor.candidate.edits,
3540                                Some(&field_path),
3541                                Some(&field_orig),
3542                            )?
3543                            else {
3544                                return Ok(None);
3545                            };
3546                            if mutant.equals_expected != Some(false)
3547                                || mutant.value != raw_mutant.value
3548                                || value == mutant.value
3549                            {
3550                                return Ok(None);
3551                            }
3552                            let Some(checked) = observe(
3553                                scenario,
3554                                baseline,
3555                                &[],
3556                                Some(&field_path),
3557                                Some(&field_orig),
3558                            )?
3559                            else {
3560                                return Ok(None);
3561                            };
3562                            if checked.equals_expected != Some(true) || checked.value != value {
3563                                return Ok(None);
3564                            }
3565                            Ok(
3566                                scenario.verified_field(
3567                                    value,
3568                                    mutant.value,
3569                                    field_path,
3570                                    field_orig,
3571                                ),
3572                            )
3573                        })();
3574                        match distinction {
3575                            Ok(Some(mut verified)) => {
3576                                let edits = survivor.candidate.edits.len();
3577                                verified.individually_killed = (edits > 1).then_some(edits);
3578                                evidence = Some(verified);
3579                                break;
3580                            }
3581                            Ok(None) => {}
3582                            Err(err) => note(&format!(
3583                                "could not check a distinguishing test for {}: {err:#}",
3584                                scenario.expression,
3585                            )),
3586                        }
3587                    }
3588                    state.write(&file.path, &restore)?;
3589                    progress.complete(Outcome::Pass.into());
3590                    if let Some(index) = survivor.existing {
3591                        if let Some(evidence) = evidence {
3592                            report.findings[index].set_witness(evidence);
3593                            if survivor.candidate.finding_at.is_some() {
3594                                claimed.insert(index);
3595                            }
3596                        }
3597                    } else {
3598                        finding_run_survivors.push(1);
3599                        report.findings.push(Finding::Survivor {
3600                            at: survivor.at,
3601                            survivors: vec![survivor.candidate.description.clone()],
3602                            advice: survivor
3603                                .candidate
3604                                .advice
3605                                .clone()
3606                                .filter(|_| evidence.is_none()),
3607                            witness: evidence,
3608                            change_since: None,
3609                        });
3610                    }
3611                }
3612                Ok(())
3613            },
3614        )?;
3615    }
3616
3617    report.record_evaluation();
3618    debug_assert_eq!(report.findings.len(), finding_run_survivors.len());
3619    let mut paired_findings: Vec<(Finding, usize)> = report
3620        .findings
3621        .into_iter()
3622        .zip(finding_run_survivors)
3623        .collect();
3624    paired_findings.sort_by(|(a, _), (b, _)| {
3625        let (a, b) = (a.at(), b.at());
3626        (&a.file, a.line, a.column).cmp(&(&b.file, b.line, b.column))
3627    });
3628    let (sorted_findings, finding_run_survivors): (Vec<_>, Vec<_>) =
3629        paired_findings.into_iter().unzip();
3630    report.findings = sorted_findings;
3631    let places: Vec<FilePlaces> = files
3632        .iter()
3633        .map(|file| FilePlaces {
3634            display: &file.display,
3635            source: &file.original,
3636            lines: &file.lines,
3637            places: &file.places,
3638        })
3639        .collect();
3640    name_findings(&mut report.findings, &places);
3641
3642    // 8. Findings the user has already dealt with.
3643    let partial_scope = is_partial_scope.then(|| crate::baseline::PartialScope {
3644        scope: scope.as_ref(),
3645        exclude_files: &options.exclude_files,
3646        preserve_all_existing: options.shard.is_some(),
3647    });
3648    let write_ctx = BaselineWriteContext {
3649        ws_package_prefix: &ws_package_prefix,
3650        partial_scope: partial_scope.as_ref(),
3651        single_package_run: batch.is_none(),
3652        note: &note,
3653    };
3654    apply_suppressions_and_finish(
3655        options,
3656        &files,
3657        &mut report,
3658        &finding_run_survivors,
3659        checkpoint.as_ref(),
3660        &write_ctx,
3661    )?;
3662    debug_assert!(
3663        report.counts_reconcile(),
3664        "report counts do not reconcile: {report:#?}"
3665    );
3666    Ok(report)
3667}
3668
3669fn validate_package_options(options: &Options) -> Result<Vec<&str>> {
3670    if let Some(shard) = options.shard
3671        && (!options.source_only || shard.index >= shard.count)
3672    {
3673        bail!("shards require --source-only and a valid shard index");
3674    }
3675    let mut seen_errors = HashSet::new();
3676    let mut error_values = vec![];
3677    for expression in &options.error_values {
3678        let expression = expression.trim();
3679        // The text is written into the code of probes, each on the line of its site: it
3680        // is one line, and has nothing in it that is not to be seen.
3681        if expression.chars().any(char::is_control) {
3682            bail!(
3683                "invalid --error expression {expression:?}: it has to be on one line, \
3684                 without control characters"
3685            );
3686        }
3687        let parsed = syn::parse_str::<syn::Expr>(expression)
3688            .with_context(|| format!("invalid --error expression {expression:?}"))?;
3689        if seen_errors.insert(quote::ToTokens::to_token_stream(&parsed).to_string()) {
3690            error_values.push(expression);
3691        }
3692    }
3693    let selection = &options.test_selection;
3694    if options.nextest.is_some() {
3695        if !cfg!(unix) {
3696            bail!("the nextest runner is available on Unix");
3697        }
3698        if !options.source_only || options.doc || selection.enabled() {
3699            bail!(
3700                "--test-tool nextest requires --source-only; select tests through the nextest profile"
3701            );
3702        }
3703    }
3704    if options.baseline_jobs > 1 && !selection.enabled() {
3705        bail!("--baseline-jobs requires isolated tests or a test wrapper or selection");
3706    }
3707    if options.doc && selection.enabled() {
3708        bail!("--doc cannot be combined with isolated test selection");
3709    }
3710    if options.source_only && options.jobs > 1 {
3711        eprintln!(
3712            "tmt: warning: --source-only runs mutants serially in one working copy; ignoring --jobs {}",
3713            options.jobs
3714        );
3715    }
3716    Ok(error_values)
3717}
3718
3719struct PreparedWorkCopy {
3720    workspace: PathBuf,
3721    work: PathBuf,
3722    work_lock: Option<Arc<WorkLock>>,
3723    copy: PathBuf,
3724    state: WorkCopy,
3725    external_deps: BTreeSet<PathBuf>,
3726}
3727
3728fn prepare_work_copy(
3729    options: &Options,
3730    metadata: &Metadata,
3731    batch: Option<&WorkspaceBatch<'_>>,
3732    catalogue: Option<&CatalogueSnapshot>,
3733    note: &impl Fn(&str),
3734) -> Result<PreparedWorkCopy> {
3735    let workspace = metadata.workspace_root.canonicalize()?;
3736    let requested_work = catalogue
3737        .map(|catalogue| &catalogue.path)
3738        .or(options.work_dir.as_ref());
3739    let work = match requested_work {
3740        Some(dir) => {
3741            fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
3742            dir.canonicalize()?
3743        }
3744        None => metadata.target_directory.join("tmt"),
3745    };
3746    // The copy is brought up to date on every run, and files that are no longer wanted
3747    // are deleted from it. Make sure it is ours to delete from.
3748    if workspace.starts_with(&work) {
3749        bail!(
3750            "the work directory {} contains the workspace; choose a directory of its own",
3751            work.display()
3752        );
3753    }
3754    fs::create_dir_all(&work).with_context(|| format!("creating {}", work.display()))?;
3755    let work = work.canonicalize()?;
3756    let work_lock = if catalogue.is_none() {
3757        Some(Arc::new(WorkLock::take(&work)?))
3758    } else {
3759        None
3760    };
3761    let stage_root = work.join("src");
3762    let copy_subdir = staged_copy_subdir(&workspace, &options.stage_external)?;
3763    let copy = if copy_subdir.as_os_str().is_empty() {
3764        stage_root.clone()
3765    } else {
3766        stage_root.join(&copy_subdir)
3767    };
3768    let marker = work.join(WORK_MARKER);
3769    if stage_root.exists() && !marker.exists() {
3770        bail!(
3771            "{} exists and was not created by tmt; refusing to delete it. \
3772                 Choose another --work-dir or remove it yourself.",
3773            stage_root.display()
3774        );
3775    }
3776    fs::write(
3777        &marker,
3778        "Working directory of tmt (targeted-mutation). Safe to delete.\n",
3779    )?;
3780    let target_dir = metadata.target_directory.clone();
3781    let forbidden = |path: &Path| {
3782        path == target_dir
3783            || path == work
3784            || batch.is_some_and(|batch| path == batch.work)
3785            || path.file_name().is_some_and(|n| n == ".git")
3786            || (path.parent() == Some(workspace.as_path())
3787                && path.file_name().is_some_and(|n| n == "target"))
3788    };
3789    let state = WorkCopy::open_with_copy_root(&work, &stage_root, &copy);
3790    let fixtures = options
3791        .copy_fixtures
3792        .iter()
3793        .map(|path| fixture_relative(path))
3794        .collect::<Result<Vec<_>>>()?;
3795    let excluded = fixture_exclusions(&workspace, &fixtures, &options.copy_fixture_excludes)?;
3796    let fixture_forbidden = |path: &Path| forbidden(path) || excluded.contains(path);
3797    let skip = |path: &Path| {
3798        fixture_forbidden(path) || path.file_name().is_some_and(|n| n == "node_modules")
3799    };
3800    if options.progress && !options.list {
3801        for path in &excluded {
3802            note(&format!(
3803                "excluded fixture {}",
3804                path.strip_prefix(&workspace).unwrap_or(path).display()
3805            ));
3806        }
3807    }
3808    if catalogue.is_none_or(|catalogue| !catalogue.ready.get()) {
3809        work_directory(&work, "src")?;
3810        real_dir(&copy, &state)?;
3811        if copy != stage_root {
3812            for ancestor in copy.ancestors() {
3813                if ancestor == stage_root || !ancestor.starts_with(&stage_root) {
3814                    break;
3815                }
3816                state.kept.borrow_mut().insert(ancestor.to_path_buf());
3817            }
3818        }
3819        let visible = if options.all_files {
3820            None
3821        } else {
3822            git_visible_files(&workspace)?
3823        };
3824        match visible {
3825            // Only what git would not ignore: build output, caches, local notes and secrets
3826            // that are kept out of the repository stay out of the copy too.
3827            Some(files) => {
3828                let copied = copy_git_visible(&workspace, &copy, files, &workspace, &skip, &state)?;
3829                note(&format!(
3830                    "copied {copied} files (ignored files are left out)"
3831                ));
3832            }
3833            None => copy_tree(&workspace, &copy, &workspace, &skip, &state)?,
3834        }
3835        for relative in &fixtures {
3836            copy_fixture_entry(
3837                &workspace.join(relative),
3838                &copy.join(relative),
3839                &workspace,
3840                &fixture_forbidden,
3841                &state,
3842                &mut BTreeSet::new(),
3843            )?;
3844        }
3845        let mut staged_destinations: Vec<PathBuf> = Vec::new();
3846        let mut folded_ancestors: BTreeMap<String, PathBuf> = BTreeMap::new();
3847        for entry in &options.stage_external {
3848            let (rel, _) = parse_external_rel(&entry.rel)?;
3849            let dst = normalize(&copy.join(&rel));
3850            let copy_rel_in_stage = copy.strip_prefix(&stage_root).unwrap_or(&copy);
3851            let dst_rel_in_stage = dst.strip_prefix(&stage_root).unwrap_or(&dst);
3852            if !dst.starts_with(&stage_root)
3853                || dst == stage_root
3854                || copy.starts_with(&dst)
3855                || dst.starts_with(&copy)
3856                || paths_overlap_case_insensitive(copy_rel_in_stage, dst_rel_in_stage)
3857                || staged_destinations.iter().any(|prev| {
3858                    let prev_rel = prev.strip_prefix(&stage_root).unwrap_or(prev);
3859                    paths_overlap_case_insensitive(prev_rel, dst_rel_in_stage)
3860                })
3861            {
3862                bail!(
3863                    "--stage-external destination collides with the workspace copy or another staged path: {}",
3864                    entry.rel.display()
3865                );
3866            }
3867            for ancestor in dst_rel_in_stage.ancestors() {
3868                if ancestor.as_os_str().is_empty() {
3869                    continue;
3870                }
3871                let folded = ancestor.to_string_lossy().to_lowercase();
3872                if let Some(previous) = folded_ancestors.get(&folded)
3873                    && previous != ancestor
3874                {
3875                    bail!(
3876                        "--stage-external destinations differ only by case: {} and {}",
3877                        previous.display(),
3878                        ancestor.display()
3879                    );
3880                }
3881                folded_ancestors.insert(folded, ancestor.to_path_buf());
3882            }
3883            staged_destinations.push(dst.clone());
3884            let src = if entry.from.is_absolute() {
3885                entry.from.clone()
3886            } else {
3887                workspace.join(&entry.from)
3888            };
3889            copy_external_entry(
3890                &src,
3891                &dst,
3892                None,
3893                &work,
3894                &forbidden,
3895                &state,
3896                &mut BTreeSet::new(),
3897            )?;
3898        }
3899        prune(&stage_root, &state)?;
3900        if options.git_index {
3901            git_index::snapshot(&workspace, &copy)?;
3902        }
3903        let mut external_deps = BTreeSet::new();
3904        if !options.list {
3905            // Relative path dependencies that leave the workspace would point nowhere from the copy.
3906            let mut manifests: Vec<&Path> = metadata
3907                .packages
3908                .iter()
3909                .map(|p| p.manifest_path.as_path())
3910                .collect();
3911            let root_manifest = metadata.workspace_root.join("Cargo.toml");
3912            manifests.push(&root_manifest);
3913            for manifest in manifests {
3914                let Ok(canonical) = manifest.canonicalize() else {
3915                    continue;
3916                };
3917                let (Some(manifest_dir), Ok(relative)) =
3918                    (canonical.parent(), canonical.strip_prefix(&workspace))
3919                else {
3920                    continue;
3921                };
3922                let text = fs::read_to_string(&canonical)?;
3923                let (rewritten, externals) = absolutize_path_dependencies_with_externals(
3924                    &text,
3925                    manifest_dir,
3926                    &workspace,
3927                    &copy,
3928                )?;
3929                external_deps.extend(externals);
3930                if let Some(rewritten) = rewritten {
3931                    state.write(&copy.join(relative), &rewritten)?;
3932                }
3933            }
3934        }
3935        if let Some(catalogue) = catalogue {
3936            state.settle(&workspace)?;
3937            catalogue.ready.set(true);
3938        }
3939        return Ok(PreparedWorkCopy {
3940            workspace,
3941            work,
3942            work_lock,
3943            copy,
3944            state,
3945            external_deps,
3946        });
3947    }
3948    Ok(PreparedWorkCopy {
3949        workspace,
3950        work,
3951        work_lock,
3952        copy,
3953        state,
3954        external_deps: BTreeSet::new(),
3955    })
3956}
3957
3958#[allow(clippy::too_many_arguments)]
3959fn run_audit_phase<'a>(
3960    session: &Session,
3961    files: &[SourceFile],
3962    jobs: &[Job],
3963    results: &mut [JobResult],
3964    timeout_rechecks: &mut report::TimeoutRechecks,
3965    scratch: &Path,
3966    wanted: usize,
3967    workers: usize,
3968    probe_phase: &impl Fn(&str, &[Job]) -> Result<Option<Phase<'a>>>,
3969) -> Result<report::Audit> {
3970    let survivors: Vec<usize> = (0..jobs.len())
3971        .filter(|job| results[*job].survived.is_some())
3972        .collect();
3973    let chosen: Vec<usize> = spread(survivors.len(), wanted)
3974        .into_iter()
3975        .map(|nth| survivors[nth])
3976        .collect();
3977    session.note(&format!(
3978        "audit: running {} of {} surviving mutants against all tests",
3979        chosen.len(),
3980        survivors.len()
3981    ));
3982    let against_all: Vec<Job> = chosen
3983        .iter()
3984        .map(|job| Job {
3985            site: jobs[*job].site,
3986            mutation: jobs[*job].mutation,
3987            tests: (0..session.binaries.len()).map(|bin| (bin, None)).collect(),
3988        })
3989        .collect();
3990    let mut audit = report::Audit {
3991        sampled: chosen.len(),
3992        survivors: survivors.len(),
3993        ..report::Audit::default()
3994    };
3995    let audit_checkpoint = probe_phase("audit", &against_all)?;
3996    for (job, again) in chosen.iter().zip(session.run_jobs(
3997        &against_all,
3998        workers,
3999        "audit mutants",
4000        audit_checkpoint.as_ref(),
4001    )?) {
4002        timeout_rechecks.include(&again);
4003        if again.unable || again.unconfirmed_timeout {
4004            audit.not_audited += 1;
4005        } else if audit_all_tests_disagrees(&again) {
4006            // The verdict of all tests is the one that counts.
4007            results[*job] = again;
4008            let site = files
4009                .iter()
4010                .find_map(|f| Some((f, f.sites.iter().find(|s| s.id == jobs[*job].site)?)));
4011            if let Some((file, site)) = site {
4012                audit
4013                    .disagreements
4014                    .push(report::location(&file.display, site));
4015            }
4016        }
4017    }
4018    session.note("audit: recording the tests once more");
4019    for (index, bin) in session.binaries.iter().enumerate() {
4020        let path = scratch.join(format!("trace-{index}-audit.tsv"));
4021        let _ = fs::remove_file(&path);
4022        let trace_env = path.to_string_lossy().into_owned();
4023        let limit = Duration::from_secs(3600);
4024        let outcome = run_binary(
4025            bin,
4026            None,
4027            &[("TMT_TRACE", &trace_env)],
4028            limit,
4029            RunOutput::Quiet,
4030            1,
4031        )?;
4032        let again = Trace::parse(&fs::read_to_string(&path).unwrap_or_default());
4033        let _ = fs::remove_file(&path);
4034        let records = bin.trace.differences(&again);
4035        if outcome != Outcome::Pass || records > 0 {
4036            audit.trace_differences.push(report::TraceDifference {
4037                binary: bin.name.clone(),
4038                records,
4039                rerun_failed: outcome != Outcome::Pass,
4040            });
4041        }
4042    }
4043    Ok(audit)
4044}
4045
4046fn run_effects_phase(
4047    session: &Session,
4048    files: &[SourceFile],
4049    jobs: &[Job],
4050    effect_jobs: &[(usize, usize)],
4051    scratch: &Path,
4052    workers: usize,
4053    findings: &mut [Finding],
4054) -> Result<()> {
4055    session.note(&format!("tracing {} surviving mutants", effect_jobs.len()));
4056    let sites: BTreeMap<u32, (&str, &Site)> = files
4057        .iter()
4058        .flat_map(|f| f.sites.iter().map(move |s| (s.id, (f.display.as_str(), s))))
4059        .collect();
4060    let traced = run_pool(effect_jobs.len(), workers, |index| {
4061        session.trace_job(
4062            &jobs[effect_jobs[index].1],
4063            scratch,
4064            workers.clamp(1, effect_jobs.len()),
4065        )
4066    })?;
4067    for ((finding, job), mut changes) in effect_jobs.iter().zip(traced) {
4068        // What happens inside the mutated code itself is not an effect of it: deleting
4069        // a statement trivially stops the expressions in it from running.
4070        if let Some((mutated_file, mutated)) = sites.get(&jobs[*job].site) {
4071            for found in changes.values_mut() {
4072                found.retain(|change| {
4073                    sites.get(&change.site()).is_none_or(|(file, site)| {
4074                        file != mutated_file
4075                            || site.end <= mutated.start
4076                            || mutated.end <= site.start
4077                    })
4078                });
4079            }
4080            changes.retain(|_, found| !found.is_empty());
4081        }
4082        if let Finding::AssertionGap {
4083            effects,
4084            effects_of,
4085            ..
4086        } = &mut findings[*finding]
4087        {
4088            *effects = describe_effects(&changes, &sites);
4089            *effects_of = sites
4090                .get(&jobs[*job].site)
4091                .map(|(_, site)| report::describe(site, jobs[*job].mutation));
4092        }
4093    }
4094    Ok(())
4095}
4096
4097struct BaselineWriteContext<'a> {
4098    ws_package_prefix: &'a str,
4099    partial_scope: Option<&'a crate::baseline::PartialScope<'a>>,
4100    single_package_run: bool,
4101    note: &'a dyn Fn(&str),
4102}
4103
4104fn apply_suppressions_and_finish(
4105    options: &Options,
4106    files: &[SourceFile],
4107    report: &mut Report,
4108    finding_run_survivors: &[usize],
4109    checkpoint: Option<&Checkpoint>,
4110    write_ctx: &BaselineWriteContext<'_>,
4111) -> Result<()> {
4112    let parsed_ignores: BTreeMap<&str, crate::baseline::ParsedLineIgnores> = files
4113        .iter()
4114        .map(|f| {
4115            (
4116                f.display.as_str(),
4117                crate::baseline::parse_line_ignores(&f.original),
4118            )
4119        })
4120        .collect();
4121    for (file, parsed) in &parsed_ignores {
4122        for warning in &parsed.warnings {
4123            match warning {
4124                crate::baseline::IgnoreWarning::EmptyScope { line } => {
4125                    eprintln!(
4126                        "tmt: warning: {}:{line}: empty `tmt:ignore[]` scope suppresses nothing (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
4127                        crate::report::sanitize_inline(file),
4128                    );
4129                }
4130                crate::baseline::IgnoreWarning::InvalidToken { line, token } => {
4131                    eprintln!(
4132                        "tmt: warning: {}:{line}: unknown `tmt:ignore` scope `{}` (supported: input_gap, assertion_gap, survivor, @COL, or kind@COL)",
4133                        crate::report::sanitize_inline(file),
4134                        crate::report::sanitize_inline(token),
4135                    );
4136                }
4137            }
4138        }
4139    }
4140    let known = match &options.baseline {
4141        Some(path) => {
4142            let loaded = crate::baseline::load(path)?;
4143            loaded.validate_for_package(&report.package, path)?;
4144            Some(loaded)
4145        }
4146        None => None,
4147    };
4148    let before = report.findings.len();
4149    let mut after_inline: Vec<(Finding, usize)> = Vec::with_capacity(before);
4150    let mut matched_entries: BTreeSet<(&str, usize)> = BTreeSet::new();
4151    for (finding, run_survivors) in report
4152        .findings
4153        .drain(..)
4154        .zip(finding_run_survivors.iter().copied())
4155    {
4156        let at = finding.at();
4157        if let Some((&file_key, parsed)) = parsed_ignores.get_key_value(at.file.as_str())
4158            && parsed
4159                .directives
4160                .get(&at.line)
4161                .is_some_and(|ignore| ignore.matches(finding.kind(), at.column))
4162        {
4163            for entry in &parsed.entries {
4164                if entry.matches(at.line, finding.kind(), at.column) {
4165                    matched_entries.insert((file_key, entry.comment_line));
4166                }
4167            }
4168            report.survivor_breakdown.suppressed += run_survivors;
4169        } else {
4170            after_inline.push((finding, run_survivors));
4171        }
4172    }
4173    // Warn about active `// tmt:ignore` directives that matched no findings on a line where
4174    // at least one site was evaluated (e.g. mutants are already killed or `@COL` missed).
4175    // Skip when sharding or when the run left mutants unevaluated/unbuilt on that line.
4176    if options.shard.is_none() && report.mutants_not_evaluated == 0 {
4177        let skipped_locs: BTreeSet<(&str, usize, usize)> = report
4178            .skipped
4179            .iter()
4180            .map(|s| (s.at.file.as_str(), s.at.line, s.at.column))
4181            .collect();
4182        let unreached_locs: BTreeSet<(&str, usize, usize)> = report
4183            .unreached
4184            .iter()
4185            .map(|u| (u.file.as_str(), u.line, u.column))
4186            .collect();
4187        for file in files {
4188            let Some(parsed) = parsed_ignores.get(file.display.as_str()) else {
4189                continue;
4190            };
4191            if parsed.entries.is_empty() {
4192                continue;
4193            }
4194            let evaluated_lines: BTreeSet<usize> = file
4195                .sites
4196                .iter()
4197                .chain(&file.rebuild_sites)
4198                .filter(|site| {
4199                    let key = (file.display.as_str(), site.line, site.column);
4200                    !skipped_locs.contains(&key) && !unreached_locs.contains(&key)
4201                })
4202                .map(|site| site.line)
4203                .collect();
4204            for entry in &parsed.entries {
4205                if !entry.is_active() {
4206                    continue;
4207                }
4208                if matched_entries.contains(&(file.display.as_str(), entry.comment_line)) {
4209                    continue;
4210                }
4211                if entry
4212                    .target_lines
4213                    .iter()
4214                    .any(|line| evaluated_lines.contains(line))
4215                {
4216                    eprintln!(
4217                        "tmt: warning: {}:{}: `tmt:ignore` matched no findings on an evaluated line (mutants may already be killed or selector/column may not match)",
4218                        crate::report::sanitize_inline(&file.display),
4219                        entry.comment_line,
4220                    );
4221                }
4222            }
4223        }
4224    }
4225    if let Some(path) = &options.write_baseline {
4226        let unignored: Vec<Finding> = after_inline.iter().map(|(f, _)| f.clone()).collect();
4227        let single_pkg = write_ctx
4228            .single_package_run
4229            .then_some(report.package.as_str());
4230        let summary = crate::baseline::write_scoped(
4231            path,
4232            &report.package,
4233            write_ctx.ws_package_prefix,
4234            &unignored,
4235            write_ctx.partial_scope,
4236            single_pkg,
4237        )?;
4238        if summary.preserved > 0 || summary.removed > 0 {
4239            (write_ctx.note)(&format!(
4240                "baseline {}: {} entries written ({} preserved out of scope, {} resolved removed)",
4241                path.display(),
4242                summary.written,
4243                summary.preserved,
4244                summary.removed
4245            ));
4246        }
4247    }
4248    for (finding, run_survivors) in after_inline {
4249        if known
4250            .as_ref()
4251            .is_some_and(|known| known.knows_in_package(&report.package, &finding))
4252        {
4253            report.survivor_breakdown.suppressed += run_survivors;
4254        } else {
4255            report.survivor_breakdown.reported += run_survivors;
4256            report.findings.push(finding);
4257        }
4258    }
4259    report.suppressed = before - report.findings.len();
4260    if let Some(checkpoint) = checkpoint {
4261        checkpoint.finish_if_complete()?;
4262    }
4263    Ok(())
4264}
4265
4266fn workspace_report_prefix(relative: &Path) -> String {
4267    let parts: Vec<_> = relative
4268        .components()
4269        .filter_map(|part| match part {
4270            std::path::Component::Normal(name) => Some(name.to_string_lossy()),
4271            _ => None,
4272        })
4273        .collect();
4274    if parts.is_empty() {
4275        String::new()
4276    } else {
4277        format!("{}/", parts.join("/"))
4278    }
4279}
4280
4281/// Where a directory is in its git repository: `crates/core/`, or nothing at the top
4282/// and outside of any. The files of a report are named from the package; this in front
4283/// of them names them from the repository, as a code-scanning service wants them.
4284fn repository_prefix(dir: &Path) -> String {
4285    let shown = Command::new("git")
4286        .arg("-C")
4287        .arg(dir)
4288        .args(["rev-parse", "--show-prefix"])
4289        .stderr(Stdio::null())
4290        .output();
4291    match shown {
4292        Ok(output) if output.status.success() => {
4293            String::from_utf8_lossy(&output.stdout).trim().to_string()
4294        }
4295        _ => String::new(),
4296    }
4297}
4298
4299/// `wanted` of the numbers below `count`, spread evenly and the same every time; all of
4300/// them where there are no more.
4301fn spread(count: usize, wanted: usize) -> Vec<usize> {
4302    let wanted = wanted.min(count);
4303    (0..wanted).map(|nth| nth * count / wanted).collect()
4304}
4305
4306/// What naming the findings of a file needs to know of it.
4307struct FilePlaces<'a> {
4308    display: &'a str,
4309    source: &'a str,
4310    lines: &'a scope::LineIndex,
4311    /// Every site of the file as (line, column, code), whatever part of it was analysed.
4312    places: &'a [(usize, usize, String)],
4313}
4314
4315/// Gives every finding the item it is in and its name (`report::finding_id`). Which of
4316/// several places with the same code in one item a finding is at is counted over the
4317/// sites of the file, not over the findings: a finding keeps its number when the one
4318/// before it is closed.
4319fn name_findings(findings: &mut [Finding], files: &[FilePlaces]) {
4320    let mut by_file: BTreeMap<String, Vec<&mut Finding>> = BTreeMap::new();
4321    for finding in findings {
4322        by_file
4323            .entry(finding.at().file.clone())
4324            .or_default()
4325            .push(finding);
4326    }
4327    for file in files {
4328        let Some(findings) = by_file.remove(file.display) else {
4329            continue;
4330        };
4331        let items = instrument::named_items(file.source);
4332        let index = instrument::ItemIndex::new(&items);
4333        let item_at = |line, column| {
4334            file.lines
4335                .offset_of(file.source, line, column)
4336                .map_or("", |offset| index.at(offset))
4337        };
4338        let mut positions: BTreeMap<(&str, &str), Vec<(usize, usize)>> = BTreeMap::new();
4339        for (line, column, code) in file.places {
4340            positions
4341                .entry((item_at(*line, *column), code))
4342                .or_default()
4343                .push((*line, *column));
4344        }
4345        for places in positions.values_mut() {
4346            places.sort_unstable();
4347            places.dedup();
4348        }
4349        for finding in findings {
4350            let kind = finding.kind();
4351            let at = finding.at_mut();
4352            let item = item_at(at.line, at.column);
4353            let nth = positions.get(&(item, &at.code)).map_or(0, |places| {
4354                places.partition_point(|&place| place < (at.line, at.column))
4355            });
4356            at.item = item.to_string();
4357            at.id = report::finding_id(kind, at, nth);
4358        }
4359    }
4360}
4361
4362/// The mutation that a change of the source text is, to describe it in the same words.
4363fn mutation_of(site: &Site, mutant: &instrument::SourceMutant) -> Mutation {
4364    match &site.kind {
4365        SiteKind::Cmp { .. } => plan::CmpOp::ALL
4366            .into_iter()
4367            .find(|op| op.symbol() == mutant.into)
4368            .map_or(Mutation::Negate, Mutation::Op),
4369        SiteKind::Arith { op, .. } => {
4370            if mutant.into.trim_end_matches('=') == op.swapped().symbol() {
4371                Mutation::ArithSwap
4372            } else {
4373                Mutation::ArithSwap2
4374            }
4375        }
4376        SiteKind::Guard { .. } => Mutation::Const(mutant.into == "true"),
4377        SiteKind::Logic { .. } => Mutation::LogicSwap,
4378        SiteKind::Not { .. } => Mutation::DropNot,
4379        SiteKind::Range { .. } | SiteKind::RangeContains { .. } => Mutation::RangeEnd,
4380        SiteKind::SliceEnd { .. } => Mutation::OtherEnd,
4381        SiteKind::StrAffix { .. } => Mutation::StrContains,
4382        SiteKind::StrReplace { .. } => Mutation::StrReplaceMultiplicity,
4383        SiteKind::Clamp { .. } => {
4384            if mutant.into.contains("lower") {
4385                Mutation::ClampDropLower
4386            } else {
4387                Mutation::ClampDropUpper
4388            }
4389        }
4390        SiteKind::Rounding { op, .. } => {
4391            if mutant.into == op.alt1().name() {
4392                Mutation::RoundAlt1
4393            } else {
4394                Mutation::RoundAlt2
4395            }
4396        }
4397        SiteKind::Quantifier { .. } => Mutation::QuantifierSwap,
4398        SiteKind::Position { .. } => Mutation::PositionSwap,
4399        SiteKind::SaturatingArith { .. } => Mutation::SaturatingSwap,
4400        SiteKind::StrTrim { op, .. } => {
4401            if mutant.into == op.alt1().name() {
4402                Mutation::TrimAlt1
4403            } else {
4404                Mutation::TrimAlt2
4405            }
4406        }
4407        SiteKind::StrCaseEq { .. } => Mutation::StrExactEq,
4408        SiteKind::Abs { .. } => Mutation::DropAbs,
4409        SiteKind::IterLimit { .. } => Mutation::IterLimitDrop,
4410        SiteKind::EndianSwap { .. } => Mutation::EndianSwap,
4411        SiteKind::BitCount { .. } => Mutation::BitCountSwap,
4412        SiteKind::LoopCtrl { .. } => Mutation::LoopCtrlSwap,
4413        SiteKind::LiteralSet { elements, .. } => {
4414            let idx = elements
4415                .iter()
4416                .position(|(elem, _, _)| elem == &mutant.into)
4417                .unwrap_or(0);
4418            Mutation::DropLiteralElem(idx as u8)
4419        }
4420        // The other kinds have one mutant of the source: a statement, an arm, a field or
4421        // a minus that is not there, a body that is another.
4422        _ => Mutation::Delete,
4423    }
4424}
4425
4426/// The mutations a probe may have run that are the same change as a mutant of the source,
4427/// its own name first. A comparison is planned in other words than it is written in:
4428/// `a != b` for `a == b` is run as the negation, and on integers `a <= b` for `a < b` as
4429/// the bound moved by one.
4430///
4431/// `integers`: the operands are integers, which always have an order. For anything
4432/// else (a float can be NaN) the negation of `>=` is true where `<` is false, and is
4433/// not the same change.
4434fn mutations_like(site: &Site, mutant: &instrument::SourceMutant, integers: bool) -> Vec<Mutation> {
4435    let mut all = vec![mutation_of(site, mutant)];
4436    if let (SiteKind::Cmp { op, .. }, Mutation::Op(into)) = (&site.kind, all[0]) {
4437        let an_order_is_needed = matches!(op, plan::CmpOp::Le | plan::CmpOp::Ge);
4438        if into == op.negated() && (integers || !an_order_is_needed) {
4439            all.push(Mutation::Negate);
4440        }
4441        match (op, into) {
4442            (plan::CmpOp::Lt, plan::CmpOp::Le) | (plan::CmpOp::Ge, plan::CmpOp::Gt) => {
4443                all.push(Mutation::Shift(1))
4444            }
4445            (plan::CmpOp::Gt, plan::CmpOp::Ge) | (plan::CmpOp::Le, plan::CmpOp::Lt) => {
4446                all.push(Mutation::Shift(-1))
4447            }
4448            _ => {}
4449        }
4450    }
4451    all
4452}
4453
4454/// The changes a surviving mutant causes, as up to three sentences. Changes that many
4455/// tests share are mentioned once.
4456fn describe_effects(
4457    changes: &BTreeMap<String, BTreeSet<Change>>,
4458    sites: &BTreeMap<u32, (&str, &Site)>,
4459) -> Vec<String> {
4460    let mut by_change: BTreeMap<&Change, Vec<&str>> = BTreeMap::new();
4461    for (test, found) in changes {
4462        for change in found {
4463            by_change.entry(change).or_default().push(test);
4464        }
4465    }
4466    if by_change.is_empty() {
4467        return vec![
4468            "with the mutant, these tests still reach the same code with the same outcomes, as far as that is recorded: they do not use its result, it is the same for their inputs, or what they assert holds for both".to_string(),
4469        ];
4470    }
4471    let mut out = vec![];
4472    for (change, tests) in by_change.iter().take(3) {
4473        let Some((file, site)) = sites.get(&change.site()) else {
4474            continue;
4475        };
4476        let code = report::location(file, site).code;
4477        let at = format!("{file}:{}", site.line);
4478        let who = if tests.is_empty() {
4479            continue;
4480        } else if let Some(first) = tests
4481            .iter()
4482            .copied()
4483            .find(|test| *test != crate::trace::UNKNOWN_TEST)
4484        {
4485            if tests.len() == 1 {
4486                format!("`{first}`")
4487            } else {
4488                format!("`{first}` (and {} more)", tests.len() - 1)
4489            }
4490        } else if tests.len() == 1 {
4491            "a test".to_string()
4492        } else {
4493            format!("a test (and {} more)", tests.len() - 1)
4494        };
4495        out.push(match change {
4496            Change::Returns { value, .. } => {
4497                format!("with the mutant, {who} gets `{value}` from `{code}` ({at})")
4498            }
4499            Change::NowRuns { .. } => format!("with the mutant, {who} now runs `{code}` ({at})"),
4500            Change::NoLongerRuns { .. } => {
4501                format!("with the mutant, {who} no longer runs `{code}` ({at})")
4502            }
4503            Change::NewOutcome { .. } => {
4504                format!("with the mutant, {who} takes `{code}` ({at}) a way it did not before")
4505            }
4506        });
4507    }
4508    if by_change.len() > 3 {
4509        out.push(format!("(and {} more such changes)", by_change.len() - 3));
4510    }
4511    out
4512}
4513
4514#[cfg(test)]
4515mod tests;