vers3 0.2.0

Explicit-state model checking library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026, Marco Elver <me@marcoelver.com>

//! Search algorithms: BFS over the state space.
//!
//! Two variants:
//!
//! - [`Bfs`] — stores full states in the visited set. Exact (no false negatives),
//!   higher memory use. Preferred when states are small or the space is bounded.
//! - [`BfsHashing`] — stores only state *hashes*. Memory-efficient, but hash
//!   collisions can cause false state equivalences (missed states). Use when the
//!   state space is large and collision probability is acceptably low.
//!
//! Both return a [`Counterexample`] on error, which carries whatever evidence
//! for the path to the error the search could produce (see [`TraceEvidence`]).

use crate::ts::{CheckerError, State, Stepping};
use crate::types::{StateHash, hash_of};
use std::collections::hash_map::Entry;
use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::rc::Rc;
use std::time::Instant;

// --- Trace types -------------------------------------------------------------

/// A sequence of `(state, rule_name)` pairs from an initial state to an error.
///
/// The first entry is the initial state with an empty rule name. Each subsequent
/// entry is the state *after* applying the named rule.
pub type Trace<S> = Vec<(S, String)>;

/// A compact trace storing only [`StateHash`]es instead of full states.
///
/// Elements are ordered from **last** (error) state to **first** (initial) state.
/// Used internally by [`BfsHashing`] with [`BfsHashing::with_verbose`]`(false)`.
pub type HashTrace = Vec<StateHash>;

// --- Counterexample ----------------------------------------------------------

/// The evidence a [`Counterexample`] carries for the path leading to the error.
///
/// Which variant applies is decided by the search, so consumers match on it
/// rather than inferring it from an empty trace or a set flag.
pub enum TraceEvidence<S> {
    /// No path applies: the violation was found at the final property check.
    None,
    /// Full state trace, from an initial state to the violating state.
    States(Trace<S>),
    /// State trace that stops short of the violating state: replay could not
    /// reproduce the whole recorded path (e.g. a hash collision broke the
    /// parent chain). Empty if no initial state matched the recorded root.
    /// Only [`BfsHashing`] trace reconstruction can produce this.
    PartialStates(Trace<S>),
    /// State hashes only, error state first. Produced by [`BfsHashing`] with
    /// [`BfsHashing::with_verbose`]`(false)`.
    Hashes(HashTrace),
}

impl<S> TraceEvidence<S> {
    /// The reconstructed states, or an empty slice if none are available.
    pub fn states(&self) -> &[(S, String)] {
        match self {
            Self::States(t) | Self::PartialStates(t) => t,
            Self::None | Self::Hashes(_) => &[],
        }
    }
}

/// A property violation or deadlock found during search.
///
/// Contains the [`CheckerError`], the [`TraceEvidence`] for how the error was
/// reached, and the search progress counters at the time of the error.
pub struct Counterexample<S: State> {
    /// What went wrong.
    pub error: CheckerError,
    /// Evidence for the path from an initial state to the error.
    pub evidence: TraceEvidence<S>,
    /// States fully explored at the time of the error.
    pub states_visited: usize,
    /// States in the queue (including the erroring state) at the time of the error.
    pub states_queued: usize,
}

impl<S: State> Counterexample<S> {
    /// A violation reported by [`Stepping::check_final`], after the state space
    /// was exhausted: no single state or path is at fault, so there is no trace.
    fn final_violation(property: String, detail: String, states_visited: usize) -> Self {
        Self {
            error: CheckerError::PropertyViolation {
                property,
                detail: Some(detail),
            },
            evidence: TraceEvidence::None,
            states_visited,
            states_queued: 0,
        }
    }
}

impl<S: State + fmt::Debug> fmt::Debug for Counterexample<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Counterexample {{ error: {:?}, {}, visited: {}, queued: {} }}",
            self.error,
            match &self.evidence {
                TraceEvidence::None => "no trace".to_owned(),
                TraceEvidence::States(t) => format!("trace_len: {}", t.len()),
                TraceEvidence::PartialStates(t) => format!("partial_trace_len: {}", t.len()),
                TraceEvidence::Hashes(ht) => format!("hash_trace_len: {}", ht.len()),
            },
            self.states_visited,
            self.states_queued,
        )
    }
}

