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
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026, Marco Elver <me@marcoelver.com>

//! Transition system: states, rules, properties, and the core step function.
//!
//! The [`TransitionSystem`] is the central model description. You register
//! [`Rule`]s (transitions) and [`Property`] checks, then hand it to a search
//! algorithm in [`crate::search`].

use crate::types::hash_of;
use std::error::Error;
use std::fmt;
use std::hash::Hash;

// --- Unknown -----------------------------------------------------------------

/// Signals that a rule fired but its outcome is not modelled.
///
/// Return from [`Rule::apply`] when the outcome depends on information outside
/// the model (e.g. an unresolved race), or when the model does not cover this
/// case yet: the state is reachable, but what happens next is left out. The
/// state does not count as a deadlock. The unknown is passed to
/// [`Property::on_successors`] and counted in
/// [`Stats::unknowns`](crate::search::Stats::unknowns).
#[derive(Debug, Clone)]
pub struct Unknown {
    /// Model-defined code identifying the unknown.
    pub code: i32,
}

impl Unknown {
    /// Create an unknown with a model-defined `code`.
    pub fn new(code: i32) -> Self {
        Self { code }
    }
}

/// Collection of [`Unknown`]s gathered during one step.
pub type Unknowns = Vec<Unknown>;

// --- RuleError ---------------------------------------------------------------

/// Errors a [`Rule::apply`] implementation can signal.
#[derive(Debug, Clone)]
pub enum RuleError {
    /// Unresolvable non-determinism; recorded, not fatal (see [`Unknown`]).
    Unknown(Unknown),
    /// Model-defined error (e.g. an internal model assertion failed). Fatal:
    /// the search stops and reports a counterexample with the trace to the
    /// state being expanded. Boxed to keep `Result<bool, RuleError>` small on
    /// the (very hot) success path.
    Model(Box<str>),
}

impl RuleError {
    /// Construct a [`RuleError::Model`].
    ///
    /// Use with `.ok_or_else()` or a bare `return Err(..)` where the message is
    /// formatted; see [`error_if`] for the plain-condition case.
    pub fn model(what: impl Into<String>) -> Self {
        Self::Model(what.into().into_boxed_str())
    }
}

impl From<Unknown> for RuleError {
    fn from(u: Unknown) -> Self {
        Self::Unknown(u)
    }
}

/// Signal a model-defined error from within a rule if `cond` holds.
///
/// Use with `?` inside [`rule_try`] closures; the search reports the error as a
/// counterexample with a full trace (rather than the model having to `panic!`,
/// which would abort without a trace).
///
/// # Example
///
/// ```
/// use vers3::{Stepping, TransitionSystem, error_if, rule_try};
///
/// #[derive(Clone, Hash, PartialEq, Eq, Debug)]
/// struct Depth(u32);
/// vers3::display_via_debug!(Depth);
///
/// let mut ts = TransitionSystem::new();
/// ts.add_rule(rule_try(
///     "descend",
///     |_: &Depth| true,
///     |s: &mut Depth| {
///         s.0 += 1;
///         error_if(s.0 > 8, "recursion too deep")?;
///         Ok(true)
///     },
/// ));
/// assert!(ts.step(&Depth(8)).is_err());
/// ```
pub fn error_if(cond: bool, what: impl Into<String>) -> Result<(), RuleError> {
    if cond {
        Err(RuleError::model(what))
    } else {
        Ok(())
    }
}

// --- CheckerError ------------------------------------------------------------

/// Errors that can be returned by [`TransitionSystem::step`].
#[derive(Debug, Clone)]
pub enum CheckerError {
    /// A registered [`Property`] returned `false` from [`Property::check_state`]
    /// or [`Property::is_satisfied`].
    PropertyViolation {
        /// Name of the violated property.
        property: String,
        /// Optional detail from [`Property::is_satisfied`] (e.g. a livelock cycle path).
        detail: Option<String>,
    },

