knotrel-core 1.3.0

Exact in-memory connectivity for undirected graphs.
Documentation
//! Exact general-graph connectivity using one Euler-tour spanning forest.
use crate::{GraphError, NodeId, forest::Forest, index::remove_incidence};
use rustc_hash::FxHashMap;
use std::collections::{BTreeSet, hash_map::Entry};

/// Cumulative replacement-search work, from [`ForestGraph::stats`].
///
/// A stable interface of the experimental ETT engine
/// ([`crate::EngineConfig::EulerTour`]). The struct is exhaustive: its four
/// public fields are frozen for 1.x, and a new field requires a major release.
///
/// # Guaranteed
///
/// - Each field counts the event its documentation names, in units of events.
/// - Every counter is `0` on a new graph ([`ForestGraph::new`], `Default`) and
///   after [`ForestGraph::reset_stats`].
/// - Between resets, counters only grow, and each saturates at `u64::MAX`
///   instead of wrapping.
/// - Queries ([`ForestGraph::connected`], [`ForestGraph::node_count`],
///   [`ForestGraph::edge_count`], [`ForestGraph::stats`]) never change them.
/// - `replacements <= tree_cuts` (at most one replacement per removed
///   spanning edge), `replacements <= candidate_edges` (a replacement is a
///   tested entry) and `replacements <= scanned_vertices` (it is found while
///   scanning a vertex).
///
/// # Implementation-dependent
///
/// The exact values for a given operation sequence: which edges belong to the
/// spanning forest, which side is scanned, the order in which vertices and
/// entries are examined and where the search stops depend on the
/// implementation and may change in any release. Do not compare values across
/// versions.
///
/// # Examples
///
/// ```
/// use knotrel_core::{ForestGraph, ForestStats};
///
/// let mut graph = ForestGraph::new();
/// graph.link(1, 2)?;
/// graph.link(2, 3)?;
/// graph.link(3, 1)?;
/// graph.cut(1, 2)?;
/// let stats = graph.stats();
/// assert!(stats.replacements <= stats.tree_cuts);
/// assert!(stats.replacements <= stats.candidate_edges);
/// graph.reset_stats();
/// assert_eq!(graph.stats(), ForestStats::default());
/// # Ok::<(), knotrel_core::GraphError>(())
/// ```
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct ForestStats {
    /// Deleted edges that belonged to the maintained spanning forest.
    pub tree_cuts: u64,
    /// Candidate-bearing vertices yielded on the smaller side after tree cuts.
    /// Pruned empty regions and unvisited vertices after success are excluded.
    pub scanned_vertices: u64,
    /// Non-tree adjacency entries tested for a crossing replacement.
    pub candidate_edges: u64,
    /// Successful promotions of non-tree edges into the forest.
    pub replacements: u64,
}

/// Exact connectivity with deterministic Euler-tour trees.
///
/// **Stable interface, experimental engine.** This type, its methods and its
/// trait implementations are stable for 1.x: they are removed or changed
/// incompatibly only after a deprecation and in a major release. The
/// experimental qualification covers performance, maturity and usage
/// recommendation only: the cost bounds below describe the current
/// implementation and are not a compatibility promise
/// ([compatibility policy](https://github.com/knotrel/knotrel/blob/main/docs/compatibility.md#22-stable-interface-experimental-engine)).
///
/// Maintains a spanning forest: each graph component has exactly one tree.
/// Non-tree edges are stored at both endpoints. Removing a forest edge scans
/// non-tree edges incident to its smaller side; a crossing edge reconnects the
/// trees, or exhaustion proves a real split. This is not HDT: repeated scans have
/// no polylogarithmic amortized bound. The default [`crate::Graph`] is unchanged.
///
/// AVL root queries cost O(log V) algorithmically, with expected O(1) ID hash map translation. Link costs
/// O(log V + log E) amortized including arena growth. A tree cut costs (amortized for free-list growth)
/// O(log V + log E + min(s, (k+1) log V) + c log V), where s is the
/// smaller side size, k the yielded candidate-bearing vertices, and c the
/// examined non-tree incidences. Empty candidate sets require no enumeration. Non-tree cuts cost O(log V + log E).
/// A single token-arena or free-list growth can add O(V) time. Logical storage is O(V + E); allocated
/// arenas retain O(V) high-water capacity, removed tree-edge slots are reused and an emptied
/// non-tree incidence set frees its storage.
/// Queries allocate no scratch, cache no answers and use no internal locks.
#[derive(Debug, Default)]
pub struct ForestGraph {
    // Read by `ConnectivityGraph`'s bulk listing.
    pub(crate) ids: FxHashMap<NodeId, usize>,
    pub(crate) non_tree: Vec<BTreeSet<usize>>,
    pub(crate) edges: FxHashMap<(usize, usize), Option<(usize, usize)>>,
    forest: Forest,
    stats: ForestStats,
}
impl ForestGraph {
    /// Reports whether `node` is registered; expected O(1) ID-map lookup.
    pub(crate) fn contains_node(&self, node: NodeId) -> bool {
        self.ids.contains_key(&node)
    }