// --- Stats -------------------------------------------------------------------

/// Statistics returned on successful (violation-free) search completion.
#[derive(Debug, Clone)]
pub struct Stats<S: State> {
    /// Total number of distinct states visited.
    pub states_visited: usize,
    /// Queue size at search termination (0 for full traversal, >0 if monitor stopped early).
    pub states_queued: usize,
    /// Wall-clock duration of the search.
    pub duration: std::time::Duration,
    /// States for which `accept_fn` returned `true`, in encounter order.
    pub accept_states: Vec<S>,
    /// Total [`Unknown`](crate::Unknown)s returned by rules: cases the model
    /// reached but does not model. Nonzero means the state space was not fully
    /// checked.
    pub unknowns: usize,
}

impl<S: State + fmt::Display> fmt::Display for Stats<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "visited={} queued={} accept={} unknowns={} duration={:.2}s",
            self.states_visited,
            self.states_queued,
            self.accept_states.len(),
            self.unknowns,
            self.duration.as_secs_f64()
        )
    }
}

// --- Bfs (exact) -------------------------------------------------------------

/// Exact BFS: the visited map is keyed by the full state.
///
/// States are merged only when `S`'s `Eq` says they are equal, never by hash
/// collision alone; exactness is thus relative to `Eq`. Parent pointers are
/// stored as `(parent_state, rule_name)` pairs for trace reconstruction.
/// States are reference-counted, so each distinct state is allocated once and
/// shared by the visited map, the queue, and its children's parent pointers.
pub struct Bfs<S: State> {
    // Maps state → Option<(parent_state, rule_name)>; the initial states have no parent (None).
    visited: HashMap<Rc<S>, Option<(Rc<S>, String)>, ahash::RandomState>,
    accept_fn: Option<Box<dyn Fn(&S) -> bool>>,
    monitor: Option<Box<dyn FnMut(usize, usize, &[S]) -> bool>>,
}

impl<S: State> Bfs<S> {
    /// Create a search with no accept predicate and no monitor.
    pub fn new() -> Self {
        Self {
            visited: HashMap::with_hasher(ahash::RandomState::new()),
            accept_fn: None,
            monitor: None,
        }
    }

    /// Set a predicate that marks states as accepting (collected in [`Stats::accept_states`]).
    pub fn with_accept(mut self, f: impl Fn(&S) -> bool + 'static) -> Self {
        self.accept_fn = Some(Box::new(f));
        self
    }

    /// Set a monitor callback invoked before each state is processed.
    ///
    /// Arguments: `(states_visited, states_queued, accept_states)`.
    /// Return `false` to stop the search early.
    pub fn with_monitor(mut self, f: impl FnMut(usize, usize, &[S]) -> bool + 'static) -> Self {
        self.monitor = Some(Box::new(f));
        self
    }

    /// Run BFS from `initial` states until the state space is exhausted or an
    /// error is found. The transition system is consumed, preventing accidental
    /// reuse with accumulated property state.
    pub fn run(
        &mut self,
        initial: Vec<S>,
        mut ts: impl Stepping<S>,
    ) -> Result<Stats<S>, Counterexample<S>> {
        self.visited.clear();
        let start = Instant::now();
        let mut queue: VecDeque<Rc<S>> = VecDeque::new();
        let mut states_visited: usize = 0;
        let mut unknowns: usize = 0;
        let mut accept_states: Vec<S> = Vec::new();

        for s in initial {
            if let Entry::Vacant(e) = self.visited.entry(Rc::new(s)) {
                queue.push_back(Rc::clone(e.key()));
                e.insert(None);
            }
        }

        while !queue.is_empty() {
            // Monitor is called before processing the front state; the queue
            // still holds it, so `queue.len()` includes the current state.
            if let Some(ref mut m) = self.monitor
                && !m(states_visited, queue.len(), &accept_states)
            {
                break;
            }

            let current_state = queue.pop_front().unwrap();

            if let Some(ref af) = self.accept_fn
                && af(&current_state)
            {
                accept_states.push((*current_state).clone());
            }

            match ts.step(&current_state) {
                Ok((successors, step_unknowns)) => {
                    states_visited += 1;
                    unknowns += step_unknowns.len();
                    for (next_state, rule_name) in successors {
                        if let Entry::Vacant(e) = self.visited.entry(Rc::new(next_state)) {
                            queue.push_back(Rc::clone(e.key()));
                            e.insert(Some((Rc::clone(&current_state), rule_name)));
                        }
                    }
                }
                Err(e) => {
                    // The current state is already popped, but still counts as queued.
                    let states_queued = queue.len() + 1;
                    let trace = self.build_trace(&current_state);
                    return Err(Counterexample {
                        error: e,
                        evidence: TraceEvidence::States(trace),
                        states_visited,
                        states_queued,
                    });
                }
            }
        }

        // Final property checks.
        if let Some((prop_name, detail)) = ts.check_final() {
            return Err(Counterexample::final_violation(
                prop_name,
                detail,
                states_visited,
            ));
        }

        Ok(Stats {
            states_visited,
            states_queued: queue.len(),
            duration: start.elapsed(),
            accept_states,
            unknowns,
        })
    }