    /// No rule was enabled in `state` and deadlock detection is on.
    Deadlock,

    /// A rule signalled a model-defined error via [`RuleError::Model`]
    /// (e.g. through [`error_if`]).
    ModelError {
        /// Name of the rule that raised the error.
        rule: String,
        /// The rule's description of the error.
        what: String,
    },
}

impl fmt::Display for CheckerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PropertyViolation {
                property,
                detail: None,
            } => {
                write!(f, "property violation: {property}")
            }
            Self::PropertyViolation {
                property,
                detail: Some(d),
            } => {
                write!(f, "property violation: {property}: {d}")
            }
            Self::Deadlock => write!(f, "deadlock"),
            Self::ModelError { rule, what } => {
                write!(f, "model error in rule {rule}: {what}")
            }
        }
    }
}

impl Error for CheckerError {}

// --- State -------------------------------------------------------------------

/// Marker trait for model states.
///
/// Automatically implemented for any type satisfying the bounds. You do not
/// implement this manually — just derive `Clone`, `Hash`, `PartialEq`, `Eq`,
/// and `Display` on your state struct.
pub trait State: Clone + Hash + Eq + fmt::Display + 'static {}
impl<S: Clone + Hash + Eq + fmt::Display + 'static> State for S {}

// --- Rule --------------------------------------------------------------------

/// A guarded transition: if [`Rule::precondition`] holds, [`Rule::apply`]
/// produces the next state.
///
/// Use the [`rule`] constructor for closure-based rules.
pub trait Rule<S: State> {
    /// Short human-readable name, shown in counterexample traces.
    fn name(&self) -> &str;

    /// Returns `true` if this rule is enabled in `state`.
    fn precondition(&self, state: &S) -> bool;

    /// Apply the rule to `state` (mutating it into the successor).
    ///
    /// Return `Ok(true)` to keep the successor, `Ok(false)` to discard it
    /// (e.g. post-condition failed), `Err(RuleError::Unknown)` to signal that
    /// the transition cannot be resolved deterministically, or
    /// `Err(RuleError::Model)` to signal a model-defined error (fatal; see
    /// [`error_if`]).
    fn apply(&self, state: &mut S) -> Result<bool, RuleError>;
}

/// Closure-based [`Rule`]. Construct with [`rule`] or [`rule_try`].
pub struct RuleFn<S> {
    name: String,
    precondition: Box<dyn Fn(&S) -> bool>,
    apply: Box<dyn Fn(&mut S) -> Result<bool, RuleError>>,
}

/// Construct a [`Rule`] from closures.
///
/// The `apply` closure returns `bool`; use [`rule_try`] if you need to signal
/// [`Unknown`].
///
/// # Example
///
/// ```
/// use vers3::rule;
///
/// #[derive(Clone, Hash, PartialEq, Eq)]
/// struct Counter(u32);
/// impl std::fmt::Display for Counter {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) }
/// }
///
/// let inc = rule("increment", |s: &Counter| s.0 < 10, |s: &mut Counter| { s.0 += 1; true });
/// ```
pub fn rule<S: State>(
    name: impl Into<String>,
    precondition: impl Fn(&S) -> bool + 'static,
    apply: impl Fn(&mut S) -> bool + 'static,
) -> RuleFn<S> {
    RuleFn {
        name: name.into(),
        precondition: Box::new(precondition),
        apply: Box::new(move |s| Ok((apply)(s))),
    }
}

/// Construct a [`Rule`] from closures where `apply` can return a [`RuleError`]
/// — an [`Unknown`] (via `.into()` or `?`) or a model error (via [`error_if`]).
pub fn rule_try<S: State>(
    name: impl Into<String>,
    precondition: impl Fn(&S) -> bool + 'static,
    apply: impl Fn(&mut S) -> Result<bool, RuleError> + 'static,
) -> RuleFn<S> {
    RuleFn {
        name: name.into(),
        precondition: Box::new(precondition),
        apply: Box::new(apply),
    }
}

