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;
pub type Trace<S> = Vec<(S, String)>;
pub type HashTrace = Vec<StateHash>;
pub enum TraceEvidence<S> {
None,
States(Trace<S>),
PartialStates(Trace<S>),
Hashes(HashTrace),
}
impl<S> TraceEvidence<S> {
pub fn states(&self) -> &[(S, String)] {
match self {
Self::States(t) | Self::PartialStates(t) => t,
Self::None | Self::Hashes(_) => &[],
}
}
}
pub struct Counterexample<S: State> {
pub error: CheckerError,
pub evidence: TraceEvidence<S>,
pub states_visited: usize,
pub states_queued: usize,
}
impl<S: State> Counterexample<S> {
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,
)
}
}
#[derive(Debug, Clone)]
pub struct Stats<S: State> {
pub states_visited: usize,
pub states_queued: usize,
pub duration: std::time::Duration,
pub accept_states: Vec<S>,
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()
)
}
}
pub struct Bfs<S: State> {
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> {
pub fn new() -> Self {
Self {
visited: HashMap::with_hasher(ahash::RandomState::new()),
accept_fn: None,
monitor: None,
}
}
pub fn with_accept(mut self, f: impl Fn(&S) -> bool + 'static) -> Self {
self.accept_fn = Some(Box::new(f));
self
}
pub fn with_monitor(mut self, f: impl FnMut(usize, usize, &[S]) -> bool + 'static) -> Self {
self.monitor = Some(Box::new(f));
self
}
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() {
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(¤t_state)
{
accept_states.push((*current_state).clone());
}
match ts.step(¤t_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(¤t_state), rule_name)));
}
}
}
Err(e) => {
let states_queued = queue.len() + 1;
let trace = self.build_trace(¤t_state);
return Err(Counterexample {
error: e,
evidence: TraceEvidence::States(trace),
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,
})
}
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())); path.reverse();
path
}
}
impl<S: State> Default for Bfs<S> {
fn default() -> Self {
Self::new()
}
}
pub type StateMap<S> = std::collections::HashMap<StateHash, S, ahash::RandomState>;
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> {
pub fn new() -> Self {
Self {
visited: StateMap::with_hasher(ahash::RandomState::new()),
initial: Vec::new(),
accept_fn: None,
monitor: None,
verbose: true,
}
}
pub fn with_accept(mut self, f: impl Fn(&S) -> bool + 'static) -> Self {
self.accept_fn = Some(Box::new(f));
self
}
pub fn with_monitor(mut self, f: impl FnMut(usize, usize, &[S]) -> bool + 'static) -> Self {
self.monitor = Some(Box::new(f));
self
}
pub fn with_verbose(mut self, enabled: bool) -> Self {
self.verbose = enabled;
self
}
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(¤t_state));
if let Some(ref af) = self.accept_fn
&& af(¤t_state)
{
accept_states.push(current_state.clone());
}
match ts.step(¤t_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,
})
}
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()
}
}
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, }
}
path
}
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 {
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(¤t) {
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, }
}
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)
}
}
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)); 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(); 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); 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); assert!(cex.evidence.states().is_empty());
assert_eq!(cex.states_visited, 2);
assert_eq!(cex.states_queued, 1);
}
#[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() {
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() {
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);
}
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);
}
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
struct NumA(i32); #[derive(Clone, Hash, PartialEq, Eq, Debug)]
struct NumB(i32);
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)
} }
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() {
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() {
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); }
#[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);
}
}