    /// Reconstruct a trace by walking parent pointers back to a root.
    fn build_trace(&self, current: &S) -> Trace<S> {
        let mut path: Vec<(S, String)> = Vec::new();
        let mut cur: &S = current;
        while let Some(Some((parent, rule_name))) = self.visited.get(cur) {
            path.push((cur.clone(), rule_name.clone()));
            cur = parent;
        }
        path.push((cur.clone(), String::new())); // root: no incoming rule
        path.reverse();
        path
    }
}

impl<S: State> Default for Bfs<S> {
    fn default() -> Self {
        Self::new()
    }
}

// --- BfsHashing (memory-efficient) -------------------------------------------

/// Maps [`StateHash`]es to states. Uses [`ahash`] for fast hashing.
pub type StateMap<S> = std::collections::HashMap<StateHash, S, ahash::RandomState>;

/// Memory-efficient BFS: stores only state *hashes* in the visited map.
///
/// Uses roughly 16 bytes per visited state (vs. full state size for [`Bfs`]).
/// On error, the trace is by default reconstructed by replaying the system
/// from the initial states; with [`BfsHashing::with_verbose`]`(false)`, a
/// compact [`HashTrace`] is returned instead.
///
/// Hash collisions can cause false state equivalences, pruning states that are
/// actually distinct. For typical 64-bit hashes and state spaces under ~10⁹,
/// collision probability is negligible.
pub struct BfsHashing<S: State> {
    visited: StateMap<Option<(StateHash, String)>>,
    initial: Vec<S>,
    accept_fn: Option<Box<dyn Fn(&S) -> bool>>,
    monitor: Option<Box<dyn FnMut(usize, usize, &[S]) -> bool>>,
    verbose: bool,
}

impl<S: State> BfsHashing<S> {
    /// Create a search with no accept predicate, no monitor, and full-trace
    /// reconstruction enabled.
    pub fn new() -> Self {
        Self {
            visited: StateMap::with_hasher(ahash::RandomState::new()),
            initial: Vec::new(),
            accept_fn: None,
            monitor: None,
            verbose: true,
        }
    }

    /// Set a predicate that marks states as accepting.
    pub fn with_accept(mut self, f: impl Fn(&S) -> bool + 'static) -> Self {
        self.accept_fn = Some(Box::new(f));
        self
    }

    /// Set a monitor callback invoked before each state is processed.
    ///
    /// Arguments: `(states_visited, states_queued, accept_states)`.
    /// Return `false` to stop the search early.
    pub fn with_monitor(mut self, f: impl FnMut(usize, usize, &[S]) -> bool + 'static) -> Self {
        self.monitor = Some(Box::new(f));
        self
    }

    /// Enable or disable full-trace reconstruction on error (default: enabled).
    ///
    /// When disabled, a counterexample carries a compact
    /// [`TraceEvidence::Hashes`] instead of replaying the system to
    /// reconstruct full states.
    pub fn with_verbose(mut self, enabled: bool) -> Self {
        self.verbose = enabled;
        self
    }

