Skip to main content

targeted_mutation/
trace.rs

1//! Reads the trace written by the injected runtime (`src/runtime/tmt_rt.rs`).
2//!
3//! Lines are tab separated:
4//! - `O <site> <test> <rels> <unvalued> <max_neg|-> <min_pos|-> <unfloat> <f_max_neg|-> <f_min_pos|->`:
5//!   cumulative summary of a comparison
6//! - `R <site> <test> <bits>`: a statement site was executed
7//! - `L <site> <test> <bits>`: observations at `&&` / `||` (cumulative)
8//! - `A <site> <test> <bits>`: observations at an arithmetic operator (cumulative)
9//! - `B <site> <test> <bits>`: values a `-> bool` function returned (cumulative)
10//! - `T <site> <lhs_min> <lhs_max> <rhs_min> <rhs_max>`: integer type bounds of the operands
11//!
12//! A process killed mid-write can leave a truncated last line; malformed lines are skipped
13//! and counted rather than trusted.
14
15use std::collections::{BTreeMap, BTreeSet};
16
17use crate::plan::{ArithObs, LogicObs, Obs, ReturnObs};
18
19/// Test name used when the observing thread is not a libtest test thread.
20pub const UNKNOWN_TEST: &str = "?";
21
22#[derive(Clone, Copy, PartialEq, Eq, Debug)]
23pub struct TypeBounds {
24    pub lhs: (i128, i128),
25    pub rhs: (i128, i128),
26}
27
28#[derive(Default, Debug, PartialEq)]
29pub struct Trace {
30    /// site -> test -> observations
31    pub cmp: BTreeMap<u32, BTreeMap<String, Obs>>,
32    pub logic: BTreeMap<u32, BTreeMap<String, LogicObs>>,
33    pub arith: BTreeMap<u32, BTreeMap<String, ArithObs>>,
34    pub returns: BTreeMap<u32, BTreeMap<String, ReturnObs>>,
35    /// site -> tests that executed the statement
36    pub reach: BTreeMap<u32, BTreeSet<String>>,
37    /// Ranges `a..b` that some test ran with `b` at the largest value of its type.
38    pub ranges_at_top: BTreeSet<u32>,
39    pub bounds: BTreeMap<u32, TypeBounds>,
40    pub malformed_lines: usize,
41}
42
43fn flag(text: &str) -> Option<bool> {
44    match text {
45        "0" => Some(false),
46        "1" => Some(true),
47        _ => None,
48    }
49}
50
51fn optional<T: std::str::FromStr>(text: &str) -> Option<Option<T>> {
52    if text == "-" {
53        Some(None)
54    } else {
55        text.parse().ok().map(Some)
56    }
57}
58
59/// Counts differing records from two streams ordered by the same key.
60fn differing<K: Ord, V: PartialEq>(
61    a: impl Iterator<Item = (K, V)>,
62    b: impl Iterator<Item = (K, V)>,
63) -> usize {
64    let mut a = a.peekable();
65    let mut b = b.peekable();
66    let mut count = 0;
67    while let (Some((left, _)), Some((right, _))) = (a.peek(), b.peek()) {
68        match left.cmp(right) {
69            std::cmp::Ordering::Less => {
70                a.next();
71                count += 1;
72            }
73            std::cmp::Ordering::Greater => {
74                b.next();
75                count += 1;
76            }
77            std::cmp::Ordering::Equal => {
78                let left = a.next().unwrap().1;
79                let right = b.next().unwrap().1;
80                count += usize::from(left != right);
81            }
82        }
83    }
84    count + a.count() + b.count()
85}
86
87fn records<T>(map: &BTreeMap<u32, BTreeMap<String, T>>) -> impl Iterator<Item = ((u32, &str), &T)> {
88    map.iter().flat_map(|(&site, tests)| {
89        tests
90            .iter()
91            .map(move |(test, seen)| ((site, test.as_str()), seen))
92    })
93}
94
95fn reached_records(
96    map: &BTreeMap<u32, BTreeSet<String>>,
97) -> impl Iterator<Item = ((u32, &str), ())> {
98    map.iter()
99        .flat_map(|(&site, tests)| tests.iter().map(move |test| ((site, test.as_str()), ())))
100}
101
102impl Trace {
103    /// How many records (what one test saw at one site) are not the same in two traces
104    /// of the same tests. Tests that always do the same give none.
105    pub fn differences(&self, other: &Trace) -> usize {
106        differing(records(&self.cmp), records(&other.cmp))
107            + differing(records(&self.logic), records(&other.logic))
108            + differing(records(&self.arith), records(&other.arith))
109            + differing(records(&self.returns), records(&other.returns))
110            + differing(reached_records(&self.reach), reached_records(&other.reach))
111    }
112
113    pub fn parse(text: &str) -> Trace {
114        let mut trace = Trace::default();
115        for line in text.lines() {
116            if trace.parse_line(line).is_none() {
117                trace.malformed_lines += 1;
118            }
119        }
120        trace
121    }
122
123    fn parse_line(&mut self, line: &str) -> Option<()> {
124        // The comparison record is the widest. Reject extra fields without allocating.
125        let mut cols = [""; 10];
126        let mut len = 0;
127        for field in line.split('\t') {
128            *cols.get_mut(len)? = field;
129            len += 1;
130        }
131        match cols[..len] {
132            [
133                "O",
134                site,
135                test,
136                rels,
137                unvalued,
138                max_neg,
139                min_pos,
140                unfloat,
141                f_max_neg,
142                f_min_pos,
143            ] => {
144                let rels: u8 = rels.parse().ok().filter(|r| *r < 16)?;
145                let obs = Obs {
146                    lt: rels & 1 != 0,
147                    eq: rels & 2 != 0,
148                    gt: rels & 4 != 0,
149                    un: rels & 8 != 0,
150                    unvalued: flag(unvalued)?,
151                    max_neg: optional::<i128>(max_neg)?.filter(|d| *d < 0),
152                    min_pos: optional::<i128>(min_pos)?.filter(|d| *d > 0),
153                    unfloat: flag(unfloat)?,
154                    f_max_neg: optional::<f64>(f_max_neg)?.filter(|d| d.is_finite() && *d < 0.0),
155                    f_min_pos: optional::<f64>(f_min_pos)?.filter(|d| d.is_finite() && *d > 0.0),
156                };
157                let site = site.parse().ok()?;
158                (!test.is_empty()).then_some(())?;
159                self.cmp
160                    .entry(site)
161                    .or_default()
162                    .entry(test.to_string())
163                    .or_default()
164                    .merge(&obs);
165            }
166            [kind @ ("R" | "L" | "A" | "B"), site, test, bits] => {
167                let site: u32 = site.parse().ok()?;
168                let limit = match kind {
169                    "B" => 4,
170                    "A" => 32,
171                    "L" => 16,
172                    _ => 8,
173                };
174                let bits: u8 = bits.parse().ok().filter(|b| (1..limit).contains(b))?;
175                (!test.is_empty()).then_some(())?;
176                let test = test.to_string();
177                match kind {
178                    "R" => {
179                        if bits & 2 != 0 {
180                            self.ranges_at_top.insert(site);
181                        }
182                        self.reach.entry(site).or_default().insert(test);
183                    }
184                    "B" => self
185                        .returns
186                        .entry(site)
187                        .or_default()
188                        .entry(test)
189                        .or_default()
190                        .merge(&ReturnObs::from_bits(bits)),
191                    "L" => self
192                        .logic
193                        .entry(site)
194                        .or_default()
195                        .entry(test)
196                        .or_default()
197                        .merge(&LogicObs::from_bits(bits)),
198                    _ => self
199                        .arith
200                        .entry(site)
201                        .or_default()
202                        .entry(test)
203                        .or_default()
204                        .merge(&ArithObs::from_bits(bits)),
205                }
206            }
207            ["T", site, lhs_min, lhs_max, rhs_min, rhs_max] => {
208                let bounds = TypeBounds {
209                    lhs: (lhs_min.parse().ok()?, lhs_max.parse().ok()?),
210                    rhs: (rhs_min.parse().ok()?, rhs_max.parse().ok()?),
211                };
212                self.bounds.insert(site.parse().ok()?, bounds);
213            }
214            _ => return None,
215        }
216        Some(())
217    }
218
219    /// Everything any test observed at a comparison site.
220    pub fn merged(&self, site: u32) -> Obs {
221        let mut all = Obs::default();
222        for obs in self
223            .cmp
224            .get(&site)
225            .into_iter()
226            .flat_map(|tests| tests.values())
227        {
228            all.merge(obs);
229        }
230        all
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237    use crate::plan::{CmpOp, Mutation, Rel, eval_mutated_d};
238    use crate::tmt_rt;
239
240    #[test]
241    fn parses_and_merges_lines() {
242        let trace = Trace::parse(
243            "O\t3\ttests::a\t1\t0\t-4\t-\t1\t-\t-\n\
244             O\t3\ttests::a\t5\t0\t-1\t2\t1\t-\t-\n\
245             O\t3\ttests::b\t2\t0\t-\t-\t1\t-\t-\n\
246             R\t9\ttests::a\t1\n\
247             R\t9\t?\t1\n\
248             T\t3\t0\t255\t0\t255\n",
249        );
250        assert_eq!(trace.malformed_lines, 0);
251        let a = trace.cmp[&3]["tests::a"];
252        assert_eq!(
253            (a.lt, a.eq, a.gt, a.max_neg, a.min_pos),
254            (true, false, true, Some(-1), Some(2))
255        );
256        assert!(trace.merged(3).eq);
257        assert_eq!(
258            trace.reach[&9].iter().collect::<Vec<_>>(),
259            ["?", "tests::a"]
260        );
261        assert_eq!(
262            trace.bounds[&3],
263            TypeBounds {
264                lhs: (0, 255),
265                rhs: (0, 255)
266            }
267        );
268        assert_eq!(trace.merged(42), Obs::default());
269    }
270
271    #[test]
272    fn skips_truncated_and_malformed_lines() {
273        let trace = Trace::parse(
274            "O\t3\ttests::a\t1\t0\t-4\nX\t1\nO\tx\tt\t1\t0\t-\t-\t1\t-\t-\nO\t1\tt\t99\t0\t-\t-\t1\t-\t-\nR\t1\t\t1\nR\t2\tok\t1\n",
275        );
276        assert_eq!(trace.malformed_lines, 5);
277        assert!(trace.cmp.is_empty());
278        assert_eq!(trace.reach.len(), 1);
279    }
280
281    #[test]
282    fn trace_records_need_the_exact_number_of_fields_with_any_line_ending() {
283        for record in [
284            "O\t3\ttests::a\t5\t0\t-1\t2\t1\t-\t-",
285            "R\t3\ttests::a\t1",
286            "L\t3\ttests::a\t1",
287            "A\t3\ttests::a\t1",
288            "B\t3\ttests::a\t1",
289            "T\t3\t0\t255\t0\t255",
290        ] {
291            let (short, _) = record.rsplit_once('\t').unwrap();
292            let long = format!("{record}\t");
293            for ending in ["\n", "\r\n", ""] {
294                let parsed = Trace::parse(&format!("{record}{ending}"));
295                assert_eq!(parsed.malformed_lines, 0, "{record:?} {ending:?}");
296                assert_ne!(parsed, Trace::default());
297                for malformed in [short, long.as_str()] {
298                    assert_eq!(
299                        Trace::parse(&format!("{malformed}{ending}")),
300                        Trace {
301                            malformed_lines: 1,
302                            ..Trace::default()
303                        },
304                        "{malformed:?} {ending:?}"
305                    );
306                }
307            }
308        }
309
310        let parsed = Trace::parse(&format!(
311            "R\t3\ttests::a\t1{}\nR\t4\ttests::b\t1\n",
312            "\t".repeat(32)
313        ));
314        assert_eq!(parsed.malformed_lines, 1);
315        assert!(!parsed.reach.contains_key(&3));
316        assert!(parsed.reach[&4].contains("tests::b"));
317    }
318
319    #[test]
320    fn relation_bits_and_field_validation() {
321        for (rels, expected) in [(1, "lt"), (2, "eq"), (4, "gt"), (8, "un")] {
322            let trace = Trace::parse(&format!("O\t1\tt\t{rels}\t1\t-\t-\t1\t-\t-\n"));
323            let o = trace.cmp[&1]["t"];
324            let set: Vec<&str> = [(o.lt, "lt"), (o.eq, "eq"), (o.gt, "gt"), (o.un, "un")]
325                .into_iter()
326                .filter_map(|(on, name)| on.then_some(name))
327                .collect();
328            assert_eq!(set, [expected]);
329            assert!(o.unvalued);
330        }
331        // 15 is every relation, 16 is not a relation mask.
332        assert_eq!(
333            Trace::parse("O\t1\tt\t15\t0\t-\t-\t1\t-\t-\n").malformed_lines,
334            0
335        );
336        assert_eq!(
337            Trace::parse("O\t1\tt\t16\t0\t-\t-\t1\t-\t-\n").malformed_lines,
338            1
339        );
340        // A comparison line needs a test name too.
341        let nameless = Trace::parse("O\t1\t\t1\t0\t-\t-\t1\t-\t-\n");
342        assert_eq!((nameless.malformed_lines, nameless.cmp.len()), (1, 0));
343        // The nearest-below value is negative and the nearest-above positive, or they are dropped.
344        let signs = Trace::parse("O\t1\tt\t5\t0\t0\t0\t1\t-\t-\nO\t2\tt\t5\t0\t3\t-3\t1\t-\t-\n");
345        for site in [1, 2] {
346            let o = signs.cmp[&site]["t"];
347            assert_eq!((o.max_neg, o.min_pos), (None, None));
348        }
349    }
350
351    fn rt_op(op: CmpOp) -> u8 {
352        op.code()
353    }
354
355    fn rt_mutant(m: Mutation) -> tmt_rt::Mutant {
356        let spec = format!("7:{}", m.encode());
357        let (site, parsed) =
358            tmt_rt::parse_mutant(&spec).unwrap_or_else(|| panic!("runtime rejects {spec}"));
359        assert_eq!(site, 7);
360        parsed
361    }
362
363    /// The injected runtime is a separate source file; it must agree with the planner on
364    /// what every mutation does and on how observations are summarised.
365    #[test]
366    fn runtime_agrees_with_the_planner() {
367        for op in CmpOp::ALL {
368            let mut ms = vec![
369                Mutation::Const(true),
370                Mutation::Const(false),
371                Mutation::Negate,
372            ];
373            ms.extend(CmpOp::ALL.into_iter().map(Mutation::Op));
374            if op.is_ordering() {
375                ms.extend((-4..=4).filter(|s| *s != 0).map(Mutation::Shift));
376            }
377            for m in ms {
378                for d in -6..=6i128 {
379                    let rel = if d < 0 {
380                        1
381                    } else if d == 0 {
382                        2
383                    } else {
384                        4
385                    };
386                    assert_eq!(
387                        tmt_rt::apply(
388                            rt_op(op),
389                            rt_mutant(m),
390                            op.eval_d(d),
391                            rel,
392                            tmt_rt::Diff::Int(d)
393                        ),
394                        eval_mutated_d(op, m, d),
395                        "{op:?} {m:?} d={d}"
396                    );
397                }
398            }
399            // Unordered operands (NaN): only `!=` is true.
400            assert_eq!(
401                tmt_rt::apply(
402                    rt_op(op),
403                    tmt_rt::Mutant::Op(rt_op(op)),
404                    false,
405                    8,
406                    tmt_rt::Diff::None
407                ),
408                op.eval_rel(Rel::Unordered)
409            );
410            // A shift needs values of its own kind; without them the original result stands.
411            for orig in [true, false] {
412                assert_eq!(
413                    tmt_rt::apply(
414                        rt_op(op),
415                        tmt_rt::Mutant::Shift(1),
416                        orig,
417                        2,
418                        tmt_rt::Diff::None
419                    ),
420                    orig
421                );
422                assert_eq!(
423                    tmt_rt::apply(
424                        rt_op(op),
425                        tmt_rt::Mutant::ShiftF(1.0),
426                        orig,
427                        2,
428                        tmt_rt::Diff::Int(0)
429                    ),
430                    orig
431                );
432                assert_eq!(
433                    tmt_rt::apply(
434                        rt_op(op),
435                        tmt_rt::Mutant::Delete,
436                        orig,
437                        2,
438                        tmt_rt::Diff::Int(0)
439                    ),
440                    orig
441                );
442            }
443        }
444        assert_eq!(
445            tmt_rt::parse_mutant("12:del"),
446            Some((12, tmt_rt::Mutant::Delete))
447        );
448        for (m, expected) in [
449            (Mutation::LogicSwap, tmt_rt::Mutant::LogicSwap),
450            (Mutation::LogicDropRhs, tmt_rt::Mutant::LogicDropRhs),
451            (Mutation::LogicDropLhs, tmt_rt::Mutant::LogicDropLhs),
452            (Mutation::ArithSwap, tmt_rt::Mutant::ArithSwap),
453            (Mutation::ArithSwap2, tmt_rt::Mutant::ArithSwap2),
454            (Mutation::ShiftF(-10.25), tmt_rt::Mutant::ShiftF(-10.25)),
455            (Mutation::ShiftF(1e-7), tmt_rt::Mutant::ShiftF(1e-7)),
456        ] {
457            assert_eq!(rt_mutant(m), expected);
458        }
459        for bad in [
460            "", "x:neg", "1:", "1:op9", "1:shx", "1:zzz", "neg", "1:shfnan", "1:shfinf", "1:shf",
461        ] {
462            assert_eq!(tmt_rt::parse_mutant(bad), None, "{bad:?}");
463        }
464    }
465
466    /// Float shifts: the runtime's result on the observed differences never changes for a
467    /// shift the planner calls safe.
468    #[test]
469    fn runtime_float_shifts_agree_with_the_planner() {
470        let observed = [-20.5f64, -3.0, 9.5, 12.0];
471        let mut obs = Obs::default();
472        for d in observed {
473            obs.merge(&Obs::of_f(d));
474        }
475        for op in [CmpOp::Lt, CmpOp::Le, CmpOp::Gt, CmpOp::Ge] {
476            for shift in [-20.5, -10.0, -3.0, -1.5, 4.75, 9.5, 11.0] {
477                let changes_something = observed.iter().any(|d| {
478                    let rel = if *d < 0.0 { 1 } else { 4 };
479                    let orig = op.eval_d(if *d < 0.0 { -1 } else { 1 });
480                    tmt_rt::apply(
481                        rt_op(op),
482                        tmt_rt::Mutant::ShiftF(shift),
483                        orig,
484                        rel,
485                        tmt_rt::Diff::Float(*d),
486                    ) != orig
487                });
488                let predicted = crate::plan::infects(op, Mutation::ShiftF(shift), &obs);
489                // Safe by the planner implies unchanged at run time (the converse need not hold
490                // exactly at the edges of the gap).
491                assert!(predicted || !changes_something, "{op:?} shift={shift}");
492            }
493        }
494        // Equal floats are reported as a zero difference even where subtraction is not finite.
495        use tmt_rt::{Diff, Val};
496        assert_eq!(
497            tmt_rt::diff(Val::Float(f64::INFINITY), Val::Float(f64::INFINITY), true),
498            Diff::Float(0.0)
499        );
500        assert_eq!(
501            tmt_rt::diff(Val::Float(f64::INFINITY), Val::Float(1.0), false),
502            Diff::None
503        );
504        assert_eq!(
505            tmt_rt::diff(Val::Float(f64::NAN), Val::Float(1.0), false),
506            Diff::None
507        );
508        assert_eq!(
509            tmt_rt::diff(Val::Float(1.5), Val::Float(1.0), false),
510            Diff::Float(0.5)
511        );
512        assert_eq!(
513            tmt_rt::diff(Val::Int(3, 0, 9), Val::Int(5, 0, 9), false),
514            Diff::Int(-2)
515        );
516        assert_eq!(
517            tmt_rt::diff(Val::Int(3, 0, 9), Val::Float(5.0), false),
518            Diff::None
519        );
520        assert_eq!(tmt_rt::diff(Val::None, Val::None, true), Diff::None);
521    }
522
523    /// `&&` / `||` in the runtime against the plain operators and the planner's bits.
524    #[test]
525    fn runtime_logic_matches_the_operators() {
526        let run = |and: bool, m: Option<tmt_rt::Mutant>, a: bool, b: bool| -> (bool, bool) {
527            match tmt_rt::lhs_code(and, a, m) {
528                2 => (tmt_rt::rhs_value(and, b, m), true),
529                code => (code == 1, false),
530            }
531        };
532        for and in [true, false] {
533            for a in [true, false] {
534                for b in [true, false] {
535                    let real = if and { a && b } else { a || b };
536                    let swapped = if and { a || b } else { a && b };
537                    assert_eq!(run(and, None, a, b).0, real);
538                    assert_eq!(run(and, Some(tmt_rt::Mutant::LogicSwap), a, b).0, swapped);
539                    assert_eq!(
540                        run(and, Some(tmt_rt::Mutant::LogicDropLhs), a, b),
541                        (b, true)
542                    );
543                    // The right operand is evaluated exactly when the original evaluates it.
544                    assert_eq!(
545                        run(and, Some(tmt_rt::Mutant::LogicDropRhs), a, b),
546                        (a, run(and, None, a, b).1)
547                    );
548                    // Short-circuiting: the right operand is skipped exactly as in Rust.
549                    assert_eq!(run(and, None, a, b).1, if and { a } else { !a });
550
551                    // What the planner predicts from the observation bits is what changes.
552                    let (_, evaluated) = run(and, None, a, b);
553                    let bits = if !evaluated {
554                        tmt_rt::LOGIC_SHORT
555                    } else if b {
556                        tmt_rt::LOGIC_RHS_TRUE
557                    } else {
558                        tmt_rt::LOGIC_RHS_FALSE
559                    };
560                    let obs = crate::plan::LogicObs::from_bits(bits);
561                    for (m, rt) in [
562                        (Mutation::LogicDropRhs, tmt_rt::Mutant::LogicDropRhs),
563                        (Mutation::LogicDropLhs, tmt_rt::Mutant::LogicDropLhs),
564                    ] {
565                        let changed = run(and, Some(rt), a, b) != run(and, None, a, b);
566                        assert_eq!(
567                            crate::plan::logic_infects(and, m, &obs),
568                            changed,
569                            "and={and} a={a} b={b} {m:?}"
570                        );
571                    }
572                }
573            }
574        }
575        // Without a mutant or a trace the probes are the plain operators.
576        assert_eq!(tmt_rt::lhs(0, true, false), 0);
577        assert_eq!(tmt_rt::lhs(0, false, true), 1);
578        assert_eq!(tmt_rt::lhs(0, true, true), 2);
579        assert!(tmt_rt::rhs(0, true, true));
580        assert!(!tmt_rt::rhs(0, false, false));
581    }
582
583    #[test]
584    #[allow(clippy::needless_borrow)] // the explicit `&` is the call form the probes use
585    fn runtime_arithmetic_probes() {
586        use tmt_rt::{AnyAdd as _, AnyMul as _, AnySub as _, ArithNum, ArithPrim as _};
587        // Primitive numbers: the real operator.
588        assert_eq!((&tmt_rt::Ar::new(7u32, 2u32)).tmt_add(0), 9);
589        assert_eq!((&tmt_rt::Ar::new(7i64, 2)).tmt_sub(0), 5);
590        assert_eq!((&tmt_rt::Ar::new(7usize, 2)).tmt_mul(0), 14);
591        assert_eq!((&tmt_rt::Ar::new(7u8, 2)).tmt_div(0), 3);
592        assert_eq!((&tmt_rt::Ar::new(7i16, 2)).tmt_rem(0), 1);
593        assert_eq!((&tmt_rt::Ar::new(1.5f64, 2.0)).tmt_mul(0), 3.0);
594        // Everything else falls back to the operator's own implementation.
595        assert_eq!((&tmt_rt::Ar::new(String::from("a"), "b")).tmt_add(0), "ab");
596        let second = std::time::Duration::from_secs(1);
597        assert_eq!((&tmt_rt::Ar::new(second, second)).tmt_add(0), second * 2);
598        assert_eq!((&tmt_rt::Ar::new(second, 3u32)).tmt_mul(0), second * 3);
599        assert_eq!((&tmt_rt::Ar::new(&5i32, &3i32)).tmt_sub(0), 2);
600
601        // The swapped operator of each operator, and when it agrees.
602        for (op, swapped) in [
603            (tmt_rt::ADD, tmt_rt::SUB),
604            (tmt_rt::SUB, tmt_rt::ADD),
605            (tmt_rt::MUL, tmt_rt::DIV),
606            (tmt_rt::DIV, tmt_rt::MUL),
607            (tmt_rt::REM, tmt_rt::DIV),
608        ] {
609            assert_eq!(tmt_rt::arith_swapped(op), swapped);
610            for a in -6..=6i32 {
611                for b in -6..=6i32 {
612                    let real = |op: u8| match op {
613                        tmt_rt::ADD => a.checked_add(b),
614                        tmt_rt::SUB => a.checked_sub(b),
615                        tmt_rt::MUL => a.checked_mul(b),
616                        tmt_rt::DIV => a.checked_div(b),
617                        _ => a.checked_rem(b),
618                    };
619                    // Equal only when both are defined: a fault on either side has to be run.
620                    let same = matches!((real(op), real(swapped)), (Some(x), Some(y)) if x == y);
621                    assert_eq!(
622                        i32::tmt_same(op, tmt_rt::arith_swapped(op), a, b),
623                        same,
624                        "op={op} {a} {b}"
625                    );
626                    if let Some(value) = real(op) {
627                        assert_eq!(i32::tmt_real(op, a, b), value);
628                    }
629                }
630            }
631        }
632        assert!(u8::tmt_same(
633            tmt_rt::ADD,
634            tmt_rt::arith_swapped(tmt_rt::ADD),
635            9,
636            0
637        ));
638        // Both shifts overflow: not "the same", the tests decide.
639        assert!(!u8::tmt_same(
640            tmt_rt::SHL,
641            tmt_rt::arith_swapped(tmt_rt::SHL),
642            2,
643            9
644        ));
645        assert!(u8::tmt_same(
646            tmt_rt::SHL,
647            tmt_rt::arith_swapped(tmt_rt::SHL),
648            2,
649            0
650        ));
651        assert!(!u8::tmt_same(
652            tmt_rt::DIV,
653            tmt_rt::arith_swapped(tmt_rt::DIV),
654            4,
655            0
656        ));
657        assert!(
658            !u8::tmt_same(tmt_rt::ADD, tmt_rt::arith_swapped(tmt_rt::ADD), 250, 9),
659            "overflow in one of the two counts as different"
660        );
661        assert!(
662            !u8::tmt_same(tmt_rt::MUL, tmt_rt::arith_swapped(tmt_rt::MUL), 4, 0),
663            "division by zero counts as different"
664        );
665        assert!(f64::tmt_same(
666            tmt_rt::MUL,
667            tmt_rt::arith_swapped(tmt_rt::MUL),
668            4.0,
669            1.0
670        ));
671        assert!(!f64::tmt_same(
672            tmt_rt::ADD,
673            tmt_rt::arith_swapped(tmt_rt::ADD),
674            4.0,
675            0.5
676        ));
677        assert!(
678            !f32::tmt_same(tmt_rt::MUL, tmt_rt::arith_swapped(tmt_rt::MUL), 4.0, 0.0),
679            "4*0 is 0, 4/0 is infinite"
680        );
681    }
682
683    #[test]
684    fn runtime_summary_lines_round_trip() {
685        use tmt_rt::Diff;
686        let observations = [
687            (1, Diff::Int(-5)),
688            (1, Diff::Int(-2)),
689            (4, Diff::Int(9)),
690            (2, Diff::Int(0)),
691            (4, Diff::Int(3)),
692            (1, Diff::Float(-2.5)),
693            (1, Diff::Float(-0.125)),
694            (4, Diff::Float(1e-7)),
695            (8, Diff::None),
696        ];
697        let mut summary = tmt_rt::Summary::default();
698        let mut expected = Obs::default();
699        let mut text = String::new();
700        for (rel, d) in observations {
701            let changed = summary.observe(rel, d);
702            assert!(
703                changed,
704                "each of these observations adds information: {d:?}"
705            );
706            assert!(
707                !summary.observe(rel, d),
708                "repeating an observation changes nothing"
709            );
710            text.push_str(&summary.line(4, "tests::t"));
711            expected.merge(&match d {
712                Diff::Int(d) => Obs::of_d(d),
713                Diff::Float(d) => Obs::of_f(d),
714                Diff::None => Obs::of_rel(Rel::Unordered),
715            });
716        }
717        let trace = Trace::parse(&text);
718        assert_eq!(trace.malformed_lines, 0);
719        assert_eq!(trace.cmp[&4]["tests::t"], expected);
720        assert_eq!(expected.f_min_pos, Some(1e-7));
721
722        // Floats only: the summary keeps the float gap.
723        let mut floats = tmt_rt::Summary::default();
724        floats.observe(1, Diff::Float(-20.5));
725        floats.observe(4, Diff::Float(9.5));
726        let trace = Trace::parse(&floats.line(1, "t"));
727        assert_eq!(trace.cmp[&1]["t"].float_gap(), Some((-20.5, 9.5)));
728    }
729
730    #[test]
731    fn float_columns_are_validated() {
732        let gap = |line: &str| {
733            let trace = Trace::parse(line);
734            assert_eq!(trace.malformed_lines, 0, "{line:?}");
735            let o = trace.cmp[&1]["t"];
736            (o.f_max_neg, o.f_min_pos)
737        };
738        assert_eq!(
739            gap("O\t1\tt\t5\t1\t-\t-\t0\t-2.5\t0.5\n"),
740            (Some(-2.5), Some(0.5))
741        );
742        // Wrong sign, zero, or not finite: dropped.
743        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t2.5\t-0.5\n"), (None, None));
744        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t0.0\t0.0\n"), (None, None));
745        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\t-inf\tinf\n"), (None, None));
746        assert_eq!(gap("O\t1\tt\t5\t1\t-\t-\t0\tNaN\tNaN\n"), (None, None));
747        assert_eq!(
748            Trace::parse("O\t1\tt\t5\t1\t-\t-\t2\t-\t-\n").malformed_lines,
749            1,
750            "bad flag"
751        );
752        assert_eq!(
753            Trace::parse("O\t1\tt\t5\t1\t-\t-\t0\tx\t-\n").malformed_lines,
754            1
755        );
756    }
757
758    #[test]
759    fn return_lines() {
760        let returns = Trace::parse("B\t4\tt\t1\nB\t4\tt\t2\nB\t4\tu\t2\n");
761        assert_eq!(returns.malformed_lines, 0);
762        assert_eq!(
763            returns.returns[&4]["t"],
764            ReturnObs {
765                saw_true: true,
766                saw_false: true
767            }
768        );
769        assert_eq!(
770            returns.returns[&4]["u"],
771            ReturnObs {
772                saw_true: false,
773                saw_false: true
774            }
775        );
776        assert_eq!(
777            Trace::parse("B\t4\tt\t4\n").malformed_lines,
778            1,
779            "only two return bits exist"
780        );
781        assert_eq!(Trace::parse("B\t4\tt\t3\n").malformed_lines, 0);
782        assert_eq!(Trace::parse("A\t4\tt\t7\n").malformed_lines, 0);
783    }
784
785    #[test]
786    fn logic_arithmetic_and_reach_lines() {
787        let trace = Trace::parse(
788            "L\t1\tt\t1\nL\t1\tt\t5\nL\t1\tu\t2\nA\t2\tt\t1\nA\t2\tu\t6\nR\t3\tt\t1\n",
789        );
790        assert_eq!(trace.malformed_lines, 0);
791        assert_eq!(
792            trace.logic[&1]["t"],
793            crate::plan::LogicObs {
794                short: true,
795                rhs_true: false,
796                rhs_false: true,
797                rhs_started: false,
798            }
799        );
800        assert_eq!(
801            trace.logic[&1]["u"],
802            crate::plan::LogicObs {
803                short: false,
804                rhs_true: true,
805                rhs_false: false,
806                rhs_started: false,
807            }
808        );
809        assert_eq!(
810            trace.arith[&2]["t"],
811            crate::plan::ArithObs {
812                same: true,
813                differs: false,
814                opaque: false,
815                ..Default::default()
816            }
817        );
818        assert_eq!(
819            trace.arith[&2]["u"],
820            crate::plan::ArithObs {
821                same: false,
822                differs: true,
823                opaque: true,
824                ..Default::default()
825            }
826        );
827        assert!(trace.reach[&3].contains("t"));
828        // A range that ended at the largest value of its type is remembered as one.
829        let ranges = Trace::parse("R\t7\tt\t3\nR\t8\tt\t1\n");
830        assert_eq!(ranges.malformed_lines, 0);
831        assert!(ranges.reach[&7].contains("t") && ranges.reach[&8].contains("t"));
832        assert_eq!(ranges.ranges_at_top.iter().collect::<Vec<_>>(), [&7]);
833        // A right operand that was started, with and without a value.
834        let started = Trace::parse("L\t1\tt\t8\nL\t1\tu\t10\n");
835        assert_eq!(started.malformed_lines, 0);
836        assert!(started.logic[&1]["t"].rhs_started && !started.logic[&1]["t"].rhs_true);
837        assert!(started.logic[&1]["u"].rhs_started && started.logic[&1]["u"].rhs_true);
838        for bad in [
839            "L\t1\tt\t0\n",
840            "L\t1\tt\t16\n",
841            "A\t1\t\t1\n",
842            "R\t1\tt\n",
843            "L\tx\tt\t1\n",
844            "Z\t1\tt\t1\n",
845        ] {
846            assert_eq!(Trace::parse(bad).malformed_lines, 1, "{bad:?}");
847        }
848    }
849
850    #[test]
851    #[allow(clippy::needless_borrow)] // the explicit `&` is the call form the probes use
852    fn runtime_probes_are_transparent_without_env() {
853        use tmt_rt::{Val, ValAny as _, ValNum as _};
854        // Autoref specialisation: numbers carry values, everything else does not.
855        assert_eq!((&tmt_rt::W(&7u8)).tmt_val(), Val::Int(7, 0, 255));
856        assert_eq!(
857            (&tmt_rt::W(&&-3i64)).tmt_val(),
858            Val::Int(-3, i64::MIN as i128, i64::MAX as i128)
859        );
860        assert_eq!((&tmt_rt::W(&1.5f64)).tmt_val(), Val::Float(1.5));
861        assert_eq!((&tmt_rt::W(&&2.5f32)).tmt_val(), Val::Float(2.5));
862        assert_eq!((&tmt_rt::W("text")).tmt_val(), Val::None);
863        assert_eq!((&tmt_rt::W(&'c')).tmt_val(), Val::None);
864
865        for (a, b) in [(1, 2), (2, 2), (3, 2)] {
866            assert_eq!(
867                tmt_rt::ord(0, tmt_rt::LT, &a, &b, Val::None, Val::None),
868                a < b
869            );
870            assert_eq!(
871                tmt_rt::ord(0, tmt_rt::LE, &a, &b, Val::None, Val::None),
872                a <= b
873            );
874            assert_eq!(
875                tmt_rt::ord(0, tmt_rt::GT, &a, &b, Val::None, Val::None),
876                a > b
877            );
878            assert_eq!(
879                tmt_rt::ord(0, tmt_rt::GE, &a, &b, Val::None, Val::None),
880                a >= b
881            );
882            assert_eq!(
883                tmt_rt::eq(0, tmt_rt::EQ, &a, &b, Val::None, Val::None),
884                a == b
885            );
886            assert_eq!(
887                tmt_rt::eq(0, tmt_rt::NE, &a, &b, Val::None, Val::None),
888                a != b
889            );
890        }
891        assert!(!tmt_rt::ord(
892            0,
893            tmt_rt::GE,
894            &f64::NAN,
895            &1.0,
896            Val::None,
897            Val::None
898        ));
899        assert!(tmt_rt::eq(0, tmt_rt::NE, "a", "b", Val::None, Val::None));
900        assert!(tmt_rt::live(0));
901    }
902    /// The two replacements of each operator are those of cargo-mutants, and the runtime
903    /// and the report name the same ones.
904    #[test]
905    fn both_replacements_of_every_operator() {
906        use crate::instrument::ArithOp;
907        let code = |op: ArithOp| match op {
908            ArithOp::Add => tmt_rt::ADD,
909            ArithOp::Sub => tmt_rt::SUB,
910            ArithOp::Mul => tmt_rt::MUL,
911            ArithOp::Div => tmt_rt::DIV,
912            ArithOp::Rem => tmt_rt::REM,
913            ArithOp::BitAnd => tmt_rt::BITAND,
914            ArithOp::BitOr => tmt_rt::BITOR,
915            ArithOp::BitXor => tmt_rt::BITXOR,
916            ArithOp::Shl => tmt_rt::SHL,
917            ArithOp::Shr => tmt_rt::SHR,
918        };
919        let table = [
920            (ArithOp::Add, "-", Some("*")),
921            (ArithOp::Sub, "+", Some("/")),
922            (ArithOp::Mul, "/", Some("+")),
923            (ArithOp::Div, "*", Some("%")),
924            (ArithOp::Rem, "/", Some("+")),
925            (ArithOp::BitAnd, "|", Some("^")),
926            (ArithOp::BitOr, "&", Some("^")),
927            (ArithOp::BitXor, "&", Some("|")),
928            (ArithOp::Shl, ">>", None),
929            (ArithOp::Shr, "<<", None),
930        ];
931        assert_eq!(table.map(|row| row.0), ArithOp::ALL);
932        for (op, first, second) in table {
933            assert_eq!(op.swapped().symbol(), first, "{op:?}");
934            assert_eq!(op.swapped2().map(ArithOp::symbol), second, "{op:?}");
935            assert_eq!(
936                tmt_rt::arith_swapped(code(op)),
937                code(op.swapped()),
938                "{op:?}"
939            );
940            assert_eq!(
941                tmt_rt::arith_swapped2(code(op)),
942                op.swapped2().map(code),
943                "{op:?}"
944            );
945        }
946        assert_eq!(
947            tmt_rt::parse_mutant("3:as2"),
948            Some((3, tmt_rt::Mutant::ArithSwap2))
949        );
950
951        // What is recorded for a pair of operands: whether each replacement agrees.
952        use tmt_rt::ArithNum;
953        // 2 + 2 = 2 * 2, but not 2 - 2.
954        assert!(!i32::tmt_same(tmt_rt::ADD, tmt_rt::SUB, 2, 2));
955        assert!(i32::tmt_same(tmt_rt::ADD, tmt_rt::MUL, 2, 2));
956        // 6 / 1 = 6 * 1, but not 6 % 1.
957        assert!(i32::tmt_same(tmt_rt::DIV, tmt_rt::MUL, 6, 1));
958        assert!(!i32::tmt_same(tmt_rt::DIV, tmt_rt::REM, 6, 1));
959        // 4 | 1 = 4 ^ 1, but not 4 & 1.
960        assert!(i32::tmt_same(tmt_rt::BITOR, tmt_rt::BITXOR, 4, 1));
961        assert!(!i32::tmt_same(tmt_rt::BITOR, tmt_rt::BITAND, 4, 1));
962        assert!(f64::tmt_same(tmt_rt::MUL, tmt_rt::ADD, 2.0, 2.0));
963
964        // And as the planner reads it.
965        let seen = |bits: u8| crate::plan::ArithObs::from_bits(bits);
966        let both = seen(tmt_rt::ARITH_DIFFERS | tmt_rt::ARITH_SAME2);
967        assert!(both.differs && both.same2 && !both.same && !both.differs2 && !both.opaque);
968        assert!(both.infected_by(Mutation::ArithSwap));
969        assert!(!both.infected_by(Mutation::ArithSwap2));
970        let other = seen(tmt_rt::ARITH_SAME | tmt_rt::ARITH_DIFFERS2);
971        assert!(!other.infected_by(Mutation::ArithSwap));
972        assert!(other.infected_by(Mutation::ArithSwap2));
973        assert_eq!(crate::plan::plan_arith(&both), crate::plan::ArithPlan::Run);
974        assert_eq!(
975            crate::plan::plan_arith(&both.second()),
976            crate::plan::ArithPlan::NeverDiffers
977        );
978        assert_eq!(
979            crate::plan::plan_arith(&other.second()),
980            crate::plan::ArithPlan::Run
981        );
982        let mut merged = both;
983        merged.merge(&other);
984        assert!(merged.same && merged.differs && merged.same2 && merged.differs2);
985        let mut merged = other;
986        merged.merge(&both);
987        assert!(merged.same && merged.differs && merged.same2 && merged.differs2);
988        // An assignment that collects bits has one replacement, as in cargo-mutants.
989        assert_eq!(ArithOp::BitOr.second(true), None);
990        assert_eq!(ArithOp::BitAnd.second(true), None);
991        assert_eq!(ArithOp::BitXor.second(true), Some(ArithOp::BitOr));
992        assert_eq!(ArithOp::BitOr.second(false), Some(ArithOp::BitXor));
993        assert_eq!(ArithOp::Add.second(true), Some(ArithOp::Mul));
994        // Operands that are not numbers stay that for both.
995        assert_eq!(
996            crate::plan::plan_arith(&seen(tmt_rt::ARITH_OPAQUE).second()),
997            crate::plan::ArithPlan::Opaque
998        );
999        assert_eq!(Mutation::ArithSwap2.encode(), "as2");
1000
1001        // A trace line with the wider bits is read; one beyond them is not.
1002        let trace = Trace::parse("A\t1\tt\t18\nA\t2\tt\t31\nA\t3\tt\t32\n");
1003        assert_eq!(trace.arith[&1]["t"], seen(18));
1004        assert!(trace.arith.contains_key(&2) && !trace.arith.contains_key(&3));
1005        assert_eq!(trace.malformed_lines, 1);
1006    }
1007
1008    /// A probe in a loop asks the tracer only when it has something new to say.
1009    #[test]
1010    fn two_traces_differ_by_the_records_that_are_not_the_same() {
1011        let text =
1012            "O\t1\ta\t3\t0\t-2\t-\t1\t-\t-\nL\t2\ta\t1\nA\t3\ta\t1\nB\t4\ta\t1\nR\t5\ta\t1\n";
1013        let base = Trace::parse(text);
1014        assert_eq!(base.malformed_lines, 0);
1015        assert_eq!(base.differences(&Trace::parse(text)), 0);
1016        // Each kind of record counts, in whichever of the two it is missing or other.
1017        for (other, differing) in [
1018            ("O\t1\ta\t3\t0\t-1\t-\t1\t-\t-\n", 1), // a nearer value
1019            ("O\t1\tb\t3\t0\t-2\t-\t1\t-\t-\n", 1), // seen by another test too
1020            ("O\t9\ta\t3\t0\t-2\t-\t1\t-\t-\n", 1), // at another site too
1021            ("L\t2\ta\t2\n", 1),
1022            ("A\t3\ta\t2\n", 1),
1023            ("B\t4\ta\t2\n", 1),
1024            ("R\t5\tb\t1\n", 1),
1025            ("R\t6\ta\t1\nL\t2\tb\t1\n", 2),
1026        ] {
1027            let more = Trace::parse(&format!("{text}{other}"));
1028            assert_eq!(base.differences(&more), differing, "{other:?}");
1029            assert_eq!(more.differences(&base), differing, "{other:?}");
1030        }
1031        assert_eq!(base.differences(&Trace::default()), 5);
1032        assert_eq!(Trace::default().differences(&base), 5);
1033    }
1034
1035    #[test]
1036    fn sorted_audit_counts_changes_once_across_interleaved_keys() {
1037        let before = [((0, "a"), 1), ((1, "a"), 2), ((1, "ba"), 3), ((7, "u"), 4)];
1038        let after = [((1, "a"), 2), ((1, "b"), 3), ((1, "ba"), 7), ((8, "u"), 4)];
1039        assert_eq!(differing(before.into_iter(), after.into_iter()), 5);
1040        assert_eq!(differing(after.into_iter(), before.into_iter()), 5);
1041        assert_eq!(differing(before.into_iter(), before.into_iter()), 0);
1042        assert_eq!(differing(before.into_iter(), [].into_iter()), 4);
1043    }
1044
1045    #[test]
1046    fn only_a_known_distance_coming_closer_can_wait() {
1047        use tmt_rt::{Diff, News, Summary};
1048        let mut s = Summary::default();
1049        // The first distance on each side is news of the other kind, and so is a new relation.
1050        assert_eq!(s.news(1, Diff::Int(-9)), News::Other);
1051        assert_eq!(s.news(1, Diff::Int(-9)), News::Nothing);
1052        assert_eq!(s.news(1, Diff::Int(-10)), News::Nothing);
1053        assert_eq!(s.news(1, Diff::Int(-4)), News::Closer);
1054        assert_eq!(s.news(4, Diff::Int(7)), News::Other);
1055        assert_eq!(s.news(4, Diff::Int(6)), News::Closer);
1056        assert_eq!(s.news(1, Diff::Int(-1)), News::Closer);
1057        assert_eq!(s.news(2, Diff::Int(0)), News::Other);
1058        assert_eq!((s.max_neg, s.min_pos), (Some(-1), Some(6)));
1059        // Floats alike; a closer distance together with something new does not wait.
1060        assert_eq!(s.news(1, Diff::Float(-2.0)), News::Other);
1061        assert_eq!(s.news(1, Diff::Float(-1.5)), News::Closer);
1062        assert_eq!(s.news(4, Diff::Float(0.5)), News::Other);
1063        assert_eq!(s.news(4, Diff::Float(0.25)), News::Closer);
1064        let mut t = Summary::default();
1065        assert_eq!(t.news(1, Diff::Int(-9)), News::Other);
1066        assert_eq!(t.news(8, Diff::Int(-3)), News::Other);
1067        assert_eq!(t.news(8, Diff::None), News::Other);
1068    }
1069
1070    #[test]
1071    fn summary_classifies_type_and_distance_changes_independently() {
1072        use tmt_rt::{Diff, News, Summary};
1073
1074        let mut summary = Summary::default();
1075        for (rel, diff, expected) in [
1076            (1, Diff::Int(i128::MIN), News::Other),
1077            (1, Diff::Int(i128::MIN), News::Nothing),
1078            (1, Diff::Int(-1), News::Closer),
1079            (1, Diff::Int(i128::MAX), News::Other),
1080            (5, Diff::Int(1), News::Other),
1081            (2, Diff::Float(-0.0), News::Other),
1082            (2, Diff::Float(0.0), News::Nothing),
1083            (2, Diff::Float(f64::NAN), News::Nothing),
1084            (1, Diff::Float(-f64::MAX), News::Other),
1085            (1, Diff::Float(-f64::MIN_POSITIVE), News::Closer),
1086            (1, Diff::Float(-f64::MAX), News::Nothing),
1087            (4, Diff::Float(f64::MAX), News::Other),
1088            (4, Diff::Float(f64::MIN_POSITIVE), News::Closer),
1089            (1, Diff::None, News::Nothing),
1090        ] {
1091            assert_eq!(summary.news(rel, diff), expected, "{rel} {diff:?}");
1092        }
1093        assert_eq!(summary.rels, 7);
1094        assert!(summary.unvalued && summary.unfloat);
1095        assert_eq!((summary.max_neg, summary.min_pos), (Some(-1), Some(1)));
1096        assert_eq!(summary.f_max_neg, Some(-f64::MIN_POSITIVE));
1097        assert_eq!(summary.f_min_pos, Some(f64::MIN_POSITIVE));
1098    }
1099
1100    #[test]
1101    fn a_backlog_hands_out_the_latest_of_each_site_once() {
1102        use tmt_rt::{Backlog, Diff, Summary};
1103        let at = |d: i128| {
1104            let mut s = Summary::default();
1105            s.observe(1, Diff::Int(d));
1106            s
1107        };
1108        let mut backlog = Backlog::default();
1109        assert!(backlog.drain().is_empty());
1110        backlog.keep(7, at(-5));
1111        backlog.keep(2, at(-8));
1112        backlog.keep(7, at(-3));
1113        assert_eq!(backlog.drain(), [(7, at(-3)), (2, at(-8))]);
1114        assert!(backlog.drain().is_empty(), "written once");
1115        // Kept again after it was written: written again.
1116        backlog.keep(7, at(-1));
1117        assert_eq!(backlog.drain(), [(7, at(-1))]);
1118        // A site written by other means is not written from here, the others are.
1119        backlog.keep(7, at(-1));
1120        backlog.keep(2, at(-2));
1121        backlog.keep(9, at(-4));
1122        backlog.forget(2);
1123        backlog.forget(100);
1124        backlog.forget(1);
1125        assert_eq!(backlog.drain(), [(7, at(-1)), (9, at(-4))]);
1126        backlog.keep(2, at(-1));
1127        assert_eq!(backlog.drain(), [(2, at(-1))]);
1128    }
1129
1130    #[test]
1131    fn a_thread_remembers_what_it_recorded() {
1132        // Sites of their own, far from the ones other tests of this binary use.
1133        let site = 900_000;
1134        assert!(!tmt_rt::bits_known(b'A', site, 1));
1135        assert!(tmt_rt::bits_are_news(b'A', site, 1));
1136        assert!(!tmt_rt::bits_are_news(b'A', site, 1));
1137        assert!(tmt_rt::bits_known(b'A', site, 1));
1138        // Another bit of the same site is news once, and then both are known.
1139        assert!(!tmt_rt::bits_known(b'A', site, 3));
1140        assert!(tmt_rt::bits_are_news(b'A', site, 3));
1141        assert!(!tmt_rt::bits_are_news(b'A', site, 2));
1142        assert!(tmt_rt::bits_known(b'A', site, 3));
1143        // Each kind of record and each site has its own memory.
1144        for kind in *b"RLB" {
1145            assert!(!tmt_rt::bits_known(kind, site, 1), "{}", kind as char);
1146            assert!(tmt_rt::bits_are_news(kind, site, 1), "{}", kind as char);
1147            assert!(!tmt_rt::bits_are_news(kind, site, 1), "{}", kind as char);
1148        }
1149        assert!(tmt_rt::bits_are_news(b'A', site + 1, 1));
1150        assert!(!tmt_rt::bits_known(b'A', site - 1, 1));
1151        // And each thread: a test is a thread.
1152        std::thread::spawn(move || {
1153            assert!(!tmt_rt::bits_known(b'A', site, 1));
1154            assert!(tmt_rt::bits_are_news(b'A', site, 1));
1155        })
1156        .join()
1157        .unwrap();
1158    }
1159}