impl<S: State> Rule<S> for RuleFn<S> {
    fn name(&self) -> &str {
        &self.name
    }

    fn precondition(&self, state: &S) -> bool {
        (self.precondition)(state)
    }

    fn apply(&self, state: &mut S) -> Result<bool, RuleError> {
        (self.apply)(state)
    }
}

// --- Property ----------------------------------------------------------------

/// A property to check over the state space.
///
/// The three hooks correspond to different verification phases:
///
/// - [`Property::check_state`] — checked at every visited state (safety invariant).
/// - [`Property::on_successors`] — called after successors are computed, for
///   properties that need to reason about transitions (e.g. liveness).
/// - [`Property::is_satisfied`] — called once after the full state space is
///   explored, for properties with global acceptance conditions.
///
/// Use [`invariant`] for the common case of a stateless safety predicate.
pub trait Property<S: State> {
    /// Short human-readable name, shown in violation reports.
    fn name(&self) -> &str;

    /// Check a safety invariant at `state`. Return `false` to signal violation.
    ///
    /// Called before computing successors, so the trace ends at the violating state.
    fn check_state(&self, _state: &S) -> bool {
        true
    }

    /// Called after successors of `state` have been computed.
    ///
    /// `successors` is a slice of `(next_state, rule_name)` pairs.
    /// `unknowns` contains any [`Unknown`]s thrown by rules during this step.
    fn on_successors(&mut self, _state: &S, _successors: &[(S, String)], _unknowns: &[Unknown]) {}

    /// Final acceptance check after the full state space has been explored.
    ///
    /// Return `None` if satisfied, or `Some(reason)` with a human-readable
    /// description of the violation (e.g. a cycle path for liveness properties).
    fn is_satisfied(&self) -> Option<String> {
        None
    }
}

/// Closure-based safety invariant. Construct with [`invariant`].
pub struct InvariantFn<S> {
    name: String,
    check: Box<dyn Fn(&S) -> bool>,
}

/// Construct a stateless safety [`Property`] from a closure.
///
/// # Example
///
/// ```
/// use vers3::invariant;
///
/// #[derive(Clone, Hash, PartialEq, Eq)]
/// struct Counter(u32);
/// impl std::fmt::Display for Counter {
///     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) }
/// }
///
/// let bounded = invariant("counter_bounded", |s: &Counter| s.0 <= 10);
/// ```
pub fn invariant<S: State>(
    name: impl Into<String>,
    check: impl Fn(&S) -> bool + 'static,
) -> InvariantFn<S> {
    InvariantFn {
        name: name.into(),
        check: Box::new(check),
    }
}

impl<S: State> Property<S> for InvariantFn<S> {
    fn name(&self) -> &str {
        &self.name
    }

    fn check_state(&self, state: &S) -> bool {
        (self.check)(state)
    }
}

// --- Stepping trait ----------------------------------------------------------

/// Common interface for types that can drive a BFS search.
///
/// Implemented by [`TransitionSystem`] and [`TransitionSysSimulation`], allowing
/// the same [`crate::search::Bfs`] / [`crate::search::BfsHashing`] to work with
/// both.
pub trait Stepping<S: State> {
    /// Compute one step from `state`: check invariants, compute successors,
    /// detect deadlock, and notify properties.
    ///
    /// Returns `(successors, unknowns)` on success, or a [`CheckerError`] on
    /// invariant violation or deadlock.
    fn step(&mut self, state: &S) -> Result<(Vec<(S, String)>, Unknowns), CheckerError>;

    /// Check [`Property::is_satisfied`] after the full state space has been explored.
    ///
    /// Returns `Some((property_name, detail))` for the first unsatisfied property,
    /// or `None` if all properties are satisfied.
    fn check_final(&self) -> Option<(String, String)>;
}