    /// Run BFS. Same contract as [`Bfs::run`].
    pub fn run(
        &mut self,
        initial: Vec<S>,
        mut ts: impl Stepping<S>,
    ) -> Result<Stats<S>, Counterexample<S>> {
        self.visited.clear();
        self.initial = initial.clone();
        let start = Instant::now();
        let mut queue: VecDeque<S> = VecDeque::new();
        let mut states_visited: usize = 0;
        let mut unknowns: usize = 0;
        let mut accept_states: Vec<S> = Vec::new();

        for s in &initial {
            let h = StateHash(hash_of(s));
            if let std::collections::hash_map::Entry::Vacant(e) = self.visited.entry(h) {
                e.insert(None);
                queue.push_back(s.clone());
            }
        }

        while !queue.is_empty() {
            if let Some(ref mut m) = self.monitor
                && !m(states_visited, queue.len(), &accept_states)
            {
                break;
            }

            let current_state = queue.front().unwrap().clone();
            let current_hash = StateHash(hash_of(&current_state));

            if let Some(ref af) = self.accept_fn
                && af(&current_state)
            {
                accept_states.push(current_state.clone());
            }

            match ts.step(&current_state) {
                Ok((successors, step_unknowns)) => {
                    states_visited += 1;
                    unknowns += step_unknowns.len();
                    for (next_state, rule_name) in successors {
                        let next_hash = StateHash(hash_of(&next_state));
                        if let std::collections::hash_map::Entry::Vacant(e) =
                            self.visited.entry(next_hash)
                        {
                            e.insert(Some((current_hash, rule_name)));
                            queue.push_back(next_state);
                        }
                    }
                    queue.pop_front();
                }
                Err(e) => {
                    let states_queued = queue.len();
                    let evidence = if self.verbose {
                        reconstruct_trace(&self.initial, current_hash, &self.visited, &mut ts)
                    } else {
                        TraceEvidence::Hashes(self.build_hash_trace(current_hash))
                    };
                    return Err(Counterexample {
                        error: e,
                        evidence,
                        states_visited,
                        states_queued,
                    });
                }
            }
        }

        if let Some((prop_name, detail)) = ts.check_final() {
            return Err(Counterexample::final_violation(
                prop_name,
                detail,
                states_visited,
            ));
        }

        Ok(Stats {
            states_visited,
            states_queued: queue.len(),
            duration: start.elapsed(),
            accept_states,
            unknowns,
        })
    }

    /// Build a hash trace from the error state back to a root.
    ///
    /// Ordered from **error** (last) to **root** (first).
    fn build_hash_trace(&self, error_hash: StateHash) -> HashTrace {
        parent_hash_path(&self.visited, error_hash)
            .into_iter()
            .map(|(h, _)| h)
            .collect()
    }
}

impl<S: State> Default for BfsHashing<S> {
    fn default() -> Self {
        Self::new()
    }
}

// --- Trace reconstruction ----------------------------------------------------

/// Walk parent pointers from `error_hash` back to a root.
///
/// Returns `(hash, rule_name)` pairs ordered from **error** to **root**, where
/// `rule_name` is the rule that produced that state (empty for a root). Stops
/// early, yielding only the suffix, if the parent chain is broken.
fn parent_hash_path(
    visited: &StateMap<Option<(StateHash, String)>>,
    error_hash: StateHash,
) -> Vec<(StateHash, String)> {
    let mut path = Vec::new();
    let mut h = error_hash;
    loop {
        match visited.get(&h) {
            Some(None) => {
                path.push((h, String::new()));
                break;
            }
            Some(Some((parent_hash, rule_name))) => {
                path.push((h, rule_name.clone()));
                h = *parent_hash;
            }
            None => break, // broken parent chain
        }
    }
    path
}