    pub(crate) fn contains_edge(&self, source: NodeId, target: NodeId) -> bool {
        let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
            return false;
        };
        self.edges.contains_key(&(a.min(b), a.max(b)))
    }

    /// Creates an empty graph in O(1) time.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers an isolated vertex; returns false for an existing ID.
    ///
    /// O(1) amortized; arena/vector growth can take O(V) in one call.
    pub fn add_node(&mut self, node: NodeId) -> bool {
        self.index_or_insert(node).1
    }

    /// Returns `node`'s dense index and whether this call registered it.
    ///
    /// One ID-map probe through the entry API. Expected O(1), amortized for
    /// arena growth.
    fn index_or_insert(&mut self, node: NodeId) -> (usize, bool) {
        match self.ids.entry(node) {
            Entry::Occupied(entry) => (*entry.get(), false),
            Entry::Vacant(entry) => {
                let index = self.non_tree.len();
                self.non_tree.push(BTreeSet::new());
                self.forest.add_vertex();
                entry.insert(index);
                (index, true)
            }
        }
    }
    /// Inserts a simple undirected edge, registering absent endpoints.
    ///
    /// Returns false for an existing edge, including reversed endpoints.
    /// # Errors
    /// Rejects self-loops before registering either endpoint.
    pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        GraphError::check_distinct(source, target)?;
        let (a, _) = self.index_or_insert(source);
        let (b, _) = self.index_or_insert(target);
        let Entry::Vacant(slot) = self.edges.entry((a.min(b), a.max(b))) else {
            return Ok(false);
        };
        let arcs = if self.forest.connected(a, b) {
            self.non_tree[a].insert(b);
            self.non_tree[b].insert(a);
            self.forest.set_candidate(a, true);
            self.forest.set_candidate(b, true);
            None
        } else {
            Some(self.forest.link(a, b))
        };
        slot.insert(arcs);
        Ok(true)
    }
    /// Removes an edge while retaining both vertices; absent edges return false.
    ///
    /// Tree cuts synchronously complete replacement search before returning.
    /// # Errors
    /// Rejects self-loops without changing graph state.
    pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        GraphError::check_distinct(source, target)?;
        let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
            return Ok(false);
        };
        let key = (a.min(b), a.max(b));
        let Some(arcs) = self.edges.remove(&key) else {
            return Ok(false);
        };
        if let Some(arcs) = arcs {
            self.forest.cut(arcs);
            self.stats.tree_cuts = self.stats.tree_cuts.saturating_add(1);
            let mut replacement = None;
            let mut candidates = self.forest.smaller_candidates(a, b);
            'search: while let Some(v) = candidates.next() {
                self.stats.scanned_vertices = self.stats.scanned_vertices.saturating_add(1);
                for &w in &self.non_tree[v] {
                    self.stats.candidate_edges = self.stats.candidate_edges.saturating_add(1);
                    if !candidates.contains_vertex(w) {
                        replacement = Some((v, w));
                        break 'search;
                    }
                }
            }
            if let Some((v, w)) = replacement {
                let v_empty = remove_incidence(&mut self.non_tree[v], w);
                let w_empty = remove_incidence(&mut self.non_tree[w], v);
                self.forest.set_candidate(v, !v_empty);
                self.forest.set_candidate(w, !w_empty);
                let arcs = self.forest.link(v, w);
                *self
                    .edges
                    .get_mut(&(v.min(w), v.max(w)))
                    .expect("replacement edge exists") = Some(arcs);
                self.stats.replacements = self.stats.replacements.saturating_add(1);
            }
        } else {
            let a_empty = remove_incidence(&mut self.non_tree[a], b);
            let b_empty = remove_incidence(&mut self.non_tree[b], a);
            self.forest.set_candidate(a, !a_empty);
            self.forest.set_candidate(b, !b_empty);
        }
        Ok(true)
    }
    /// Answers exact connectivity in O(log V) algorithmic tree root time, plus expected O(1) hash map lookup for node IDs, without allocation.
    ///
    /// Existing vertices connect to themselves, including isolated vertices.
    /// # Errors
    /// Reports an absent source before an absent target.
    pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        let a = *self
            .ids
            .get(&source)
            .ok_or(GraphError::UnknownNode { node: source })?;
        let b = *self
            .ids
            .get(&target)
            .ok_or(GraphError::UnknownNode { node: target })?;
        Ok(self.forest.connected(a, b))
    }
    /// Returns the number of registered vertices in O(1) time.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.ids.len()
    }
    /// Returns the number of undirected graph edges in O(1) time.
    #[must_use]
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }
    /// Returns the replacement-search counters accumulated since creation or
    /// the last [`Self::reset_stats`], in O(1) time without changing any state.
    ///
    /// [`ForestStats`] lists which properties of the values are guaranteed.
    #[must_use]
    pub fn stats(&self) -> ForestStats {
        self.stats
    }
    /// Sets every diagnostic counter to zero, preserving all graph state.
    pub fn reset_stats(&mut self) {
        self.stats = ForestStats::default();
    }
}

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

    /// Counters saturate at `u64::MAX` instead of wrapping (a guaranteed
    /// property of `ForestStats`).
    #[test]
    fn stats_counters_saturate_instead_of_wrapping() {
        let mut g = ForestGraph::new();
        for (a, b) in [(1, 2), (2, 3), (3, 1)] {
            g.link(a, b).unwrap();
        }
        g.stats = super::ForestStats {
            tree_cuts: u64::MAX,
            scanned_vertices: u64::MAX,
            candidate_edges: u64::MAX,
            replacements: u64::MAX,
        };
        let tree_edge = [(1, 2), (2, 3), (3, 1)]
            .into_iter()
            .find(|&(a, b)| {
                let (a, b) = (g.ids[&a], g.ids[&b]);
                g.edges[&(a.min(b), a.max(b))].is_some()
            })
            .expect("a triangle has spanning edges");
        assert_eq!(g.cut(tree_edge.0, tree_edge.1), Ok(true));
        assert!(g.connected(1, 3).unwrap());
        assert_eq!(
            g.stats(),
            super::ForestStats {
                tree_cuts: u64::MAX,
                scanned_vertices: u64::MAX,
                candidate_edges: u64::MAX,
                replacements: u64::MAX,
            }
        );
    }
    #[test]
    fn general_graph_updates_preserve_avl_and_edge_classification() {
        let mut g = ForestGraph::new();
        let mut seed = 123_u64;
        for step in 0..3000 {
            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
            let a = (seed >> 32) % 50;
            let b = (seed >> 48) % 50;
            if step % 3 == 0 {
                let _ = g.cut(a, b);
            } else {
                let _ = g.link(a, b);
            }
            g.forest.validate();
            for (&(u, v), arcs) in &g.edges {
                assert!(g.forest.connected(u, v));
                assert_eq!(g.non_tree[u].contains(&v), arcs.is_none());
                assert_eq!(g.non_tree[v].contains(&u), arcs.is_none());
            }
            for (u, neighbors) in g.non_tree.iter().enumerate() {
                assert_eq!(g.forest.is_candidate(u), !neighbors.is_empty());
                for &v in neighbors {
                    assert_eq!(g.edges.get(&(u.min(v), u.max(v))), Some(&None));
                }
            }
        }
        let counts = (g.node_count(), g.edge_count());
        g.reset_stats();
        assert_eq!(g.stats(), super::ForestStats::default());
        assert_eq!(counts, (g.node_count(), g.edge_count()));
    }
}