// --- TransitionSystem --------------------------------------------------------

/// Central model description: holds rules and properties, drives state stepping.
///
/// Build with [`TransitionSystem::new`], register rules and properties, then
/// pass to a search algorithm.
pub struct TransitionSystem<S: State> {
    rules: Vec<Box<dyn Rule<S>>>,
    properties: Vec<Box<dyn Property<S>>>,
    deadlock_detection: bool,
}

impl<S: State> TransitionSystem<S> {
    /// Create an empty system with deadlock detection enabled.
    pub fn new() -> Self {
        Self {
            rules: Vec::new(),
            properties: Vec::new(),
            deadlock_detection: true,
        }
    }

    /// Register a transition rule.
    pub fn add_rule(&mut self, rule: impl Rule<S> + 'static) -> &mut Self {
        self.rules.push(Box::new(rule));
        self
    }

    /// Register a property to check.
    pub fn add_property(&mut self, prop: impl Property<S> + 'static) -> &mut Self {
        self.properties.push(Box::new(prop));
        self
    }

    /// Enable or disable deadlock detection (default: enabled).
    pub fn with_deadlock_detection(mut self, enabled: bool) -> Self {
        self.deadlock_detection = enabled;
        self
    }

    /// Phase 1 + 2: check invariants and compute successor candidates.
    ///
    /// Does not notify properties; does not check deadlock. Used internally by
    /// [`TransitionSysSimulation`].
    pub(crate) fn step_candidates(
        &self,
        state: &S,
    ) -> Result<(Vec<(S, String)>, Unknowns), CheckerError> {
        // Phase 1: check invariants.
        for prop in self.properties.iter() {
            if !prop.check_state(state) {
                return Err(CheckerError::PropertyViolation {
                    property: prop.name().to_owned(),
                    detail: None,
                });
            }
        }

        // Phase 2: compute successors. Duplicate successor states within one
        // step (different rules producing equal states) are kept only once,
        // attributed to the first producing rule. The searches dedup globally
        // anyway; this is so [`Property::on_successors`] observes each distinct
        // successor once and rule attribution does not depend on which
        // duplicate the search happens to keep.
        let mut successors: Vec<(S, String)> = Vec::new();
        // Hash of each entry in `successors`, to keep the quadratic dedup scan
        // off the (deep, and for symmetric states costly) `S: PartialEq` path.
        let mut successor_hashes: Vec<u64> = Vec::new();
        let mut unknowns: Unknowns = Vec::new();

        for rule in self.rules.iter() {
            if rule.precondition(state) {
                let mut next = state.clone();
                match rule.apply(&mut next) {
                    Ok(true) => {
                        let hash = hash_of(&next);
                        let is_dup = successor_hashes
                            .iter()
                            .zip(successors.iter())
                            .any(|(&h, (s, _))| h == hash && *s == next);
                        if !is_dup {
                            successor_hashes.push(hash);
                            successors.push((next, rule.name().to_owned()));
                        }
                    }
                    Ok(false) => {}
                    Err(RuleError::Unknown(u)) => unknowns.push(u),
                    Err(RuleError::Model(what)) => {
                        return Err(CheckerError::ModelError {
                            rule: rule.name().to_owned(),
                            what: what.into(),
                        });
                    }
                }
            }
        }

        Ok((successors, unknowns))
    }

    /// Phase 3 + 4: deadlock check and notify properties.
    pub(crate) fn step_finalize(
        &mut self,
        state: &S,
        successors: Vec<(S, String)>,
        unknowns: Unknowns,
    ) -> Result<(Vec<(S, String)>, Unknowns), CheckerError> {
        // Phase 3: deadlock detection (only if both queues empty).
        if self.deadlock_detection && successors.is_empty() && unknowns.is_empty() {
            return Err(CheckerError::Deadlock);
        }

        // Phase 4: notify properties of transitions.
        for prop in self.properties.iter_mut() {
            prop.on_successors(state, &successors, &unknowns);
        }

        Ok((successors, unknowns))
    }
}

