vers3 0.2.0

Explicit-state model checking library
Documentation
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2026, Marco Elver <me@marcoelver.com>

//! Livelock freedom property.

use crate::ts::{Property, State};
use crate::util::find_cycle;
use std::collections::HashSet;
use std::fmt;
use std::hash::Hash;

/// Livelock freedom liveness property.
///
/// If a node issues a request, that request must eventually be satisfied. Records the directed
/// graph of transient-state transitions seen during the search, aggregated over all nodes. A cycle
/// in that graph means a node can revisit the same transient state indefinitely without ever
/// reaching a stable state.
///
/// Aggregating over all nodes is a conservative over-approximation: a cycle assembled from edges
/// only different nodes can take is still reported. For symmetric protocols (where every node can
/// take every edge) this makes no difference; in general it errs towards false positives rather
/// than missed livelocks.
///
/// **Reference:** K. McMillan, J. Schwalbe, "Formal verification of the Gigamax cache consistency
/// protocol", ISSM 1991.
pub struct LivelockFreedom<S, NodeState> {
    name: String,
    extract_nodes: Box<dyn Fn(&S) -> Vec<NodeState>>,
    is_transient: Box<dyn Fn(&NodeState) -> bool>,
    // Directed graph of transient-state transitions across all nodes, stored
    // as full values so a detected cycle can be formatted for the violation
    // message.
    edges: HashSet<(NodeState, NodeState)>,
}

impl<S, NodeState> LivelockFreedom<S, NodeState>
where
    S: State,
    NodeState: Hash + Eq + Clone,
{
    /// `extract_nodes` returns the per-node states of `s`, in a stable order:
    /// entry `i` of successive calls must refer to the same node.
    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> {
        // `find_cycle` needs `Copy` nodes; shared references are Copy, so the
        // graph can be searched over the stored values directly.
        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() {
        // Node 0 cycles: PendingA → PendingB → PendingA (livelock).
        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() {
        // Node 0 only ever goes PendingA → PendingB; node 1 only PendingB → PendingA.
        // No single node cycles, but the aggregated transient-state graph does.
        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() {
        // Node 0 goes PendingA → Stable and stays there.
        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()
        );
    }
}