knotrel_core/dynamic.rs
1//! Exact general-graph connectivity using one Euler-tour spanning forest.
2use crate::{GraphError, NodeId, forest::Forest, index::remove_incidence};
3use rustc_hash::FxHashMap;
4use std::collections::{BTreeSet, hash_map::Entry};
5
6/// Cumulative replacement-search work, from [`ForestGraph::stats`].
7///
8/// A stable interface of the experimental ETT engine
9/// ([`crate::EngineConfig::EulerTour`]). The struct is exhaustive: its four
10/// public fields are frozen for 1.x, and a new field requires a major release.
11///
12/// # Guaranteed
13///
14/// - Each field counts the event its documentation names, in units of events.
15/// - Every counter is `0` on a new graph ([`ForestGraph::new`], `Default`) and
16/// after [`ForestGraph::reset_stats`].
17/// - Between resets, counters only grow, and each saturates at `u64::MAX`
18/// instead of wrapping.
19/// - Queries ([`ForestGraph::connected`], [`ForestGraph::node_count`],
20/// [`ForestGraph::edge_count`], [`ForestGraph::stats`]) never change them.
21/// - `replacements <= tree_cuts` (at most one replacement per removed
22/// spanning edge), `replacements <= candidate_edges` (a replacement is a
23/// tested entry) and `replacements <= scanned_vertices` (it is found while
24/// scanning a vertex).
25///
26/// # Implementation-dependent
27///
28/// The exact values for a given operation sequence: which edges belong to the
29/// spanning forest, which side is scanned, the order in which vertices and
30/// entries are examined and where the search stops depend on the
31/// implementation and may change in any release. Do not compare values across
32/// versions.
33///
34/// # Examples
35///
36/// ```
37/// use knotrel_core::{ForestGraph, ForestStats};
38///
39/// let mut graph = ForestGraph::new();
40/// graph.link(1, 2)?;
41/// graph.link(2, 3)?;
42/// graph.link(3, 1)?;
43/// graph.cut(1, 2)?;
44/// let stats = graph.stats();
45/// assert!(stats.replacements <= stats.tree_cuts);
46/// assert!(stats.replacements <= stats.candidate_edges);
47/// graph.reset_stats();
48/// assert_eq!(graph.stats(), ForestStats::default());
49/// # Ok::<(), knotrel_core::GraphError>(())
50/// ```
51#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
52pub struct ForestStats {
53 /// Deleted edges that belonged to the maintained spanning forest.
54 pub tree_cuts: u64,
55 /// Candidate-bearing vertices yielded on the smaller side after tree cuts.
56 /// Pruned empty regions and unvisited vertices after success are excluded.
57 pub scanned_vertices: u64,
58 /// Non-tree adjacency entries tested for a crossing replacement.
59 pub candidate_edges: u64,
60 /// Successful promotions of non-tree edges into the forest.
61 pub replacements: u64,
62}
63
64/// Exact connectivity with deterministic Euler-tour trees.
65///
66/// **Stable interface, experimental engine.** This type, its methods and its
67/// trait implementations are stable for 1.x: they are removed or changed
68/// incompatibly only after a deprecation and in a major release. The
69/// experimental qualification covers performance, maturity and usage
70/// recommendation only: the cost bounds below describe the current
71/// implementation and are not a compatibility promise
72/// ([compatibility policy](https://github.com/knotrel/knotrel/blob/main/docs/compatibility.md#22-stable-interface-experimental-engine)).
73///
74/// Maintains a spanning forest: each graph component has exactly one tree.
75/// Non-tree edges are stored at both endpoints. Removing a forest edge scans
76/// non-tree edges incident to its smaller side; a crossing edge reconnects the
77/// trees, or exhaustion proves a real split. This is not HDT: repeated scans have
78/// no polylogarithmic amortized bound. The default [`crate::Graph`] is unchanged.
79///
80/// AVL root queries cost O(log V) algorithmically, with expected O(1) ID hash map translation. Link costs
81/// O(log V + log E) amortized including arena growth. A tree cut costs (amortized for free-list growth)
82/// O(log V + log E + min(s, (k+1) log V) + c log V), where s is the
83/// smaller side size, k the yielded candidate-bearing vertices, and c the
84/// examined non-tree incidences. Empty candidate sets require no enumeration. Non-tree cuts cost O(log V + log E).
85/// A single token-arena or free-list growth can add O(V) time. Logical storage is O(V + E); allocated
86/// arenas retain O(V) high-water capacity, removed tree-edge slots are reused and an emptied
87/// non-tree incidence set frees its storage.
88/// Queries allocate no scratch, cache no answers and use no internal locks.
89#[derive(Debug, Default)]
90pub struct ForestGraph {
91 // Read by `ConnectivityGraph`'s bulk listing.
92 pub(crate) ids: FxHashMap<NodeId, usize>,
93 pub(crate) non_tree: Vec<BTreeSet<usize>>,
94 pub(crate) edges: FxHashMap<(usize, usize), Option<(usize, usize)>>,
95 forest: Forest,
96 stats: ForestStats,
97}
98impl ForestGraph {
99 /// Reports whether `node` is registered; expected O(1) ID-map lookup.
100 pub(crate) fn contains_node(&self, node: NodeId) -> bool {
101 self.ids.contains_key(&node)
102 }
103
104 pub(crate) fn contains_edge(&self, source: NodeId, target: NodeId) -> bool {
105 let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
106 return false;
107 };
108 self.edges.contains_key(&(a.min(b), a.max(b)))
109 }
110
111 /// Creates an empty graph in O(1) time.
112 #[must_use]
113 pub fn new() -> Self {
114 Self::default()
115 }
116
117 /// Registers an isolated vertex; returns false for an existing ID.
118 ///
119 /// O(1) amortized; arena/vector growth can take O(V) in one call.
120 pub fn add_node(&mut self, node: NodeId) -> bool {
121 self.index_or_insert(node).1
122 }
123
124 /// Returns `node`'s dense index and whether this call registered it.
125 ///
126 /// One ID-map probe through the entry API. Expected O(1), amortized for
127 /// arena growth.
128 fn index_or_insert(&mut self, node: NodeId) -> (usize, bool) {
129 match self.ids.entry(node) {
130 Entry::Occupied(entry) => (*entry.get(), false),
131 Entry::Vacant(entry) => {
132 let index = self.non_tree.len();
133 self.non_tree.push(BTreeSet::new());
134 self.forest.add_vertex();
135 entry.insert(index);
136 (index, true)
137 }
138 }
139 }
140 /// Inserts a simple undirected edge, registering absent endpoints.
141 ///
142 /// Returns false for an existing edge, including reversed endpoints.
143 /// # Errors
144 /// Rejects self-loops before registering either endpoint.
145 pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
146 GraphError::check_distinct(source, target)?;
147 let (a, _) = self.index_or_insert(source);
148 let (b, _) = self.index_or_insert(target);
149 let Entry::Vacant(slot) = self.edges.entry((a.min(b), a.max(b))) else {
150 return Ok(false);
151 };
152 let arcs = if self.forest.connected(a, b) {
153 self.non_tree[a].insert(b);
154 self.non_tree[b].insert(a);
155 self.forest.set_candidate(a, true);
156 self.forest.set_candidate(b, true);
157 None
158 } else {
159 Some(self.forest.link(a, b))
160 };
161 slot.insert(arcs);
162 Ok(true)
163 }
164 /// Removes an edge while retaining both vertices; absent edges return false.
165 ///
166 /// Tree cuts synchronously complete replacement search before returning.
167 /// # Errors
168 /// Rejects self-loops without changing graph state.
169 pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
170 GraphError::check_distinct(source, target)?;
171 let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
172 return Ok(false);
173 };
174 let key = (a.min(b), a.max(b));
175 let Some(arcs) = self.edges.remove(&key) else {
176 return Ok(false);
177 };
178 if let Some(arcs) = arcs {
179 self.forest.cut(arcs);
180 self.stats.tree_cuts = self.stats.tree_cuts.saturating_add(1);
181 let mut replacement = None;
182 let mut candidates = self.forest.smaller_candidates(a, b);
183 'search: while let Some(v) = candidates.next() {
184 self.stats.scanned_vertices = self.stats.scanned_vertices.saturating_add(1);
185 for &w in &self.non_tree[v] {
186 self.stats.candidate_edges = self.stats.candidate_edges.saturating_add(1);
187 if !candidates.contains_vertex(w) {
188 replacement = Some((v, w));
189 break 'search;
190 }
191 }
192 }
193 if let Some((v, w)) = replacement {
194 let v_empty = remove_incidence(&mut self.non_tree[v], w);
195 let w_empty = remove_incidence(&mut self.non_tree[w], v);
196 self.forest.set_candidate(v, !v_empty);
197 self.forest.set_candidate(w, !w_empty);
198 let arcs = self.forest.link(v, w);
199 *self
200 .edges
201 .get_mut(&(v.min(w), v.max(w)))
202 .expect("replacement edge exists") = Some(arcs);
203 self.stats.replacements = self.stats.replacements.saturating_add(1);
204 }
205 } else {
206 let a_empty = remove_incidence(&mut self.non_tree[a], b);
207 let b_empty = remove_incidence(&mut self.non_tree[b], a);
208 self.forest.set_candidate(a, !a_empty);
209 self.forest.set_candidate(b, !b_empty);
210 }
211 Ok(true)
212 }
213 /// Answers exact connectivity in O(log V) algorithmic tree root time, plus expected O(1) hash map lookup for node IDs, without allocation.
214 ///
215 /// Existing vertices connect to themselves, including isolated vertices.
216 /// # Errors
217 /// Reports an absent source before an absent target.
218 pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
219 let a = *self
220 .ids
221 .get(&source)
222 .ok_or(GraphError::UnknownNode { node: source })?;
223 let b = *self
224 .ids
225 .get(&target)
226 .ok_or(GraphError::UnknownNode { node: target })?;
227 Ok(self.forest.connected(a, b))
228 }
229 /// Returns the number of registered vertices in O(1) time.
230 #[must_use]
231 pub fn node_count(&self) -> usize {
232 self.ids.len()
233 }
234 /// Returns the number of undirected graph edges in O(1) time.
235 #[must_use]
236 pub fn edge_count(&self) -> usize {
237 self.edges.len()
238 }
239 /// Returns the replacement-search counters accumulated since creation or
240 /// the last [`Self::reset_stats`], in O(1) time without changing any state.
241 ///
242 /// [`ForestStats`] lists which properties of the values are guaranteed.
243 #[must_use]
244 pub fn stats(&self) -> ForestStats {
245 self.stats
246 }
247 /// Sets every diagnostic counter to zero, preserving all graph state.
248 pub fn reset_stats(&mut self) {
249 self.stats = ForestStats::default();
250 }
251}
252
253#[cfg(test)]
254mod tests {
255 use super::ForestGraph;
256
257 /// Counters saturate at `u64::MAX` instead of wrapping (a guaranteed
258 /// property of `ForestStats`).
259 #[test]
260 fn stats_counters_saturate_instead_of_wrapping() {
261 let mut g = ForestGraph::new();
262 for (a, b) in [(1, 2), (2, 3), (3, 1)] {
263 g.link(a, b).unwrap();
264 }
265 g.stats = super::ForestStats {
266 tree_cuts: u64::MAX,
267 scanned_vertices: u64::MAX,
268 candidate_edges: u64::MAX,
269 replacements: u64::MAX,
270 };
271 let tree_edge = [(1, 2), (2, 3), (3, 1)]
272 .into_iter()
273 .find(|&(a, b)| {
274 let (a, b) = (g.ids[&a], g.ids[&b]);
275 g.edges[&(a.min(b), a.max(b))].is_some()
276 })
277 .expect("a triangle has spanning edges");
278 assert_eq!(g.cut(tree_edge.0, tree_edge.1), Ok(true));
279 assert!(g.connected(1, 3).unwrap());
280 assert_eq!(
281 g.stats(),
282 super::ForestStats {
283 tree_cuts: u64::MAX,
284 scanned_vertices: u64::MAX,
285 candidate_edges: u64::MAX,
286 replacements: u64::MAX,
287 }
288 );
289 }
290 #[test]
291 fn general_graph_updates_preserve_avl_and_edge_classification() {
292 let mut g = ForestGraph::new();
293 let mut seed = 123_u64;
294 for step in 0..3000 {
295 seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
296 let a = (seed >> 32) % 50;
297 let b = (seed >> 48) % 50;
298 if step % 3 == 0 {
299 let _ = g.cut(a, b);
300 } else {
301 let _ = g.link(a, b);
302 }
303 g.forest.validate();
304 for (&(u, v), arcs) in &g.edges {
305 assert!(g.forest.connected(u, v));
306 assert_eq!(g.non_tree[u].contains(&v), arcs.is_none());
307 assert_eq!(g.non_tree[v].contains(&u), arcs.is_none());
308 }
309 for (u, neighbors) in g.non_tree.iter().enumerate() {
310 assert_eq!(g.forest.is_candidate(u), !neighbors.is_empty());
311 for &v in neighbors {
312 assert_eq!(g.edges.get(&(u.min(v), u.max(v))), Some(&None));
313 }
314 }
315 }
316 let counts = (g.node_count(), g.edge_count());
317 g.reset_stats();
318 assert_eq!(g.stats(), super::ForestStats::default());
319 assert_eq!(counts, (g.node_count(), g.edge_count()));
320 }
321}