Skip to main content

targeted_mutation/driver/
session.rs

1//! Trace-driven mutation planning, job execution, timeout confirmation, and sharding.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use anyhow::{Context, Result, bail};
8use serde::{Deserialize, Serialize};
9
10use crate::checkpoint::Phase;
11use crate::instrument::{self, LiteralSide, Site, SiteKind};
12use crate::plan::{self, Mutation, Obs};
13use crate::progress;
14use crate::propagation::{self, Change};
15use crate::report::{self, Finding};
16use crate::trace::Trace;
17
18use super::*;
19
20pub(super) struct Session {
21    pub(super) progress: bool,
22    pub(super) serial_timeout_rechecks: bool,
23    pub(super) package_dir: PathBuf,
24    pub(super) binaries: Vec<TestBinary>,
25}
26
27/// One mutant and the tests it has to face, per test binary.
28pub(super) struct Job {
29    pub(super) site: u32,
30    pub(super) mutation: Mutation,
31    /// `(index of the binary, tests to run or None for all of them)`.
32    pub(super) tests: Vec<(usize, Option<Vec<String>>)>,
33}
34
35// Jobs are appended in the same order as the numbered probe sites.
36pub(super) fn jobs_for_site(jobs: &[Job], site: u32) -> std::ops::Range<usize> {
37    let first = jobs.partition_point(|job| job.site < site);
38    let count = jobs[first..].partition_point(|job| job.site == site);
39    first..first + count
40}
41
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43pub(super) struct JobResult {
44    pub(super) first_pass_timeout: bool,
45    pub(super) unconfirmed_timeout: bool,
46    /// The tests the mutant passed, when it passed all of them.
47    pub(super) survived: Option<Vec<String>>,
48    pub(super) timed_out: bool,
49    /// The mutant could not be run as what it is: neither found out nor passed.
50    pub(super) unable: bool,
51}
52
53/// What the re-runs say of a survivor the trace predicted.
54#[derive(Debug, PartialEq)]
55pub(super) enum Prediction {
56    /// Every re-run passed all the tests.
57    Confirmed,
58    /// A re-run was found out by the tests: the trace did not see everything.
59    Refuted,
60    /// No re-run was found out, and one could not be run or was only stopped by a time
61    /// limit that was not confirmed: neither a finding nor a contradiction.
62    Unknown,
63}
64
65impl Prediction {
66    pub(super) fn of<'a>(runs: impl Iterator<Item = &'a JobResult>) -> Prediction {
67        let mut verdict = Prediction::Confirmed;
68        for run in runs {
69            if run.unable || run.unconfirmed_timeout {
70                verdict = Prediction::Unknown;
71            } else if run.survived.is_none() {
72                return Prediction::Refuted;
73            }
74        }
75        verdict
76    }
77}
78
79impl report::TimeoutRechecks {
80    pub(super) fn include(&mut self, result: &JobResult) {
81        if result.first_pass_timeout {
82            self.first_pass += 1;
83            if result.unconfirmed_timeout || result.unable {
84                self.unconfirmed += 1;
85            } else if result.timed_out {
86                self.confirmed += 1;
87            } else {
88                self.recovered += 1;
89            }
90        }
91    }
92}
93
94impl JobResult {
95    pub(super) fn not_evaluated() -> Self {
96        Self {
97            first_pass_timeout: false,
98            unconfirmed_timeout: false,
99            survived: None,
100            timed_out: false,
101            unable: true,
102        }
103    }
104
105    pub(super) fn progress_outcome(&self) -> progress::Outcome {
106        if self.unable {
107            progress::Outcome::Unable
108        } else if self.timed_out {
109            progress::Outcome::TimedOut
110        } else if self.survived.is_some() {
111            progress::Outcome::Survived
112        } else {
113            progress::Outcome::Failed
114        }
115    }
116}
117
118/// The tests of one binary whose observations satisfy `pick`.
119pub(super) fn tests_where<T>(
120    per_test: Option<&BTreeMap<String, T>>,
121    pick: impl Fn(&T) -> bool,
122) -> BTreeSet<String> {
123    per_test
124        .into_iter()
125        .flatten()
126        .filter(|(_, obs)| pick(obs))
127        .map(|(test, _)| test.clone())
128        .collect()
129}
130
131pub(super) type InfectedTests<'a> = Box<dyn Fn(&TestBinary, Mutation) -> BTreeSet<String> + 'a>;
132pub(super) type ReachingTests<'a> = Box<dyn Fn(&TestBinary) -> BTreeSet<String> + 'a>;
133
134/// A predicted survivor.
135pub(super) struct PlannedGap {
136    pub(super) finding: Finding,
137    /// Mutations to confirm the prediction with.
138    pub(super) survivors: Vec<Mutation>,
139    /// The gap says nothing more than "the expression in this byte range had one value in
140    /// every test". If that expression is a site of its own that already says so, the
141    /// gap is not reported a second time.
142    pub(super) constant_expr: Option<(usize, usize)>,
143}
144
145/// The byte range of an operand without the parentheses and spaces around it.
146pub(super) fn core_range(start: usize, text: &str) -> (usize, usize) {
147    let (mut from, mut to) = (0, text.len());
148    loop {
149        let inner = &text[from..to];
150        let trimmed = inner.trim();
151        from += inner.len() - inner.trim_start().len();
152        to = from + trimmed.len();
153        let wrapped = trimmed.starts_with('(') && trimmed.ends_with(')') && {
154            // The first parenthesis must be the one the last closes: `(a) && (b)` is not wrapped.
155            let mut depth = 0usize;
156            trimmed.char_indices().all(|(i, c)| {
157                match c {
158                    '(' => depth += 1,
159                    ')' => depth -= 1,
160                    _ => {}
161                }
162                depth > 0 || i == trimmed.len() - 1
163            })
164        };
165        if !wrapped {
166            return (start + from, start + to);
167        }
168        from += 1;
169        to -= 1;
170    }
171}
172
173/// What the planner decided for one site.
174pub(super) struct SitePlan<'a> {
175    /// Predicted survivors: the finding to report and the mutations to confirm it with.
176    pub(super) gaps: Vec<PlannedGap>,
177    /// The comparison cannot have another outcome within its operand types. A function
178    /// or condition built on it is constant for a reason no test can change.
179    pub(super) cannot_differ: bool,
180    /// The expression had a single value in every test.
181    pub(super) constant: bool,
182    /// For `&&` / `||`, every observed evaluation produced a boolean value where
183    /// `a && b == a || b`: if `LogicSwap` survives, it is a redundant constant survivor
184    /// rather than an assertion gap.
185    pub(super) redundant_logic_swap: bool,
186    /// Mutations some test observes differently.
187    pub(super) run: Vec<Mutation>,
188    /// Tests of a binary whose execution the mutation can change.
189    pub(super) infected: InfectedTests<'a>,
190    /// Tests of a binary that execute the site at all.
191    pub(super) reaching: ReachingTests<'a>,
192}
193
194pub(super) enum Planned<'a> {
195    Unreached,
196    /// Reached, and its mutant cannot be run as a probe here: said, not passed over.
197    NotEvaluated,
198    /// Reached, but nothing to mutate (operands that are not numbers).
199    Nothing,
200    Plan(SitePlan<'a>),
201}
202
203/// A predicted survivor with the jobs that confirm it and the expression it calls constant.
204pub(super) type ConfirmedGap = (Finding, Vec<usize>, Option<(usize, usize)>);
205
206/// A site with its jobs: indices into the job list.
207pub(super) struct SiteWork<'a> {
208    pub(super) file: &'a str,
209    pub(super) site: &'a Site,
210    pub(super) gaps: Vec<ConfirmedGap>,
211    pub(super) constant: bool,
212    pub(super) cannot_differ: bool,
213    pub(super) redundant_logic_swap: bool,
214    pub(super) runs: Vec<(Mutation, usize)>,
215}
216
217impl Session {
218    pub(super) fn note(&self, text: &str) {
219        if self.progress {
220            eprintln!("tmt: {}", report::sanitize_inline(text));
221        }
222    }
223
224    pub(super) fn merged<T: Default + Copy>(
225        &self,
226        select: impl Fn(&Trace) -> Option<&BTreeMap<String, T>>,
227        merge: impl Fn(&mut T, &T),
228    ) -> T {
229        let mut all = T::default();
230        for obs in self
231            .binaries
232            .iter()
233            .filter_map(|b| select(&b.trace))
234            .flat_map(|t| t.values())
235        {
236            merge(&mut all, obs);
237        }
238        all
239    }
240
241    /// `primitive` says of a byte range of the file whether it is an arithmetic
242    /// operation that was run on primitive numbers.
243    /// `cast_bounds` returns the runtime-observed `[min, max]` bounds of a cast source
244    /// expression at `(start, end)` when every test binary agreed on its primitive type.
245    pub(super) fn plan<'a>(
246        &'a self,
247        file: &str,
248        site: &'a Site,
249        verify: bool,
250        primitive: &dyn Fn(usize, usize) -> bool,
251        primitive_cmp: &dyn Fn(usize, usize) -> bool,
252        cast_bounds: &dyn Fn(usize, usize) -> Option<(i128, i128)>,
253    ) -> Planned<'a> {
254        let id = site.id;
255        let reach_plan = |mutation: Mutation| SitePlan {
256            gaps: vec![],
257            constant: false,
258            cannot_differ: false,
259            redundant_logic_swap: false,
260            run: vec![mutation],
261            infected: Box::new(move |bin, _| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
262            reaching: Box::new(move |bin| bin.trace.reach.get(&id).cloned().unwrap_or_default()),
263        };
264        let reached = || {
265            self.binaries
266                .iter()
267                .any(|b| b.trace.reach.contains_key(&id))
268        };
269        Planned::Plan(match &site.kind {
270            SiteKind::Stmt
271            | SiteKind::Neg { .. }
272            | SiteKind::Field { .. }
273            | SiteKind::Body { .. }
274                if reached() =>
275            {
276                reach_plan(Mutation::Delete)
277            }
278            SiteKind::Stmt
279            | SiteKind::Neg { .. }
280            | SiteKind::Field { .. }
281            | SiteKind::Body { .. } => return Planned::Unreached,
282            SiteKind::Guard { can_be_false } => {
283                let can_be_false = *can_be_false;
284                let allowed = move |m: &Mutation| can_be_false || *m != Mutation::Const(false);
285                let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
286                let guard_plan = plan::plan_return(&merged);
287                let any_reached = !guard_plan.unreached || reached();
288                if !any_reached {
289                    return Planned::Unreached;
290                }
291                // Any test that reached `guard_override` without reaching `guard_record`
292                // exited early (e.g. `return`, `?`, panic) inside the guard expression:
293                // replacing the guard with a constant changes that control flow.
294                let has_early_exit = self.binaries.iter().any(|bin| {
295                    let Some(reached_tests) = bin.trace.reach.get(&id) else {
296                        return false;
297                    };
298                    let returned = bin.trace.returns.get(&id);
299                    reached_tests.iter().any(|t| {
300                        returned
301                            .and_then(|m| m.get(t))
302                            .is_none_or(|obs| !obs.reached())
303                    })
304                });
305                let pure = !has_early_exit
306                    && is_strictly_pure_guard(&site.text, primitive_cmp(site.start, site.end));
307                if pure {
308                    let gaps = guard_plan
309                        .always
310                        .filter(|always| allowed(&Mutation::Const(*always)))
311                        .map(|always| PlannedGap {
312                            finding: report::guard_gap_finding(file, site, always, verify),
313                            survivors: vec![Mutation::Const(always)],
314                            // The guard is the condition it consists of.
315                            constant_expr: Some((site.start, site.end)),
316                        })
317                        .into_iter()
318                        .collect();
319                    SitePlan {
320                        constant: false,
321                        cannot_differ: false,
322                        redundant_logic_swap: false,
323                        gaps,
324                        run: guard_plan.run.into_iter().filter(allowed).collect(),
325                        infected: Box::new(move |bin, m| {
326                            tests_where(bin.trace.returns.get(&id), |obs| match m {
327                                Mutation::Const(value) => obs.infected_by_const(value),
328                                _ => obs.reached(),
329                            })
330                        }),
331                        reaching: Box::new(move |bin| guard_reaching_tests(bin, id)),
332                    }
333                } else {
334                    // A guard that may have side effects, overloaded ops/methods, or early
335                    // exits cannot be proved equivalent to a constant solely from its return
336                    // value: run all reaching tests (including early-exit tests).
337                    let run = [Mutation::Const(true), Mutation::Const(false)]
338                        .into_iter()
339                        .filter(allowed)
340                        .collect();
341                    SitePlan {
342                        constant: false,
343                        cannot_differ: false,
344                        redundant_logic_swap: false,
345                        gaps: vec![],
346                        run,
347                        infected: Box::new(move |bin, _| guard_reaching_tests(bin, id)),
348                        reaching: Box::new(move |bin| guard_reaching_tests(bin, id)),
349                    }
350                }
351            }
352            SiteKind::Arm { .. } if reached() => reach_plan(Mutation::Delete),
353            SiteKind::Arm { .. } => return Planned::Unreached,
354            SiteKind::Quantifier { .. } if reached() => reach_plan(Mutation::QuantifierSwap),
355            SiteKind::Position { .. } if reached() => reach_plan(Mutation::PositionSwap),
356            SiteKind::LoopCtrl { .. } if reached() => reach_plan(Mutation::LoopCtrlSwap),
357            SiteKind::LoopCtrl { .. } => return Planned::Unreached,
358            SiteKind::RangeContains { .. } => {
359                let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
360                if merged.opaque {
361                    return Planned::Nothing;
362                }
363                if !merged.same && !merged.differs {
364                    return Planned::Unreached;
365                }
366                if !merged.differs {
367                    let gaps = report::range_contains_gap_finding(file, site, verify)
368                        .map(|finding| PlannedGap {
369                            finding,
370                            survivors: vec![Mutation::RangeEnd],
371                            constant_expr: None,
372                        })
373                        .into_iter()
374                        .collect();
375                    SitePlan {
376                        constant: false,
377                        cannot_differ: false,
378                        redundant_logic_swap: false,
379                        gaps,
380                        run: vec![],
381                        infected: Box::new(|_, _| BTreeSet::new()),
382                        reaching: Box::new(move |bin| {
383                            tests_where(bin.trace.arith.get(&id), |obs| obs.same || obs.differs)
384                        }),
385                    }
386                } else {
387                    SitePlan {
388                        constant: false,
389                        cannot_differ: false,
390                        redundant_logic_swap: false,
391                        gaps: vec![],
392                        run: vec![Mutation::RangeEnd],
393                        infected: Box::new(move |bin, _| {
394                            tests_where(bin.trace.arith.get(&id), |obs| obs.differs)
395                        }),
396                        reaching: Box::new(move |bin| {
397                            tests_where(bin.trace.arith.get(&id), |obs| obs.same || obs.differs)
398                        }),
399                    }
400                }
401            }
402            SiteKind::LiteralSet { elements, .. } => {
403                let merged = self.merged(|t| t.lit_set.get(&id), plan::LitSetObs::merge);
404                if merged.opaque {
405                    return Planned::Nothing;
406                }
407                if !merged.reached {
408                    return Planned::Unreached;
409                }
410                let mut gaps = vec![];
411                let mut run = vec![];
412                for i in 0..elements.len().min(8) {
413                    let idx = i as u8;
414                    let m = Mutation::DropLiteralElem(idx);
415                    if merged.matched_elem(idx) {
416                        run.push(m);
417                    } else if let Some(finding) =
418                        report::literal_set_gap_finding(file, site, idx, verify)
419                    {
420                        gaps.push(PlannedGap {
421                            finding,
422                            survivors: vec![m],
423                            constant_expr: None,
424                        });
425                    }
426                }
427                SitePlan {
428                    constant: false,
429                    cannot_differ: false,
430                    redundant_logic_swap: false,
431                    gaps,
432                    run,
433                    infected: Box::new(move |bin, m| {
434                        tests_where(bin.trace.lit_set.get(&id), |obs| match m {
435                            Mutation::DropLiteralElem(idx) => obs.matched_elem(idx),
436                            _ => obs.reached,
437                        })
438                    }),
439                    reaching: Box::new(move |bin| {
440                        tests_where(bin.trace.lit_set.get(&id), |obs| obs.reached)
441                    }),
442                }
443            }
444            SiteKind::Not { .. } if reached() => reach_plan(Mutation::DropNot),
445            // `a..=b` with `b` the largest value of its type is no range the probe could
446            // return in place of `a..b`: the mutant would run as the original and pass.
447            SiteKind::Range { .. } if reached() => {
448                if self
449                    .binaries
450                    .iter()
451                    .any(|b| b.trace.ranges_at_top.contains(&id))
452                {
453                    return Planned::NotEvaluated;
454                }
455                reach_plan(Mutation::RangeEnd)
456            }
457            // `!` on an integer or a user type is not negation of a condition, a range of
458            // something other than integers has no "one more", and `.all`/`.any` on a
459            // non-`Iterator` type is opaque.
460            SiteKind::Not { .. }
461            | SiteKind::Range { .. }
462            | SiteKind::Quantifier { .. }
463            | SiteKind::Position { .. } => {
464                if self
465                    .merged(|t| t.arith.get(&id), plan::ArithObs::merge)
466                    .opaque
467                {
468                    return Planned::Nothing;
469                }
470                return Planned::Unreached;
471            }
472            SiteKind::Cmp {
473                op,
474                literal,
475                lhs,
476                rhs,
477                gap: operator,
478            } => {
479                let op = *op;
480                let mut merged = Obs::default();
481                for bin in &self.binaries {
482                    merged.merge(&bin.trace.merged(id));
483                }
484                // The types of the operands, where every binary that recorded them
485                // agrees (a type can be another under `cfg(test)`).
486                let mut recorded = self.binaries.iter().filter_map(|b| b.trace.bounds.get(&id));
487                let bounds = recorded
488                    .next()
489                    .filter(|first| recorded.all(|other| other == *first));
490                // Compared with a number, what cannot be every number has a gap only
491                // where a value it can be lies between the values the tests gave it,
492                // and another outcome only if a value it can be gives one.
493                // Only for an operation of the language: one a type defines for itself
494                // (`impl Mul<u32> for Eighths`) can give any number.
495                let against = match literal {
496                    LiteralSide::Rhs(number) => {
497                        Some((lhs, (site.start, operator.0), *number, true))
498                    }
499                    LiteralSide::Lhs(number) => Some((rhs, (operator.1, site.end), *number, false)),
500                    LiteralSide::None => None,
501                }
502                .and_then(|(expr, (from, to), number, is_rhs)| {
503                    let (reach, shift) = instrument::reach(expr)?;
504                    // A number past the values of the type it is compared with is
505                    // another number there: nothing is read from how it is written.
506                    let (low, high) = bounds.map(|b| if is_rhs { b.lhs } else { b.rhs })?;
507                    if number < low || number > high {
508                        return None;
509                    }
510                    // A shift by the width of its type or more is a shift by less when
511                    // overflow is not checked: the type says by how much.
512                    let reach = match shift {
513                        Some(bits) => plan::Reach::of_shift(
514                            bits,
515                            bounds.map(|b| if is_rhs { b.lhs } else { b.rhs })?,
516                        )?,
517                        None => reach,
518                    };
519                    // A literal past the largest value of the type is another number
520                    // there (`255i8` is -1 where that is allowed): nothing is read from it.
521                    // Without the type nothing is read from it. A shift was checked
522                    // against the width already (its stride need not be a value).
523                    let fits = |value: i128| {
524                        bounds.is_some_and(|b| value <= if is_rhs { b.lhs.1 } else { b.rhs.1 })
525                    };
526                    let (plan::Reach::Multiples(value)
527                    | plan::Reach::Bits(value)
528                    | plan::Reach::Below(value)) = reach;
529                    ((shift.is_some() || fits(value)) && primitive(from, to))
530                        .then_some((reach, number, is_rhs))
531                });
532                let mut domain = domain_of(*literal, bounds);
533                // Between the least and the greatest value it can be: by what it is
534                // (a mask, a remainder), or within its type (the multiples).
535                let ends = against.and_then(|(reach, _, is_rhs)| {
536                    reach.interval().or_else(|| {
537                        let (low, high) = bounds.map(|b| if is_rhs { b.lhs } else { b.rhs })?;
538                        reach.within(low, high)
539                    })
540                });
541                if let Some((_, number, is_rhs)) = against
542                    && let Some((low, high)) = ends
543                    && let (Some(a), Some(b)) = if is_rhs {
544                        (low.checked_sub(number), high.checked_sub(number))
545                    } else {
546                        (number.checked_sub(high), number.checked_sub(low))
547                    }
548                {
549                    domain = Some(match domain {
550                        Some((lo, hi)) => (lo.max(a), hi.min(b)),
551                        None => (a, b),
552                    });
553                }
554                let mut cmp_plan = plan::plan_cmp(op, &merged, domain);
555                if let Some((reach, number, is_rhs)) = against
556                    && let Some(gap) = cmp_plan.gap.take()
557                {
558                    // Equal to a number it cannot be: there is no other outcome.
559                    if matches!(op, plan::CmpOp::Eq | plan::CmpOp::Ne)
560                        && !reach.holds(number)
561                        && matches!(gap, plan::InputGap::OneSided { .. })
562                    {
563                        cmp_plan.cannot_differ = true;
564                    } else {
565                        cmp_plan.gap = plan::within_reach(gap, op, &merged, reach, number, is_rhs);
566                    }
567                }
568                let mut gaps = vec![];
569                let mut constant = false;
570                match &cmp_plan.gap {
571                    Some(plan::InputGap::Unreached) => return Planned::Unreached,
572                    Some(gap) => {
573                        constant = matches!(gap, plan::InputGap::OneSided { .. });
574                        if let Some(finding) =
575                            report::input_gap_finding(file, site, gap, &merged, verify)
576                        {
577                            gaps.push(PlannedGap {
578                                finding,
579                                survivors: gap.survivors(),
580                                constant_expr: None,
581                            });
582                        }
583                    }
584                    None => {}
585                }
586                SitePlan {
587                    gaps,
588                    constant,
589                    cannot_differ: cmp_plan.cannot_differ,
590                    redundant_logic_swap: false,
591                    run: cmp_plan.run,
592                    infected: Box::new(move |bin, m| {
593                        tests_where(bin.trace.cmp.get(&id), |obs| plan::infects(op, m, obs))
594                    }),
595                    reaching: Box::new(move |bin| {
596                        tests_where(bin.trace.cmp.get(&id), Obs::reached)
597                    }),
598                }
599            }
600            SiteKind::Logic {
601                and,
602                lhs,
603                rhs,
604                gap: op_gap,
605            } => {
606                let and = *and;
607                let lhs_range = core_range(site.start, lhs);
608                let rhs_range = core_range(op_gap.1, rhs);
609                let merged = self.merged(|t| t.logic.get(&id), plan::LogicObs::merge);
610                let logic_plan = plan::plan_logic(and, &merged);
611                if logic_plan.gaps.contains(&plan::LogicGap::Unreached) {
612                    return Planned::Unreached;
613                }
614                let gaps: Vec<_> = logic_plan
615                    .gaps
616                    .iter()
617                    .filter_map(|gap| {
618                        // "The operand never decides" is the same statement as "the operand
619                        // had one value whenever it was evaluated".
620                        let (mutation, operand) = match gap {
621                            plan::LogicGap::RhsNeverDecides => (Mutation::LogicDropRhs, rhs_range),
622                            _ => (Mutation::LogicDropLhs, lhs_range),
623                        };
624                        Some(PlannedGap {
625                            finding: report::logic_gap_finding(file, site, *gap, verify)?,
626                            survivors: vec![mutation],
627                            constant_expr: Some(operand),
628                        })
629                    })
630                    .collect();
631                SitePlan {
632                    constant: merged.constant_value(and).is_some(),
633                    cannot_differ: false,
634                    redundant_logic_swap: merged.swap_never_changes_value(and)
635                        && instrument::is_pure_logic_operand(rhs),
636                    gaps,
637                    run: logic_plan.run,
638                    infected: Box::new(move |bin, m| {
639                        tests_where(bin.trace.logic.get(&id), |obs| {
640                            plan::logic_infects(and, m, obs)
641                        })
642                    }),
643                    reaching: Box::new(move |bin| {
644                        tests_where(bin.trace.logic.get(&id), plan::LogicObs::reached)
645                    }),
646                }
647            }
648            SiteKind::Arith { .. }
649            | SiteKind::MinMax { .. }
650            | SiteKind::SliceEnd { .. }
651            | SiteKind::StrAffix { .. }
652            | SiteKind::StrReplace { .. }
653            | SiteKind::Clamp { .. }
654            | SiteKind::Rounding { .. }
655            | SiteKind::SaturatingArith { .. }
656            | SiteKind::StrTrim { .. }
657            | SiteKind::StrCaseEq { .. }
658            | SiteKind::Abs { .. }
659            | SiteKind::IterLimit { .. }
660            | SiteKind::EndianSwap { .. }
661            | SiteKind::BitCount { .. } => {
662                // `max` / `min` and other value-aware method probes share the 1- or 2-slot
663                // `ArithObs` recording protocol: they agree when the original and replacement
664                // compute identical values on every observed input.
665                let merged = self.merged(|t| t.arith.get(&id), plan::ArithObs::merge);
666                let mutations: Vec<(Mutation, plan::ArithObs)> = match &site.kind {
667                    SiteKind::MinMax { .. } => vec![(Mutation::MinMax, merged)],
668                    SiteKind::SliceEnd { .. } => vec![(Mutation::OtherEnd, merged)],
669                    SiteKind::StrAffix { .. } => vec![(Mutation::StrContains, merged)],
670                    SiteKind::StrReplace { .. } => {
671                        vec![(Mutation::StrReplaceMultiplicity, merged)]
672                    }
673                    SiteKind::Clamp { .. } => vec![
674                        (Mutation::ClampDropLower, merged),
675                        (Mutation::ClampDropUpper, merged.second()),
676                    ],
677                    SiteKind::Rounding { .. } => vec![
678                        (Mutation::RoundAlt1, merged),
679                        (Mutation::RoundAlt2, merged.second()),
680                    ],
681                    SiteKind::SaturatingArith { .. } => vec![(Mutation::SaturatingSwap, merged)],
682                    SiteKind::StrTrim { op, .. } => {
683                        let mut out = vec![(Mutation::TrimAlt1, merged)];
684                        if op.alt2().is_some() {
685                            out.push((Mutation::TrimAlt2, merged.second()));
686                        }
687                        out
688                    }
689                    SiteKind::StrCaseEq { .. } => vec![(Mutation::StrExactEq, merged)],
690                    SiteKind::Abs { .. } => vec![(Mutation::DropAbs, merged)],
691                    SiteKind::IterLimit { .. } => vec![(Mutation::IterLimitDrop, merged)],
692                    SiteKind::EndianSwap { .. } => vec![(Mutation::EndianSwap, merged)],
693                    SiteKind::BitCount { .. } => vec![(Mutation::BitCountSwap, merged)],
694                    SiteKind::Arith {
695                        op,
696                        assign,
697                        lhs,
698                        rhs,
699                        gap,
700                        local_types,
701                        shadowed_prims,
702                        ..
703                    } if op.second(*assign).is_some() => {
704                        let disjoint_or_xor = !*assign
705                            && !merged.differs2
706                            && matches!(
707                                op,
708                                instrument::ArithOp::BitOr | instrument::ArithOp::BitXor
709                            )
710                            && {
711                                let mut recorded =
712                                    self.binaries.iter().filter_map(|b| b.trace.bounds.get(&id));
713                                let bounds = recorded
714                                    .next()
715                                    .filter(|first| recorded.all(|other| other == *first))
716                                    .map(|b| b.lhs);
717                                instrument::disjoint_bits(
718                                    lhs,
719                                    site.start,
720                                    rhs,
721                                    gap.1,
722                                    bounds,
723                                    primitive,
724                                    local_types,
725                                    shadowed_prims,
726                                    cast_bounds,
727                                )
728                            };
729                        if disjoint_or_xor {
730                            vec![(Mutation::ArithSwap, merged)]
731                        } else {
732                            vec![
733                                (Mutation::ArithSwap, merged),
734                                (Mutation::ArithSwap2, merged.second()),
735                            ]
736                        }
737                    }
738                    _ => vec![(Mutation::ArithSwap, merged)],
739                };
740                // A `first()` that did not give the first element of the sequence is a
741                // method of another name's making: its `last()` is anyone's guess.
742                if matches!(
743                    site.kind,
744                    SiteKind::SliceEnd { .. }
745                        | SiteKind::StrAffix { .. }
746                        | SiteKind::StrReplace { .. }
747                        | SiteKind::Clamp { .. }
748                        | SiteKind::Rounding { .. }
749                        | SiteKind::SaturatingArith { .. }
750                        | SiteKind::StrTrim { .. }
751                        | SiteKind::StrCaseEq { .. }
752                        | SiteKind::Abs { .. }
753                        | SiteKind::IterLimit { .. }
754                        | SiteKind::EndianSwap { .. }
755                        | SiteKind::BitCount { .. }
756                ) && merged.opaque
757                {
758                    return Planned::Nothing;
759                }
760                let (mut gaps, mut run) = (vec![], vec![]);
761                for (mutation, seen) in mutations {
762                    match plan::plan_arith(&seen) {
763                        plan::ArithPlan::Unreached => return Planned::Unreached,
764                        // Not numbers (`String + &str`, `Duration + Duration`): nothing to mutate.
765                        plan::ArithPlan::Opaque => return Planned::Nothing,
766                        plan::ArithPlan::NeverDiffers => {
767                            let finding = match mutation {
768                                Mutation::MinMax => report::min_max_gap_finding(file, site, verify),
769                                Mutation::OtherEnd => {
770                                    report::slice_end_gap_finding(file, site, verify)
771                                }
772                                Mutation::StrContains => {
773                                    report::str_affix_gap_finding(file, site, verify)
774                                }
775                                Mutation::StrReplaceMultiplicity => {
776                                    report::str_replace_gap_finding(file, site, verify)
777                                }
778                                Mutation::ClampDropLower | Mutation::ClampDropUpper => {
779                                    report::clamp_gap_finding(file, site, mutation, verify)
780                                }
781                                Mutation::RoundAlt1 | Mutation::RoundAlt2 => {
782                                    report::rounding_gap_finding(file, site, mutation, verify)
783                                }
784                                Mutation::SaturatingSwap => {
785                                    report::saturating_gap_finding(file, site, verify)
786                                }
787                                Mutation::TrimAlt1 | Mutation::TrimAlt2 => {
788                                    report::str_trim_gap_finding(file, site, mutation, verify)
789                                }
790                                Mutation::StrExactEq => {
791                                    report::str_case_eq_gap_finding(file, site, verify)
792                                }
793                                Mutation::DropAbs => report::abs_gap_finding(file, site, verify),
794                                Mutation::IterLimitDrop => {
795                                    report::iter_limit_gap_finding(file, site, verify)
796                                }
797                                Mutation::EndianSwap => {
798                                    report::endian_gap_finding(file, site, verify)
799                                }
800                                Mutation::BitCountSwap => {
801                                    report::bit_count_gap_finding(file, site, verify)
802                                }
803                                _ => report::arith_gap_finding(file, site, mutation, verify),
804                            };
805                            gaps.extend(finding.map(|finding| PlannedGap {
806                                finding,
807                                survivors: vec![mutation],
808                                constant_expr: None,
809                            }));
810                        }
811                        plan::ArithPlan::Run => run.push(mutation),
812                    }
813                }
814                SitePlan {
815                    gaps,
816                    constant: false,
817                    cannot_differ: false,
818                    redundant_logic_swap: false,
819                    run,
820                    infected: Box::new(move |bin, m| {
821                        tests_where(bin.trace.arith.get(&id), |obs| obs.infected_by(m))
822                    }),
823                    reaching: Box::new(move |bin| {
824                        tests_where(bin.trace.arith.get(&id), |obs| {
825                            obs.same || obs.differs || obs.same2 || obs.differs2
826                        })
827                    }),
828                }
829            }
830            SiteKind::Return {
831                sole_expr, option, ..
832            } => {
833                let sole_expr = *sole_expr;
834                let is_option = option.is_some();
835                let merged = self.merged(|t| t.returns.get(&id), plan::ReturnObs::merge);
836                let return_plan = if is_option {
837                    plan::plan_option_return(&merged)
838                } else {
839                    plan::plan_return(&merged)
840                };
841                if return_plan.unreached {
842                    return Planned::Unreached;
843                }
844                let gaps: Vec<_> = return_plan
845                    .always
846                    .and_then(|always| {
847                        Some(PlannedGap {
848                            finding: report::return_gap_finding(file, site, always, verify)?,
849                            survivors: vec![Mutation::Const(always)],
850                            // A body that is one expression returns that expression's value.
851                            constant_expr: sole_expr,
852                        })
853                    })
854                    .into_iter()
855                    .collect();
856                SitePlan {
857                    constant: false,
858                    cannot_differ: false,
859                    redundant_logic_swap: false,
860                    gaps,
861                    run: return_plan.run,
862                    infected: Box::new(move |bin, m| {
863                        tests_where(bin.trace.returns.get(&id), |obs| match m {
864                            Mutation::Const(value) => obs.infected_by_const(value),
865                            _ => obs.reached(),
866                        })
867                    }),
868                    reaching: Box::new(move |bin| {
869                        tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached)
870                    }),
871                }
872            }
873        })
874    }
875
876    pub(super) fn job(
877        &self,
878        site: u32,
879        mutation: Mutation,
880        tests_of: &dyn Fn(&TestBinary) -> BTreeSet<String>,
881    ) -> Job {
882        let tests = self
883            .binaries
884            .iter()
885            .enumerate()
886            .filter_map(|(index, bin)| {
887                let tests = tests_of(bin);
888                if tests.is_empty() {
889                    return None;
890                }
891                let filter = match bin.runner {
892                    Runner::Exe(_) => test_filter(&tests, &bin.tests),
893                    Runner::Doc { .. } | Runner::Isolated { .. } | Runner::Nextest { .. } => None,
894                };
895                Some((index, filter))
896            })
897            .collect();
898        Job {
899            site,
900            mutation,
901            tests,
902        }
903    }
904
905    /// Runs one mutant against its tests, stopping at the first test that fails.
906    /// Runs one mutant while `sharing` jobs run at the same time.
907    pub(super) fn run_job(&self, job: &Job, sharing: usize) -> Result<JobResult> {
908        let spec = format!("{}:{}", job.site, job.mutation.encode());
909        let mut passed = vec![];
910        // One failure is enough: the quick binaries first.
911        let mut tests: Vec<&(usize, Option<Vec<String>>)> = job.tests.iter().collect();
912        tests.sort_by_key(|(index, _)| self.binaries[*index].baseline);
913        for (index, filter) in tests {
914            let bin = &self.binaries[*index];
915            let outcome = run_binary(
916                bin,
917                filter.as_deref(),
918                &[("TMT_MUTANT", &spec)],
919                bin.filtered_limit(filter.as_deref(), false, sharing),
920                RunOutput::FirstFailure,
921                sharing,
922            )?;
923            if outcome != Outcome::Pass {
924                return Ok(JobResult {
925                    first_pass_timeout: false,
926                    unconfirmed_timeout: false,
927                    survived: None,
928                    timed_out: outcome == Outcome::Timeout,
929                    unable: outcome == Outcome::Unable,
930                });
931            }
932            match filter {
933                Some(names) => passed.extend(names.iter().cloned()),
934                None if matches!(bin.runner, Runner::Isolated { .. }) => {
935                    passed.push(bin.name.clone())
936                }
937                None => passed.push(format!("all tests of `{}`", bin.name)),
938            }
939        }
940        Ok(JobResult {
941            first_pass_timeout: false,
942            unconfirmed_timeout: false,
943            survived: Some(passed),
944            timed_out: false,
945            unable: false,
946        })
947    }
948
949    /// Runs a surviving mutant once more with tracing on, and returns what it changed in
950    /// each test compared with the original run.
951    pub(super) fn trace_job(
952        &self,
953        job: &Job,
954        scratch: &Path,
955        sharing: usize,
956    ) -> Result<BTreeMap<String, BTreeSet<Change>>> {
957        let spec = format!("{}:{}", job.site, job.mutation.encode());
958        let mut all: BTreeMap<String, BTreeSet<Change>> = BTreeMap::new();
959        for (index, filter) in &job.tests {
960            let bin = &self.binaries[*index];
961            let path = scratch.join(format!("effects-{}-{index}.tsv", job.site));
962            let _ = fs::remove_file(&path);
963            let trace_env = path.to_string_lossy().into_owned();
964            let outcome = run_binary(
965                bin,
966                filter.as_deref(),
967                &[("TMT_MUTANT", &spec), ("TMT_TRACE", &trace_env)],
968                bin.filtered_limit(filter.as_deref(), true, sharing),
969                RunOutput::Quiet,
970                sharing,
971            )?;
972            let text = fs::read_to_string(&path).unwrap_or_default();
973            let _ = fs::remove_file(&path);
974            if outcome != Outcome::Pass {
975                continue; // not the run we saw before: say nothing rather than guess
976            }
977            let mutated = Trace::parse(&text);
978            let ran: Option<BTreeSet<String>> =
979                filter.as_ref().map(|names| names.iter().cloned().collect());
980            let baseline = bin
981                .effects_baseline
982                .get_or_init(|| propagation::BaselineIndex::new(&bin.trace));
983            for (test, found) in baseline.changes(&mutated, ran.as_ref(), job.site) {
984                all.entry(test).or_default().extend(found);
985            }
986        }
987        Ok(all)
988    }
989
990    /// Runs every job exactly once on `workers` threads (formal/tla/JobPool.tla) and
991    /// returns the results in job order.
992    /// Runs the mutants, `workers` at a time. A mutant that ran out of time while others
993    /// were running may only have been slowed down by them: it gets a second run on its
994    /// own, and that one counts.
995    pub(super) fn run_jobs(
996        &self,
997        jobs: &[Job],
998        workers: usize,
999        label: &str,
1000        checkpoint: Option<&Phase<'_>>,
1001    ) -> Result<Vec<JobResult>> {
1002        if self
1003            .binaries
1004            .first()
1005            .is_some_and(|bin| bin.timeout.is_some())
1006        {
1007            for (index, filter) in jobs.iter().flat_map(|job| &job.tests) {
1008                self.binaries[*index].warn_timeout_conflict(filter.as_deref());
1009            }
1010        }
1011        if workers > 1 {
1012            // Measure unique slow filtered baselines serially for uncached jobs before
1013            // spawning parallel workers, using the same thread-sharing budget that the
1014            // parallel pool will use so timings are neither contended nor optimistic.
1015            let pending: Vec<usize> = (0..jobs.len())
1016                .filter(|&index| {
1017                    checkpoint
1018                        .is_none_or(|phase| phase.get::<JobResult>(index).ok().flatten().is_none())
1019                })
1020                .collect();
1021            if pending.len() > 1 {
1022                let parallel_sharing = workers.clamp(1, jobs.len().max(1));
1023                let interrupted_partial = || -> Result<Vec<JobResult>> {
1024                    (0..jobs.len())
1025                        .map(|i| {
1026                            Ok(checkpoint
1027                                .map(|phase| {
1028                                    let res = phase.get::<JobResult>(i)?;
1029                                    if res.is_some() {
1030                                        phase.mark_reused();
1031                                    }
1032                                    Ok::<_, anyhow::Error>(res)
1033                                })
1034                                .transpose()?
1035                                .flatten()
1036                                .unwrap_or_else(JobResult::not_evaluated))
1037                        })
1038                        .collect()
1039                };
1040                for index in pending {
1041                    if crate::interrupt::is_interrupted() {
1042                        return interrupted_partial();
1043                    }
1044                    for (bin_index, filter) in &jobs[index].tests {
1045                        if crate::interrupt::is_interrupted() {
1046                            return interrupted_partial();
1047                        }
1048                        self.binaries[*bin_index].filtered_limit(
1049                            filter.as_deref(),
1050                            false,
1051                            parallel_sharing,
1052                        );
1053                    }
1054                }
1055            }
1056        }
1057        let run = |index: usize, sharing| self.run_job(&jobs[index], sharing);
1058        evaluate_jobs(
1059            jobs.len(),
1060            workers,
1061            self.serial_timeout_rechecks,
1062            self.progress,
1063            label,
1064            checkpoint,
1065            &run,
1066        )
1067    }
1068}
1069
1070pub(super) fn evaluate_jobs(
1071    count: usize,
1072    workers: usize,
1073    serial_rechecks: bool,
1074    progress_enabled: bool,
1075    label: &str,
1076    checkpoint: Option<&Phase<'_>>,
1077    run: &(impl Fn(usize, usize) -> Result<JobResult> + Sync),
1078) -> Result<Vec<JobResult>> {
1079    let sharing = workers.clamp(1, count.max(1));
1080    let mut results = progress::track(progress_enabled, label, count, |progress| {
1081        run_pool_partial(count, workers, |index| {
1082            if let Some(cached) = checkpoint
1083                .map(|phase| phase.get::<JobResult>(index))
1084                .transpose()?
1085                .flatten()
1086            {
1087                if let Some(phase) = checkpoint {
1088                    phase.mark_reused();
1089                }
1090                progress.complete_cached(cached.progress_outcome());
1091                return Ok((cached, false));
1092            }
1093            let mut result = run(index, sharing)?;
1094            if sharing > 1 && result.timed_out {
1095                result.first_pass_timeout = true;
1096                result.unconfirmed_timeout = true;
1097            }
1098            let pending = result.unconfirmed_timeout && serial_rechecks;
1099            if !pending {
1100                if let Some(phase) = checkpoint {
1101                    phase.record(index, &result)?;
1102                }
1103                progress.complete(result.progress_outcome());
1104            }
1105            Ok((result, pending))
1106        })
1107    })?;
1108    if crate::interrupt::is_interrupted() {
1109        return Ok(results
1110            .into_iter()
1111            .map(|slot| match slot {
1112                Some((result, false)) => result,
1113                _ => JobResult::not_evaluated(),
1114            })
1115            .collect());
1116    }
1117    let pending: Vec<_> = results
1118        .iter()
1119        .enumerate()
1120        .filter_map(|(index, slot)| {
1121            slot.as_ref()
1122                .and_then(|(_, pending)| pending.then_some(index))
1123        })
1124        .collect();
1125    if !pending.is_empty() && progress_enabled {
1126        eprintln!(
1127            "tmt: {label}: {} first-pass timeouts, {} pending serial rechecks",
1128            pending.len(),
1129            if serial_rechecks { pending.len() } else { 0 }
1130        );
1131    }
1132    if serial_rechecks {
1133        let mut interrupted = false;
1134        progress::track_timeout_rechecks(progress_enabled, pending.len(), |progress| {
1135            for index in pending {
1136                if crate::interrupt::is_interrupted() {
1137                    interrupted = true;
1138                    break;
1139                }
1140                let mut confirmed = match run(index, 1) {
1141                    Ok(confirmed) => confirmed,
1142                    Err(err) if crate::interrupt::is_interrupted_err(&err) => {
1143                        interrupted = true;
1144                        break;
1145                    }
1146                    Err(err) => return Err(err),
1147                };
1148                confirmed.first_pass_timeout = true;
1149                let outcome = if confirmed.timed_out {
1150                    progress::Outcome::TimedOut
1151                } else if confirmed.unable {
1152                    progress::Outcome::Unable
1153                } else {
1154                    progress::Outcome::Survived
1155                };
1156                if let Some(phase) = checkpoint {
1157                    phase.record(index, &confirmed)?;
1158                }
1159                results[index] = Some((confirmed, false));
1160                progress.complete(outcome);
1161            }
1162            Ok::<_, anyhow::Error>(())
1163        })?;
1164        if interrupted || crate::interrupt::is_interrupted() {
1165            return Ok(results
1166                .into_iter()
1167                .map(|slot| match slot {
1168                    Some((result, false)) => result,
1169                    _ => JobResult::not_evaluated(),
1170                })
1171                .collect());
1172        }
1173    }
1174    if let Some(phase) = checkpoint {
1175        phase.finish()?;
1176    }
1177    Ok(results
1178        .into_iter()
1179        .map(|slot| match slot {
1180            Some((result, _)) => result,
1181            None => JobResult::not_evaluated(),
1182        })
1183        .collect())
1184}
1185
1186/// Tests that reached a `match` guard (either returning a bool or exiting early).
1187fn guard_reaching_tests(bin: &TestBinary, id: u32) -> BTreeSet<String> {
1188    let mut tests = tests_where(bin.trace.returns.get(&id), plan::ReturnObs::reached);
1189    if let Some(reached) = bin.trace.reach.get(&id) {
1190        tests.extend(reached.iter().cloned());
1191    }
1192    tests
1193}
1194
1195/// Strictly side-effect-free guard expression: no calls, no methods, no indexing, no
1196/// `Deref` (including implicit field `Deref`), and no user-overloaded operators (including
1197/// `!`). A top-level binary comparison is accepted only when runtime `trace.bounds` proved
1198/// it compared primitive numbers/chars and both operands are plain literals or paths.
1199fn is_strictly_pure_guard(expr_text: &str, is_prim_cmp: bool) -> bool {
1200    fn is_trivial_value(expr: &syn::Expr) -> bool {
1201        match expr {
1202            syn::Expr::Lit(_) | syn::Expr::Path(_) => true,
1203            syn::Expr::Paren(e) => is_trivial_value(&e.expr),
1204            syn::Expr::Group(e) => is_trivial_value(&e.expr),
1205            _ => false,
1206        }
1207    }
1208    let Ok(expr) = syn::parse_str::<syn::Expr>(expr_text) else {
1209        return false;
1210    };
1211    if is_trivial_value(&expr) {
1212        return true;
1213    }
1214    if is_prim_cmp
1215        && let syn::Expr::Binary(bin) = &expr
1216        && is_trivial_value(&bin.left)
1217        && is_trivial_value(&bin.right)
1218    {
1219        return true;
1220    }
1221    false
1222}
1223
1224impl std::str::FromStr for report::Shard {
1225    type Err = anyhow::Error;
1226
1227    fn from_str(text: &str) -> Result<Self> {
1228        let (index, count) = text.split_once('/').context("expected a shard index K/N")?;
1229        let index: usize = index.parse().context("invalid shard index")?;
1230        let count: usize = count.parse().context("invalid shard count")?;
1231        if index >= count {
1232            bail!("shard index must be less than the shard count");
1233        }
1234        Ok(Self {
1235            index,
1236            count,
1237            round_robin: false,
1238        })
1239    }
1240}
1241
1242impl report::Shard {
1243    pub(super) fn contains(self, candidate: usize, candidates: usize) -> bool {
1244        candidate < candidates
1245            && (if self.round_robin {
1246                candidate % self.count
1247            } else {
1248                candidate / candidates.div_ceil(self.count)
1249            }) == self.index
1250    }
1251}