use crate::ts::{Property, State};
use crate::util::find_cycle;
use std::collections::HashSet;
use std::fmt;
use std::hash::Hash;
pub struct LivelockFreedom<S, NodeState> {
name: String,
extract_nodes: Box<dyn Fn(&S) -> Vec<NodeState>>,
is_transient: Box<dyn Fn(&NodeState) -> bool>,
edges: HashSet<(NodeState, NodeState)>,
}
impl<S, NodeState> LivelockFreedom<S, NodeState>
where
S: State,
NodeState: Hash + Eq + Clone,
{
pub fn new(
name: impl Into<String>,
extract_nodes: impl Fn(&S) -> Vec<NodeState> + 'static,
is_transient: impl Fn(&NodeState) -> bool + 'static,
) -> Self {
Self {
name: name.into(),
extract_nodes: Box::new(extract_nodes),
is_transient: Box::new(is_transient),
edges: HashSet::new(),
}
}
}
impl<S, NodeState> Property<S> for LivelockFreedom<S, NodeState>
where
S: State,
NodeState: Hash + Eq + fmt::Display + Clone + 'static,
{
fn name(&self) -> &str {
&self.name
}
fn on_successors(
&mut self,
state: &S,
successors: &[(S, String)],
_unknowns: &[crate::ts::Unknown],
) {
let from_nodes = (self.extract_nodes)(state);
for (next_state, _rule) in successors {
let to_nodes = (self.extract_nodes)(next_state);
for (from_ns, to_ns) in from_nodes.iter().zip(to_nodes.iter()) {
if (self.is_transient)(from_ns) && (self.is_transient)(to_ns) && from_ns != to_ns {
self.edges.insert((from_ns.clone(), to_ns.clone()));
}
}
}
}
fn is_satisfied(&self) -> Option<String> {
let edges: HashSet<(&NodeState, &NodeState)> =
self.edges.iter().map(|(a, b)| (a, b)).collect();
let cycle = find_cycle(&edges)?;
let states: Vec<String> = cycle.iter().map(|s| s.to_string()).collect();
Some(format!("transient-state cycle: {}", states.join(" → ")))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::search::Bfs;
use crate::ts::{TransitionSystem, rule};
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
enum NodeSt {
Stable,
PendingA,
PendingB,
}
impl fmt::Display for NodeSt {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
#[derive(Clone, Hash, PartialEq, Eq)]
struct TwoNode(NodeSt, NodeSt);
impl fmt::Display for TwoNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "({:?},{:?})", self.0, self.1)
}
}
fn extract(s: &TwoNode) -> Vec<NodeSt> {
vec![s.0.clone(), s.1.clone()]
}
fn is_transient(ns: &NodeSt) -> bool {
!matches!(ns, NodeSt::Stable)
}
fn livelock_prop() -> LivelockFreedom<TwoNode, NodeSt> {
LivelockFreedom::new("livelock_free", extract, is_transient)
}
#[test]
fn detects_livelock_cycle() {
let mut ts: TransitionSystem<TwoNode> =
TransitionSystem::new().with_deadlock_detection(false);
ts.add_rule(rule(
"a_to_b",
|s: &TwoNode| s.0 == NodeSt::PendingA,
|s: &mut TwoNode| {
s.0 = NodeSt::PendingB;
true
},
));
ts.add_rule(rule(
"b_to_a",
|s: &TwoNode| s.0 == NodeSt::PendingB,
|s: &mut TwoNode| {
s.0 = NodeSt::PendingA;
true
},
));
ts.add_property(livelock_prop());
let result = Bfs::new().run(vec![TwoNode(NodeSt::PendingA, NodeSt::Stable)], ts);
assert!(result.is_err());
}
#[test]
fn detects_cross_node_cycle() {
let mut ts: TransitionSystem<TwoNode> =
TransitionSystem::new().with_deadlock_detection(false);
ts.add_rule(rule(
"n0_a_to_b",
|s: &TwoNode| s.0 == NodeSt::PendingA,
|s: &mut TwoNode| {
s.0 = NodeSt::PendingB;
true
},
));
ts.add_rule(rule(
"n1_b_to_a",
|s: &TwoNode| s.1 == NodeSt::PendingB,
|s: &mut TwoNode| {
s.1 = NodeSt::PendingA;
true
},
));
ts.add_property(livelock_prop());
let result = Bfs::new().run(vec![TwoNode(NodeSt::PendingA, NodeSt::PendingB)], ts);
assert!(result.is_err());
}
#[test]
fn no_livelock_when_stable() {
let mut ts: TransitionSystem<TwoNode> =
TransitionSystem::new().with_deadlock_detection(false);
ts.add_rule(rule(
"resolve",
|s: &TwoNode| s.0 == NodeSt::PendingA,
|s: &mut TwoNode| {
s.0 = NodeSt::Stable;
true
},
));
ts.add_property(livelock_prop());
assert!(
Bfs::new()
.run(vec![TwoNode(NodeSt::PendingA, NodeSt::Stable)], ts)
.is_ok()
);
}
}