impl<S: State> Stepping<S> for TransitionSystem<S> {
    /// Compute one step from `state`:
    ///
    /// 1. Check all property invariants — error on first violation.
    /// 2. For each enabled rule, clone `state`, apply, collect valid successors.
    /// 3. Detect deadlock if no successors and no unknowns.
    /// 4. Notify properties of `(state, successors, unknowns)`.
    ///
    /// Returns `(successors, unknowns)` or a [`CheckerError`].
    fn step(&mut self, state: &S) -> Result<(Vec<(S, String)>, Unknowns), CheckerError> {
        let (succs, unknowns) = self.step_candidates(state)?;
        self.step_finalize(state, succs, unknowns)
    }

    fn check_final(&self) -> Option<(String, String)> {
        self.properties
            .iter()
            .find_map(|p| p.is_satisfied().map(|detail| (p.name().to_owned(), detail)))
    }
}

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

// --- TransitionSysSimulation -------------------------------------------------

/// Checks that every transition in `S` is simulated by a corresponding
/// transition in `SimBy` (refinement / bisimulation checking).
///
/// For each successor `s` of the current state (in the `S` system), there must
/// exist a successor `ss` in the `SimBy` system such that `s == ss`. If no
/// such match exists, a `PropertyViolation("SIMULATION")` error is returned.
///
/// # Bounds
///
/// - `S: Into<SimBy>` — provides the simulation relation (state projection).
/// - `S: PartialEq<SimBy>` — checks whether two states are related.
pub struct TransitionSysSimulation<S: State, SimBy: State> {
    inner: TransitionSystem<S>,
    sim_by: TransitionSystem<SimBy>,
}

impl<S, SimBy> TransitionSysSimulation<S, SimBy>
where
    S: State,
    SimBy: State,
{
    /// Create a simulation checker. `sim_by` is the reference (simulated-by)
    /// transition system; add rules to `self` for the system under test.
    pub fn new(sim_by: TransitionSystem<SimBy>) -> Self {
        Self {
            inner: TransitionSystem::new(),
            sim_by,
        }
    }

    /// Register a transition rule on the system under test.
    pub fn add_rule(&mut self, rule: impl Rule<S> + 'static) -> &mut Self {
        self.inner.add_rule(rule);
        self
    }

    /// Register a property to check on the system under test.
    pub fn add_property(&mut self, prop: impl Property<S> + 'static) -> &mut Self {
        self.inner.add_property(prop);
        self
    }

    /// Enable or disable deadlock detection on the system under test (default: enabled).
    pub fn with_deadlock_detection(mut self, enabled: bool) -> Self {
        self.inner = self.inner.with_deadlock_detection(enabled);
        self
    }
}

