Skip to main content

targeted_mutation/
propagation.rs

1//! What a surviving mutant changes further down: the difference between the trace of the
2//! original and the trace of the same tests with the mutant switched on.
3//!
4//! An assertion gap says "these tests run the changed code and pass". This says what the
5//! change did in those tests, which is where an assertion can catch it. If it did
6//! nothing, the tests do not use the result of the mutated code.
7
8use std::collections::{BTreeMap, BTreeSet};
9
10use crate::plan::{LogicObs, Obs, ReturnObs};
11use crate::trace::Trace;
12
13/// One difference in one test, at a site other than the mutated one.
14#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
15pub enum Change {
16    /// A `-> bool` function now also returns this value.
17    Returns { site: u32, value: bool },
18    /// A statement, operator or comparison that the test did not execute before.
19    NowRuns { site: u32 },
20    /// Executed before, not any more.
21    NoLongerRuns { site: u32 },
22    /// A comparison or condition is evaluated with operands in a relation not seen before.
23    NewOutcome { site: u32 },
24}
25
26impl Change {
27    pub fn site(&self) -> u32 {
28        match self {
29            Change::Returns { site, .. }
30            | Change::NowRuns { site }
31            | Change::NoLongerRuns { site }
32            | Change::NewOutcome { site } => *site,
33        }
34    }
35}
36
37/// Everything one test did at one site, reduced to what can be compared.
38#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
39struct Seen {
40    reached: bool,
41    /// Relations of a comparison, or the observation bits of `&&` / `||`.
42    outcomes: u8,
43    returned_true: bool,
44    returned_false: bool,
45}
46
47type Sites = BTreeMap<u32, Seen>;
48type IndexedSites = Box<[(u32, Seen)]>;
49
50fn per_test(trace: &Trace) -> BTreeMap<&str, Sites> {
51    let mut all: BTreeMap<&str, Sites> = BTreeMap::new();
52    for (site, tests) in &trace.reach {
53        for test in tests {
54            all.entry(test)
55                .or_default()
56                .entry(*site)
57                .or_default()
58                .reached = true;
59        }
60    }
61    for (site, tests) in &trace.cmp {
62        for (test, obs) in tests {
63            let Obs { lt, eq, gt, un, .. } = *obs;
64            let seen = all.entry(test).or_default().entry(*site).or_default();
65            seen.reached |= obs.reached();
66            // tmt:ignore the bits do not overlap, so `^` joins them just as well
67            seen.outcomes |= lt as u8 | (eq as u8) << 1 | (gt as u8) << 2 | (un as u8) << 3;
68        }
69    }
70    for (site, tests) in &trace.logic {
71        for (test, obs) in tests {
72            let LogicObs {
73                short,
74                rhs_true,
75                rhs_false,
76                // Not an outcome: it comes with every value the right operand gives.
77                rhs_started: _,
78            } = *obs;
79            let seen = all.entry(test).or_default().entry(*site).or_default();
80            seen.reached |= obs.reached();
81            // tmt:ignore the bits do not overlap, so `^` joins them just as well
82            seen.outcomes |= short as u8 | (rhs_true as u8) << 1 | (rhs_false as u8) << 2;
83        }
84    }
85    for (site, tests) in &trace.arith {
86        for (test, obs) in tests {
87            all.entry(test)
88                .or_default()
89                .entry(*site)
90                .or_default()
91                .reached |= obs.same || obs.differs || obs.opaque;
92        }
93    }
94    for (site, tests) in &trace.returns {
95        for (test, obs) in tests {
96            let ReturnObs {
97                saw_true,
98                saw_false,
99            } = *obs;
100            let seen = all.entry(test).or_default().entry(*site).or_default();
101            seen.reached |= obs.reached();
102            seen.returned_true |= saw_true;
103            seen.returned_false |= saw_false;
104        }
105    }
106    all
107}
108
109/// The changes per test between `original` and `mutated`, ignoring the mutated site itself
110/// (its probe does not record while its mutant is active). `tests` limits the comparison
111/// to the tests that were run with the mutant; `None` means the whole binary ran.
112pub fn changes(
113    original: &Trace,
114    mutated: &Trace,
115    tests: Option<&BTreeSet<String>>,
116    mutated_site: u32,
117) -> BTreeMap<String, BTreeSet<Change>> {
118    BaselineIndex::new(original).changes(mutated, tests, mutated_site)
119}
120
121/// Baseline observations grouped by test so survivor replays can look up only the tests
122/// they ran and share the index across comparisons.
123pub(crate) struct BaselineIndex(BTreeMap<String, IndexedSites>);
124
125impl BaselineIndex {
126    pub(crate) fn new(original: &Trace) -> Self {
127        Self(
128            per_test(original)
129                .into_iter()
130                .map(|(test, sites)| (test.to_owned(), sites.into_iter().collect()))
131                .collect(),
132        )
133    }
134
135    pub(crate) fn changes(
136        &self,
137        mutated: &Trace,
138        tests: Option<&BTreeSet<String>>,
139        mutated_site: u32,
140    ) -> BTreeMap<String, BTreeSet<Change>> {
141        let mut out = BTreeMap::new();
142        if tests.is_some_and(BTreeSet::is_empty) {
143            return out;
144        }
145        let mut after = per_test(mutated);
146        let mut compare = |test: &str, was: Option<&[(u32, Seen)]>, now: Option<&Sites>| {
147            let found = compare_sites(was.unwrap_or_default(), now, mutated_site);
148            if !found.is_empty() {
149                out.insert(test.to_owned(), found);
150            }
151        };
152        if let Some(tests) = tests {
153            for test in tests {
154                compare(
155                    test,
156                    self.0.get(test).map(Box::as_ref),
157                    after.get(test.as_str()),
158                );
159            }
160        } else {
161            for (test, was) in &self.0 {
162                compare(
163                    test,
164                    Some(was.as_ref()),
165                    after.remove(test.as_str()).as_ref(),
166                );
167            }
168            for (test, now) in &after {
169                compare(test, None, Some(now));
170            }
171        }
172        out
173    }
174}
175
176fn compare_sites(
177    before: &[(u32, Seen)],
178    after: Option<&Sites>,
179    mutated_site: u32,
180) -> BTreeSet<Change> {
181    let mut found = BTreeSet::new();
182    // Both sides are ordered by site, so each observation is visited once.
183    let mut before = before.iter().copied().peekable();
184    let mut after = after
185        .into_iter()
186        .flatten()
187        .map(|(&site, &seen)| (site, seen))
188        .peekable();
189    loop {
190        let site = match (before.peek(), after.peek()) {
191            (Some(&(left, _)), Some(&(right, _))) => left.min(right),
192            (Some(&(site, _)), None) | (None, Some(&(site, _))) => site,
193            (None, None) => break,
194        };
195        let was = before
196            .next_if(|entry| entry.0 == site)
197            .unwrap_or_default()
198            .1;
199        let now = after.next_if(|entry| entry.0 == site).unwrap_or_default().1;
200        if site == mutated_site {
201            continue;
202        }
203        if was.reached && !now.reached {
204            found.insert(Change::NoLongerRuns { site });
205        }
206        if now.reached && !was.reached {
207            found.insert(Change::NowRuns { site });
208        } else if now.outcomes & !was.outcomes != 0 {
209            found.insert(Change::NewOutcome { site });
210        }
211        for (value, now_seen, was_seen) in [
212            (true, now.returned_true, was.returned_true),
213            (false, now.returned_false, was.returned_false),
214        ] {
215            // Only worth saying for a function the test already called.
216            if now_seen && !was_seen && was.reached {
217                found.insert(Change::Returns { site, value });
218            }
219        }
220    }
221    found
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227
228    fn only(test: &str) -> BTreeSet<String> {
229        [test.to_string()].into_iter().collect()
230    }
231
232    #[test]
233    fn indexed_effects_cover_attribution_filter_and_mutated_sites() {
234        let cases = [
235            ("", "R\t1\t{test}\t1\n", vec![Change::NowRuns { site: 1 }]),
236            (
237                "R\t1\t{test}\t1\n",
238                "",
239                vec![Change::NoLongerRuns { site: 1 }],
240            ),
241            (
242                "O\t1\t{test}\t1\t0\t-\t-\t1\t-\t-\n",
243                "O\t1\t{test}\t9\t0\t-\t-\t1\t-\t-\n",
244                vec![Change::NewOutcome { site: 1 }],
245            ),
246            (
247                "L\t1\t{test}\t8\n",
248                "L\t1\t{test}\t10\n",
249                vec![Change::NewOutcome { site: 1 }],
250            ),
251            (
252                "B\t1\t{test}\t2\n",
253                "B\t1\t{test}\t3\n",
254                vec![Change::Returns {
255                    site: 1,
256                    value: true,
257                }],
258            ),
259            (
260                "B\t1\t{test}\t1\n",
261                "B\t1\t{test}\t3\n",
262                vec![Change::Returns {
263                    site: 1,
264                    value: false,
265                }],
266            ),
267            ("O\t1\t{test}\t0\t0\t-\t-\t1\t-\t-\n", "", Vec::new()),
268            ("R\t1\t{test}\t1\n", "R\t1\t{test}\t1\n", Vec::new()),
269            (
270                "R\t1\t{test}\t1\nL\t1\t{test}\t8\nB\t1\t{test}\t2\n",
271                "L\t1\t{test}\t10\nB\t1\t{test}\t3\nA\t1\t{test}\t4\n",
272                vec![
273                    Change::Returns {
274                        site: 1,
275                        value: true,
276                    },
277                    Change::NewOutcome { site: 1 },
278                ],
279            ),
280        ];
281        let empty = BTreeSet::new();
282        for (before, after, changes) in cases {
283            for test in ["selected", crate::trace::UNKNOWN_TEST] {
284                let selected = only(test);
285                let before = Trace::parse(&format!(
286                    "{}R\t2\tbaseline_only\t1\n",
287                    before.replace("{test}", test)
288                ));
289                let after = Trace::parse(&format!(
290                    "{}R\t{}\tmutant_only\t1\n",
291                    after.replace("{test}", test),
292                    u32::MAX,
293                ));
294                let index = BaselineIndex::new(&before);
295                for tests in [None, Some(&selected), Some(&empty)] {
296                    for mutated_site in [0, 1] {
297                        let mut expected = BTreeMap::new();
298                        if tests.is_none() {
299                            expected.insert(
300                                "baseline_only".to_string(),
301                                BTreeSet::from([Change::NoLongerRuns { site: 2 }]),
302                            );
303                            expected.insert(
304                                "mutant_only".to_string(),
305                                BTreeSet::from([Change::NowRuns { site: u32::MAX }]),
306                            );
307                        }
308                        if tests != Some(&empty) && mutated_site != 1 && !changes.is_empty() {
309                            expected.insert(test.to_string(), changes.iter().cloned().collect());
310                        }
311                        assert_eq!(index.changes(&after, tests, mutated_site), expected);
312                    }
313                }
314            }
315        }
316    }
317
318    #[test]
319    fn reusing_index_keeps_disjoint_test_runs_independent() {
320        let original = Trace::parse("R\t1\tt\t1\nR\t2\tu\t1\n");
321        let index = BaselineIndex::new(&original);
322        let mutant_t = Trace::parse("R\t3\tt\t1\nR\t4\t?\t1\n");
323        let mutant_u = Trace::parse("R\t2\tu\t1\n");
324        let expected = BTreeMap::from([(
325            "t".to_string(),
326            BTreeSet::from([
327                Change::NoLongerRuns { site: 1 },
328                Change::NowRuns { site: 3 },
329            ]),
330        )]);
331        assert_eq!(
332            index.changes(&mutant_t, Some(&only("t")), u32::MAX),
333            expected
334        );
335        assert!(
336            index
337                .changes(&mutant_u, Some(&only("u")), u32::MAX)
338                .is_empty()
339        );
340        assert_eq!(
341            index.changes(&mutant_t, Some(&only("t")), u32::MAX),
342            expected
343        );
344    }
345
346    #[test]
347    fn statements_that_start_or_stop_running() {
348        // Both traces reach site 4 after taking different paths through sites 2 and 3.
349        // The merge must find the shared site again without reporting it as an effect.
350        let original = Trace::parse("R\t1\tt\t1\nR\t2\tt\t1\nR\t2\tu\t1\nR\t4\tt\t1\n");
351        let mutated = Trace::parse("R\t1\tt\t1\nR\t3\tt\t1\nR\t2\tu\t1\nR\t4\tt\t1\n");
352        let found = changes(&original, &mutated, None, 9);
353        assert_eq!(found.len(), 1, "{found:?}");
354        assert_eq!(
355            found["t"].iter().cloned().collect::<Vec<_>>(),
356            [
357                Change::NowRuns { site: 3 },
358                Change::NoLongerRuns { site: 2 }
359            ]
360        );
361        assert_eq!(
362            kinds(&changes(&mutated, &original, None, 9)),
363            [
364                Change::NowRuns { site: 2 },
365                Change::NoLongerRuns { site: 3 }
366            ]
367        );
368        // The mutated site itself is never reported.
369        assert!(
370            changes(&original, &mutated, None, 3)["t"]
371                .iter()
372                .all(|c| c.site() != 3)
373        );
374        assert!(
375            !changes(&original, &mutated, None, 2)["t"]
376                .iter()
377                .any(|c| c.site() == 2)
378        );
379    }
380
381    #[test]
382    fn tests_that_were_not_rerun_are_not_compared() {
383        // With the mutant only `t` ran, so `u` is missing from the mutated trace.
384        let original = Trace::parse("R\t1\tt\t1\nR\t1\tu\t1\n");
385        let mutated = Trace::parse("R\t1\tt\t1\n");
386        assert!(changes(&original, &mutated, Some(&only("t")), 9).is_empty());
387        // Had the whole binary run, `u` not running the statement would be a change.
388        assert_eq!(
389            changes(&original, &mutated, None, 9)["u"]
390                .iter()
391                .cloned()
392                .collect::<Vec<_>>(),
393            [Change::NoLongerRuns { site: 1 }]
394        );
395    }
396
397    #[test]
398    fn comparisons_conditions_and_results() {
399        let original =
400            Trace::parse("O\t1\tt\t1\t0\t-3\t-\t1\t-\t-\nL\t2\tt\t1\nB\t3\tt\t2\nA\t4\tt\t1\n");
401        let mutated = Trace::parse(
402            "O\t1\tt\t5\t0\t-3\t2\t1\t-\t-\nL\t2\tt\t3\nB\t3\tt\t3\nA\t4\tt\t2\nB\t5\tt\t1\n",
403        );
404        let found = changes(&original, &mutated, None, 9);
405        assert_eq!(
406            found["t"].iter().cloned().collect::<Vec<_>>(),
407            [
408                Change::Returns {
409                    site: 3,
410                    value: true
411                },
412                // A function the test did not call before is "now runs", not "now returns".
413                Change::NowRuns { site: 5 },
414                Change::NewOutcome { site: 1 },
415                Change::NewOutcome { site: 2 },
416            ]
417        );
418        // Identical traces: nothing propagates.
419        assert!(changes(&original, &original, None, 9).is_empty());
420        // Seeing fewer outcomes than before is not reported as a new outcome.
421        assert!(
422            changes(&mutated, &original, None, 9)["t"]
423                .iter()
424                .all(|c| matches!(c, Change::NoLongerRuns { site: 5 }))
425        );
426    }
427    fn kinds(found: &BTreeMap<String, BTreeSet<Change>>) -> Vec<Change> {
428        found
429            .get("t")
430            .map(|c| c.iter().cloned().collect())
431            .unwrap_or_default()
432    }
433
434    fn cmp_line(rels: u8) -> String {
435        format!("O\t1\tt\t{rels}\t0\t-\t-\t1\t-\t-\n")
436    }
437
438    #[test]
439    fn a_site_of_any_kind_counts_as_run() {
440        let nothing = Trace::parse("");
441        for line in [
442            cmp_line(1),
443            cmp_line(2),
444            cmp_line(4),
445            cmp_line(8),
446            "L\t1\tt\t1\n".to_string(),
447            "L\t1\tt\t2\n".to_string(),
448            "L\t1\tt\t4\n".to_string(),
449            "A\t1\tt\t1\n".to_string(),
450            "A\t1\tt\t2\n".to_string(),
451            "A\t1\tt\t4\n".to_string(),
452            "B\t1\tt\t1\n".to_string(),
453            "B\t1\tt\t2\n".to_string(),
454        ] {
455            let ran = Trace::parse(&line);
456            assert_eq!(
457                kinds(&changes(&nothing, &ran, None, 9)),
458                [Change::NowRuns { site: 1 }],
459                "{line}"
460            );
461            assert_eq!(
462                kinds(&changes(&ran, &nothing, None, 9)),
463                [Change::NoLongerRuns { site: 1 }],
464                "{line}"
465            );
466        }
467    }
468
469    #[test]
470    fn a_record_without_an_outcome_is_not_a_run() {
471        // A comparison record that saw no relation, as a truncated trace could give.
472        let nothing = Trace::parse("");
473        let empty = Trace::parse(&cmp_line(0));
474        assert!(changes(&nothing, &empty, None, 9).is_empty());
475        assert!(changes(&empty, &nothing, None, 9).is_empty());
476    }
477
478    #[test]
479    fn every_new_relation_and_condition_outcome_is_a_new_outcome() {
480        for (base, extra) in [(1u8, 2u8), (2, 1), (1, 4), (1, 8), (4, 2)] {
481            let found = changes(
482                &Trace::parse(&cmp_line(base)),
483                &Trace::parse(&cmp_line(base | extra)),
484                None,
485                9,
486            );
487            assert_eq!(
488                kinds(&found),
489                [Change::NewOutcome { site: 1 }],
490                "{base} {extra}"
491            );
492        }
493        for (base, extra) in [(1u8, 2u8), (2, 1), (1, 4), (4, 2)] {
494            let found = changes(
495                &Trace::parse(&format!("L\t1\tt\t{base}\n")),
496                &Trace::parse(&format!("L\t1\tt\t{}\n", base | extra)),
497                None,
498                9,
499            );
500            assert_eq!(
501                kinds(&found),
502                [Change::NewOutcome { site: 1 }],
503                "{base} {extra}"
504            );
505        }
506    }
507
508    #[test]
509    fn a_new_result_of_a_called_function() {
510        let (only_true, only_false, both) = (
511            Trace::parse("B\t1\tt\t1\n"),
512            Trace::parse("B\t1\tt\t2\n"),
513            Trace::parse("B\t1\tt\t3\n"),
514        );
515        assert_eq!(
516            kinds(&changes(&only_true, &both, None, 9)),
517            [Change::Returns {
518                site: 1,
519                value: false
520            }]
521        );
522        assert_eq!(
523            kinds(&changes(&only_false, &both, None, 9)),
524            [Change::Returns {
525                site: 1,
526                value: true
527            }]
528        );
529        assert!(changes(&both, &only_true, None, 9).is_empty());
530    }
531}