/// Reconstruct a full [`Trace`] from hash-only parent pointers by replaying
/// the transition system from the initial states.
///
/// Yields [`TraceEvidence::States`] when the replay reproduced the whole
/// recorded hash path, and [`TraceEvidence::PartialStates`] when it could not
/// (e.g. a hash collision made the parent chain unreplayable), carrying the
/// prefix that was reconstructed.
pub fn reconstruct_trace<S: State>(
    initial: &[S],
    error_hash: StateHash,
    visited: &StateMap<Option<(StateHash, String)>>,
    ts: &mut impl Stepping<S>,
) -> TraceEvidence<S> {
    let mut hash_path = parent_hash_path(visited, error_hash);
    hash_path.reverse();

    let root = hash_path.first().and_then(|(root_hash, _)| {
        initial
            .iter()
            .find(|s| StateHash(hash_of(*s)) == *root_hash)
    });
    let Some(mut current) = root.cloned() else {
        // No initial state matches the recorded root.
        return TraceEvidence::PartialStates(Vec::new());
    };

    let mut trace: Trace<S> = vec![(current.clone(), String::new())];

    for (next_hash, _) in hash_path.iter().skip(1) {
        let successors = match ts.step(&current) {
            Ok((s, _)) => s,
            Err(_) => break,
        };
        match successors
            .into_iter()
            .find(|(s, _)| StateHash(hash_of(s)) == *next_hash)
        {
            Some((next_state, rule_name)) => {
                current = next_state.clone();
                trace.push((next_state, rule_name));
            }
            None => break, // no successor matches the recorded hash
        }
    }

    if trace.len() == hash_path.len() {
        TraceEvidence::States(trace)
    } else {
        TraceEvidence::PartialStates(trace)
    }
}

// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ts::{
        Property, TransitionSysSimulation, TransitionSystem, Unknown, invariant, rule, rule_try,
    };
    use std::fmt;

    #[derive(Clone, Hash, PartialEq, Eq, Debug)]
    struct Num(i32);
    impl fmt::Display for Num {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "Num({})", self.0)
        }
    }

    /// Increment rule: at s==5, reset to `reset_to` then increment.
    fn inc_rule(reset_to: i32) -> impl crate::ts::Rule<Num> + 'static {
        rule(
            format!("inc(reset={reset_to})"),
            |_: &Num| true,
            move |s: &mut Num| {
                if s.0 == 5 {
                    s.0 = reset_to;
                }
                s.0 += 1;
                true
            },
        )
    }

    fn ts_increment(reset_to: i32) -> TransitionSystem<Num> {
        let mut ts = TransitionSystem::new().with_deadlock_detection(false);
        ts.add_rule(inc_rule(reset_to));
        ts
    }

    #[test]
    fn bfs_accept_state() {
        let mut ts = ts_increment(0);
        ts.add_rule(inc_rule(0)); // duplicate — should not affect outcome
        let stats = Bfs::new()
            .with_accept(|s: &Num| s.0 == 3)
            .run(vec![Num(1)], ts)
            .unwrap();
        assert_eq!(stats.accept_states, vec![Num(3)]);
        assert_eq!(stats.states_visited, 5);
        assert_eq!(stats.states_queued, 0);
    }

    #[test]
    fn bfsh_accept_state() {
        let mut ts = ts_increment(0);
        ts.add_rule(inc_rule(0));
        let stats = BfsHashing::new()
            .with_accept(|s: &Num| s.0 == 3)
            .run(vec![Num(1)], ts)
            .unwrap();
        assert_eq!(stats.accept_states, vec![Num(3)]);
        assert_eq!(stats.states_visited, 5);
        assert_eq!(stats.states_queued, 0);
    }

    fn make_deadlock_ts() -> TransitionSystem<Num> {
        let mut ts = TransitionSystem::new(); // deadlock detection ON
        ts.add_rule(rule(
            "inc",
            |s: &Num| s.0 != 4,
            |s: &mut Num| {
                s.0 += 1;
                true
            },
        ));
        ts.add_property(invariant("never5", |s: &Num| s.0 != 5));
        ts
    }

    #[test]
    fn bfs_deadlock() {
        let cex = Bfs::new()
            .run(vec![Num(1)], make_deadlock_ts())
            .unwrap_err();
        assert!(matches!(cex.error, CheckerError::Deadlock));
        assert_eq!(cex.states_visited, 3);
        assert_eq!(cex.states_queued, 1);
    }

    #[test]
    fn bfsh_deadlock() {
        let cex = BfsHashing::new()
            .run(vec![Num(1)], make_deadlock_ts())
            .unwrap_err();
        assert!(matches!(cex.error, CheckerError::Deadlock));
        assert_eq!(cex.states_visited, 3);
        assert_eq!(cex.states_queued, 1);
    }

    #[test]
    fn bfs_monitor() {
        let mut bfs =
            Bfs::new()
                .with_accept(|s: &Num| s.0 == 3)
                .with_monitor(|visited, queued, accept| {
                    if visited == 4 {
                        assert_eq!(accept.len(), 1);
                        assert_eq!(queued, 1);
                        return false;
                    }
                    true
                });
        let mut ts = ts_increment(0);
        ts.add_rule(inc_rule(0));
        let stats = bfs.run(vec![Num(1)], ts).unwrap();
        assert_eq!(stats.accept_states[0], Num(3));
        assert_eq!(stats.states_visited, 4);
        assert_eq!(stats.states_queued, 1);
    }

    #[test]
    fn bfsh_monitor() {
        let mut bfs = BfsHashing::new()
            .with_accept(|s: &Num| s.0 == 3)
            .with_monitor(|visited, queued, accept| {
                if visited == 4 {
                    assert_eq!(accept.len(), 1);
                    assert_eq!(queued, 1);
                    return false;
                }
                true
            });
        let mut ts = ts_increment(0);
        ts.add_rule(inc_rule(0));
        let stats = bfs.run(vec![Num(1)], ts).unwrap();
        assert_eq!(stats.accept_states[0], Num(3));
        assert_eq!(stats.states_visited, 4);
        assert_eq!(stats.states_queued, 1);
    }

    fn make_invariant_ts() -> TransitionSystem<Num> {
        let mut ts = ts_increment(0);
        ts.add_property(invariant("not3", |s: &Num| s.0 != 3));
        ts
    }

    #[test]
    fn bfs_invariant() {
        let cex = Bfs::new()
            .run(vec![Num(1)], make_invariant_ts())
            .unwrap_err();
        assert!(
            matches!(cex.error, CheckerError::PropertyViolation { ref property, .. } if property == "not3")
        );
        assert_eq!(cex.evidence.states().len(), 3); // Num(1), Num(2), Num(3)
        assert_eq!(cex.states_visited, 2);
        assert_eq!(cex.states_queued, 1);
    }

    #[test]
    fn bfsh_invariant() {
        let cex = BfsHashing::new()
            .run(vec![Num(1)], make_invariant_ts())
            .unwrap_err();
        assert!(matches!(cex.error, CheckerError::PropertyViolation { .. }));
        assert!(matches!(cex.evidence, TraceEvidence::States(_)));
        assert_eq!(cex.evidence.states().len(), 3);
        assert_eq!(cex.states_visited, 2);
        assert_eq!(cex.states_queued, 1);
    }

    #[test]
    fn bfsh_no_verbose_on_error() {
        let mut ts = ts_increment(0);
        ts.add_property(invariant("not3", |s: &Num| s.0 != 3));
        let cex = BfsHashing::new()
            .with_verbose(false)
            .run(vec![Num(1)], ts)
            .unwrap_err();
        assert!(matches!(cex.error, CheckerError::PropertyViolation { .. }));
        let TraceEvidence::Hashes(ht) = &cex.evidence else {
            panic!("expected a hash trace, got {:?}", cex);
        };
        assert_eq!(ht.len(), 3); // hash(Num3), hash(Num2), hash(Num1)
        assert!(cex.evidence.states().is_empty());
        assert_eq!(cex.states_visited, 2);
        assert_eq!(cex.states_queued, 1);
    }
    // Bfs always produces full state traces, never hashes.
    #[test]
    fn bfs_always_verbose() {
        let mut ts = ts_increment(0);
        ts.add_property(invariant("not3", |s: &Num| s.0 != 3));
        let cex = Bfs::new().run(vec![Num(1)], ts).unwrap_err();
        assert!(matches!(cex.evidence, TraceEvidence::States(_)));
        assert_eq!(cex.evidence.states().len(), 3);
    }

    #[test]
    fn bfs_liveness_satisfied() {
        // reset_to=0: 5→0+1=1. So: 1→2→3→4→5→1. Excluding 1: edges 2→3,3→4,4→5 — no cycle.
        struct Wrap(std::collections::HashSet<(u64, u64)>);
        impl Property<Num> for Wrap {
            fn name(&self) -> &str {
                "Liveness"
            }
            fn on_successors(&mut self, state: &Num, succs: &[(Num, String)], _: &[Unknown]) {
                for (next, _) in succs {
                    if state.0 != 1 && next.0 != 1 {
                        self.0.insert((hash_of(state), hash_of(next)));
                    }
                }
            }
            fn is_satisfied(&self) -> Option<String> {
                if crate::util::is_acyclic(&self.0) {
                    None
                } else {
                    Some("cycle detected".to_owned())
                }
            }
        }
        let mut ts = ts_increment(0);
        ts.add_property(Wrap(Default::default()));
        let result = Bfs::new().run(vec![Num(1)], ts).unwrap();
        assert_eq!(result.states_visited, 5);
    }

    #[test]
    fn bfs_liveness_fail() {
        // reset_to=1: 5→1+1=2. So: 1→2→3→4→5→2 (cycle 2↔3↔4↔5). Edge 5→2 closes cycle.
        struct Wrap(std::collections::HashSet<(u64, u64)>);
        impl Property<Num> for Wrap {
            fn name(&self) -> &str {
                "Liveness"
            }
            fn on_successors(&mut self, state: &Num, succs: &[(Num, String)], _: &[Unknown]) {
                for (next, _) in succs {
                    if state.0 != 1 && next.0 != 1 {
                        self.0.insert((hash_of(state), hash_of(next)));
                    }
                }
            }
            fn is_satisfied(&self) -> Option<String> {
                if crate::util::is_acyclic(&self.0) {
                    None
                } else {
                    Some("cycle detected".to_owned())
                }
            }
        }
        let mut ts = ts_increment(1);
        ts.add_property(Wrap(Default::default()));
        let cex = Bfs::new().run(vec![Num(1)], ts).unwrap_err();
        assert!(
            matches!(cex.error, CheckerError::PropertyViolation { ref property, .. } if property == "Liveness")
        );
        assert_eq!(cex.states_visited, 5);
    }

    /// Counts unknowns across all steps; satisfied iff total == 1.
    struct CountUnknowns(usize);
    impl Property<Num> for CountUnknowns {
        fn name(&self) -> &str {
            "CheckUnknown"
        }
        fn on_successors(&mut self, _: &Num, _: &[(Num, String)], unknowns: &[Unknown]) {
            self.0 += unknowns.len();
        }
        fn is_satisfied(&self) -> Option<String> {
            if self.0 == 1 {
                None
            } else {
                Some(format!("expected 1 unknown, got {}", self.0))
            }
        }
    }

    fn make_unknowns_ts() -> TransitionSystem<Num> {
        let mut ts = TransitionSystem::new().with_deadlock_detection(false);
        ts.add_rule(rule_try(
            "unknown_at_3",
            |_: &Num| true,
            |s: &mut Num| {
                if s.0 == 3 {
                    s.0 += 1;
                    return Err(Unknown::new(s.0).into());
                }
                s.0 += 1;
                Ok(true)
            },
        ));
        ts.add_property(CountUnknowns(0));
        ts
    }

    #[test]
    fn bfs_has_unknowns() {
        let stats = Bfs::new().run(vec![Num(1)], make_unknowns_ts()).unwrap();
        assert_eq!(stats.states_visited, 3);
        assert_eq!(stats.states_queued, 0);
        assert_eq!(stats.unknowns, 1);
    }

    #[test]
    fn bfsh_has_unknowns() {
        let stats = BfsHashing::new()
            .run(vec![Num(1)], make_unknowns_ts())
            .unwrap();
        assert_eq!(stats.states_visited, 3);
        assert_eq!(stats.states_queued, 0);
        assert_eq!(stats.unknowns, 1);
    }

    // NumA and NumB: two state types with a simulation relation via From + PartialEq.
    #[derive(Clone, Hash, PartialEq, Eq, Debug)]
    struct NumA(i32); // "float" — under test
    #[derive(Clone, Hash, PartialEq, Eq, Debug)]
    struct NumB(i32); // "int" — reference

    impl fmt::Display for NumA {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "A({})", self.0)
        }
    }
    impl fmt::Display for NumB {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "B({})", self.0)
        }
    }

    impl From<NumA> for NumB {
        fn from(a: NumA) -> NumB {
            NumB(a.0)
        } // identity simulation relation
    }
    impl PartialEq<NumB> for NumA {
        fn eq(&self, other: &NumB) -> bool {
            self.0 == other.0
        }
    }

    fn inc_rule_a(reset_to: i32) -> impl crate::ts::Rule<NumA> + 'static {
        rule(
            format!("incA(reset={reset_to})"),
            |_: &NumA| true,
            move |s: &mut NumA| {
                if s.0 == 5 {
                    s.0 = reset_to;
                }
                s.0 += 1;
                true
            },
        )
    }
    fn inc_rule_b(reset_to: i32) -> impl crate::ts::Rule<NumB> + 'static {
        rule(
            format!("incB(reset={reset_to})"),
            |_: &NumB| true,
            move |s: &mut NumB| {
                if s.0 == 5 {
                    s.0 = reset_to;
                }
                s.0 += 1;
                true
            },
        )
    }

    #[test]
    fn bfs_simulation_fail() {
        // NumB TS: Increment(0) only.
        // NumA TS: Increment(0) AND Increment(3) — at s=5, A can go to 1 OR 4.
        // At A(5): B can only go to B(1). But A(4) != B(1) → SIMULATION violation.
        let mut sim_by = TransitionSystem::new().with_deadlock_detection(false);
        sim_by.add_rule(inc_rule_b(0));

        let mut ts_sim: TransitionSysSimulation<NumA, NumB> = TransitionSysSimulation::new(sim_by);
        ts_sim.add_rule(inc_rule_a(0));
        ts_sim.add_rule(inc_rule_a(3));

        let cex = Bfs::new().run(vec![NumA(1)], ts_sim).unwrap_err();
        assert!(
            matches!(cex.error, CheckerError::PropertyViolation { ref property, .. } if property == "SIMULATION")
        );
        assert_eq!(cex.states_visited, 4);
        assert_eq!(cex.states_queued, 1);
    }

    #[test]
    fn bfs_simulation_success() {
        // NumB TS: Increment(0) AND Increment(3). NumA TS: Increment(0) only.
        // A's single transition (to A(1) from A(5)) is matched by B's transition to B(1).
        let mut sim_by = TransitionSystem::new().with_deadlock_detection(false);
        sim_by.add_rule(inc_rule_b(0));
        sim_by.add_rule(inc_rule_b(3));

        let mut ts_sim: TransitionSysSimulation<NumA, NumB> = TransitionSysSimulation::new(sim_by);
        ts_sim.add_rule(inc_rule_a(0));

        let stats = Bfs::new().run(vec![NumA(1)], ts_sim).unwrap();
        assert_eq!(stats.states_visited, 5);
        assert_eq!(stats.states_queued, 0);
    }

    #[test]
    fn bfs_finds_all_states() {
        let mut ts = TransitionSystem::new().with_deadlock_detection(false);
        ts.add_rule(rule(
            "inc",
            |s: &Num| s.0 < 4,
            |s: &mut Num| {
                s.0 += 1;
                true
            },
        ));
        let stats = Bfs::new().run(vec![Num(0)], ts).unwrap();
        assert_eq!(stats.states_visited, 5); // 0,1,2,3,4
    }

    #[test]
    fn bfs_catches_violation() {
        let mut ts = TransitionSystem::new().with_deadlock_detection(false);
        ts.add_rule(rule(
            "inc",
            |_: &Num| true,
            |s: &mut Num| {
                s.0 += 1;
                true
            },
        ));
        ts.add_property(invariant("small", |s: &Num| s.0 < 3));
        let cex = Bfs::new().run(vec![Num(0)], ts).unwrap_err();
        assert!(matches!(cex.error, CheckerError::PropertyViolation { .. }));
        assert!(!cex.evidence.states().is_empty());
    }

    #[test]
    fn bfs_hashing_same_result() {
        let mut ts1 = TransitionSystem::new().with_deadlock_detection(false);
        ts1.add_rule(rule(
            "inc",
            |s: &Num| s.0 < 5,
            |s: &mut Num| {
                s.0 += 1;
                true
            },
        ));
        let mut ts2 = TransitionSystem::new().with_deadlock_detection(false);
        ts2.add_rule(rule(
            "inc",
            |s: &Num| s.0 < 5,
            |s: &mut Num| {
                s.0 += 1;
                true
            },
        ));

        let s1 = Bfs::new().run(vec![Num(0)], ts1).unwrap();
        let s2 = BfsHashing::new().run(vec![Num(0)], ts2).unwrap();
        assert_eq!(s1.states_visited, s2.states_visited);
    }
}