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