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