# vers3: Explicit-State Model Checking Library
[](https://crates.io/crates/vers3)
[](https://docs.rs/vers3)
[](LICENSE)
[](Cargo.toml)
`vers3` is an explicit-state model checking library for Rust. Protocols are
described as a state type and a set of guarded rules, and `vers3` explores
every reachable state. When an invariant fails, a model assertion fires, or the
system deadlocks, it reports the shortest trace that reaches the error, with
the state changes at each step.
## Usage
```sh
cargo add vers3
```
The model below is a lock in which two processes test and set a flag in
separate steps. `vers3` finds the interleaving that puts both processes in the
critical section:
```rust,no_run
use std::fmt;
use std::process::ExitCode;
use vers3::{TransitionSystem, invariant, report, rule, search::Bfs};
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
enum Pc { Idle, Checked, Critical }
// States must be Clone + Hash + Eq + Display.
#[derive(Clone, Hash, PartialEq, Eq)]
struct Lock { pc: [Pc; 2], locked: bool }
// Reports diff states line by line, so print one field per line.
impl fmt::Display for Lock {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "locked = {}", self.locked)?;
for (i, pc) in self.pc.iter().enumerate() {
writeln!(f, "p{i} = {pc:?}")?;
}
Ok(())
}
}
fn main() -> ExitCode {
let mut ts = TransitionSystem::new();
for i in 0..2 {
// Bug: testing and setting `locked` are two separate steps.
ts.add_rule(rule(
format!("p{i} sees lock free"),
move |s: &Lock| s.pc[i] == Pc::Idle && !s.locked,
move |s: &mut Lock| { s.pc[i] = Pc::Checked; true },
));
ts.add_rule(rule(
format!("p{i} takes lock"),
move |s: &Lock| s.pc[i] == Pc::Checked,
move |s: &mut Lock| { s.locked = true; s.pc[i] = Pc::Critical; true },
));
ts.add_rule(rule(
format!("p{i} releases lock"),
move |s: &Lock| s.pc[i] == Pc::Critical,
move |s: &mut Lock| { s.locked = false; s.pc[i] = Pc::Idle; true },
));
}
ts.add_property(invariant("mutual exclusion", |s: &Lock| {
s.pc.iter().filter(|&&pc| pc == Pc::Critical).count() <= 1
}));
let init = Lock { pc: [Pc::Idle; 2], locked: false };
report::main_report(Bfs::new().run(vec![init], ts))
}
```
It exits with status 1 and prints:
```text
═══ COUNTEREXAMPLE ══════════════════════════════════
Error: property violation: mutual exclusion
Search stats: visited=8 queued=1
Trace length: 4 steps
── Step 0 (initial)
+ locked = false
+ p0 = Idle
+ p1 = Idle
── Step 1 via rule: p0 sees lock free
locked = false
- p0 = Idle
+ p0 = Checked
p1 = Idle
── Step 2 via rule: p1 sees lock free
locked = false
p0 = Checked
- p1 = Idle
+ p1 = Checked
── Step 3 via rule: p0 takes lock
- locked = false
+ locked = true
- p0 = Checked
+ p0 = Critical
p1 = Checked
── Step 4 via rule: p1 takes lock
locked = true
p0 = Critical
- p1 = Checked
+ p1 = Critical
═════════════════════════════════════════════════════
```
Merging the two steps into one rule fixes the lock, and the run then prints
`VERIFIED` with the number of states visited.
## Features
- **Two searches.** `Bfs` stores full states, so two states merge only when
they are equal. `BfsHashing` stores 64-bit state hashes and needs far less
memory.
- **Symmetry reduction.** `ArraySet<T, N>` hashes and compares its elements
without regard to slot order. States that differ only in how identical actors
are numbered are therefore equal, and the search explores them once.
- **Model errors.** A rule built with `rule_try` can report a situation the
protocol should never reach through `error_if`. The search stops and prints
a trace, where a `panic!` would abort without one.
- **Unknowns.** A rule can return an `Unknown` for a case the model does not
cover yet: the state is reachable, but what happens next is not modelled. The
state does not count as a deadlock, so a model can grow one case at a time,
and the search stats count the unknowns it hit.
- **Liveness.** `LivelockFreedom` reports cycles among transient states, in
which an actor never returns to a stable state.
- **Refinement.** `TransitionSysSimulation` checks that every step of one
system has a matching step in a reference system.
- **Reports.** The `report` module prints each step of a counterexample as a
line diff of the state's `Display` output. `main_report` turns a search
result into an exit code.
## Choosing a search
Start with `Bfs`. It holds every visited state in memory, never confuses two
distinct states, and records the parent of each state, so traces are always
complete.
Switch to `BfsHashing` when the visited states no longer fit in memory. It
keeps about 16 bytes per state. Two distinct states with the same hash count as
one, so the search can miss states; with 64-bit hashes this is unlikely below
about 10⁹ states. On an error it rebuilds the trace by replaying the model from
the initial states. If the replay cannot reproduce the recorded path, the report
says so. `BfsHashing::with_verbose(false)` skips the replay and reports only
the hash trace.
## Example: MSI cache coherence
[`examples/msi_directory.rs`](examples/msi_directory.rs) models the MSI
directory protocol from Sorin, Hill and Wood, *A Primer on Memory Consistency
and Cache Coherence* (2011), with three processors. It uses symmetric channels,
model errors and livelock checking, and verifies 15,500 states:
```sh
cargo run --release --example msi_directory # BfsHashing
cargo run --release --example msi_directory -- --exact # Bfs
```
## Related projects
- [Murphi](https://en.wikipedia.org/wiki/Murphi) is the explicit-state model
checker whose guarded-rule style `vers3` follows.
- [VerC3](https://github.com/icsa-caps/verc3) is the C++ library that `vers3`
is ported from.
- [stateright](https://github.com/stateright/stateright) checks actor-based
implementations of distributed systems and can run them on a real network,
with an interactive explorer and linearizability testing. `vers3` is smaller
and lower-level: it checks abstract protocol models and leaves the tooling
around it to you.
## License
Licensed under the [Apache License, Version 2.0](LICENSE).