impl<S, SimBy> Stepping<S> for TransitionSysSimulation<S, SimBy>
where
    S: State + Into<SimBy> + PartialEq<SimBy>,
    SimBy: State,
{
    fn step(&mut self, state: &S) -> Result<(Vec<(S, String)>, Unknowns), CheckerError> {
        // Compute sim-by successors (full step, including its own properties).
        let sim_by_state: SimBy = state.clone().into();
        let (sim_by_succs, _) = self.sim_by.step(&sim_by_state)?;

        // Compute inner candidates (invariants + rules, no property notify yet).
        let (candidates, unknowns) = self.inner.step_candidates(state)?;

        // Filter: every inner successor must be matched by a sim-by successor.
        let mut filtered = Vec::new();
        for (s, rule_name) in candidates {
            if sim_by_succs.iter().any(|(ss, _)| &s == ss) {
                filtered.push((s, rule_name));
            } else {
                return Err(CheckerError::PropertyViolation {
                    property: "SIMULATION".to_owned(),
                    detail: None,
                });
            }
        }

        self.inner.step_finalize(state, filtered, unknowns)
    }

    fn check_final(&self) -> Option<(String, String)> {
        self.inner.check_final()
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Clone, Hash, PartialEq, Eq, Debug)]
    struct Counter(u32);

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

    fn make_ts(limit: u32) -> TransitionSystem<Counter> {
        let mut ts = TransitionSystem::new();
        ts.add_rule(rule(
            "increment",
            move |s: &Counter| s.0 < limit,
            |s: &mut Counter| {
                s.0 += 1;
                true
            },
        ));
        ts.add_property(invariant("non_negative", move |s: &Counter| s.0 <= limit));
        ts
    }

    #[test]
    fn step_produces_successors() {
        let mut ts = make_ts(3);
        let (succs, unknowns) = ts.step(&Counter(0)).unwrap();
        assert_eq!(succs.len(), 1);
        assert_eq!(succs[0].0, Counter(1));
        assert_eq!(succs[0].1, "increment");
        assert!(unknowns.is_empty());
    }

    #[test]
    fn deadlock_at_limit() {
        let mut ts = make_ts(2);
        let err = ts.step(&Counter(2)).unwrap_err();
        assert!(matches!(err, CheckerError::Deadlock));
    }

    #[test]
    fn invariant_violation() {
        let mut ts: TransitionSystem<Counter> = TransitionSystem::new();
        ts.add_rule(rule(
            "inc",
            |_| true,
            |s: &mut Counter| {
                s.0 += 1;
                true
            },
        ));
        ts.add_property(invariant("zero_only", |s: &Counter| s.0 == 0));

        ts.step(&Counter(0)).unwrap();
        let err = ts.step(&Counter(1)).unwrap_err();
        assert!(matches!(err, CheckerError::PropertyViolation { .. }));
    }

    #[test]
    fn no_deadlock_when_disabled() {
        let mut ts = TransitionSystem::new().with_deadlock_detection(false);
        ts.add_rule(rule(
            "never_fires",
            |_: &Counter| false,
            |_: &mut Counter| true,
        ));
        let (succs, unknowns) = ts.step(&Counter(0)).unwrap();
        assert!(succs.is_empty());
        assert!(unknowns.is_empty());
    }

    #[test]
    fn unknown_collected_and_not_deadlock() {
        let mut ts = TransitionSystem::new();
        ts.add_rule(rule_try(
            "maybe_unknown",
            |_: &Counter| true,
            |_: &mut Counter| Err(Unknown::new(42).into()),
        ));
        let (succs, unknowns) = ts.step(&Counter(0)).unwrap();
        assert!(succs.is_empty());
        assert_eq!(unknowns.len(), 1);
        assert_eq!(unknowns[0].code, 42);
    }

    #[test]
    fn model_error_from_rule() {
        let mut ts = TransitionSystem::new();
        ts.add_rule(rule_try(
            "guarded",
            |_: &Counter| true,
            |s: &mut Counter| {
                s.0 += 1;
                error_if(s.0 > 1, "counter exceeded 1")?;
                Ok(true)
            },
        ));
        ts.step(&Counter(0)).unwrap();
        let err = ts.step(&Counter(1)).unwrap_err();
        assert!(matches!(
            err,
            CheckerError::ModelError { ref rule, ref what }
                if rule == "guarded" && what == "counter exceeded 1"
        ));
    }

    #[test]
    fn duplicate_successors_deduped() {
        // Two rules producing the same successor: properties and search see it once.
        let mut ts = TransitionSystem::new();
        for name in ["inc_a", "inc_b"] {
            ts.add_rule(rule(
                name,
                |_: &Counter| true,
                |s: &mut Counter| {
                    s.0 += 1;
                    true
                },
            ));
        }
        let (succs, _) = ts.step(&Counter(0)).unwrap();
        assert_eq!(succs.len(), 1);
        assert_eq!(succs[0].1, "inc_a"); // first producing rule wins
    }
}