Skip to main content

knotrel_core/
hdt.rs

1//! Deterministic level-based dynamic connectivity, following HDT (2001), §3.
2//!
3//! <https://www.cs.princeton.edu/courses/archive/fall07/cos521/handouts/poly.pdf>
4//! F_i contains tree edges at levels >= i. Exact-level incidences are indexed
5//! separately. Each component of F_i has at most U / 2^i vertices, with U the
6//! next power of two of the current vertex count. Growing U only relaxes bounds.
7
8use crate::{GraphError, NodeId, hdt_forest::Forest, index::remove_incidence};
9use rustc_hash::FxHashMap;
10use std::collections::{BTreeSet, hash_map::Entry};
11
12const LEVEL_ARCS_INLINE_CAPACITY: usize = 4;
13
14type Key = (usize, usize);
15type Arcs = (usize, usize);
16
17/// Cumulative HDT repair work, from [`HdtGraph::stats`].
18///
19/// A stable interface of the experimental HDT engine
20/// ([`crate::EngineConfig::Hdt`]). The struct is exhaustive: its six public
21/// fields are frozen for 1.x, and a new field requires a major release.
22///
23/// # Guaranteed
24///
25/// - Each field counts the event its documentation names, in units of events.
26/// - Every counter is `0` on a new graph ([`HdtGraph::new`], `Default`) and
27///   after [`HdtGraph::reset_stats`].
28/// - Between resets, counters only grow, and each saturates at `u64::MAX`
29///   instead of wrapping.
30/// - Queries ([`HdtGraph::connected`], [`HdtGraph::node_count`],
31///   [`HdtGraph::edge_count`], [`HdtGraph::stats`],
32///   [`HdtGraph::storage_stats`]) never change them.
33/// - `replacements <= tree_cuts` (at most one replacement per removed
34///   spanning edge), `replacements <= candidate_edges` (a replacement is an
35///   examined candidate) and `tree_cuts <= levels_visited` (each removed
36///   spanning edge visits at least one level).
37///
38/// # Implementation-dependent
39///
40/// The exact values for a given operation sequence: which edges belong to the
41/// spanning forest, which edges are promoted, the order in which candidates
42/// are examined and how many levels are visited depend on the implementation
43/// and may change in any release. Do not compare values across versions.
44///
45/// # Examples
46///
47/// ```
48/// use knotrel_core::{HdtGraph, HdtStats};
49///
50/// let mut graph = HdtGraph::new();
51/// graph.link(1, 2)?;
52/// graph.link(2, 3)?;
53/// graph.link(3, 1)?;
54/// graph.cut(1, 2)?;
55/// let stats = graph.stats();
56/// assert!(stats.replacements <= stats.tree_cuts);
57/// assert!(stats.replacements <= stats.candidate_edges);
58/// graph.reset_stats();
59/// assert_eq!(graph.stats(), HdtStats::default());
60/// # Ok::<(), knotrel_core::GraphError>(())
61/// ```
62#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
63pub struct HdtStats {
64    /// Removed edges that belonged to the spanning forest.
65    pub tree_cuts: u64,
66    /// Exact-level non-tree edges examined for replacement (once per visit).
67    pub candidate_edges: u64,
68    /// Successful replacements of a removed spanning edge.
69    pub replacements: u64,
70    /// Increases of a tree edge's level, each adding it to one higher forest.
71    pub tree_promotions: u64,
72    /// Increases of an internal non-tree edge's level.
73    pub non_tree_promotions: u64,
74    /// Replacement-search levels visited after tree cuts.
75    pub levels_visited: u64,
76}
77
78#[derive(Debug)]
79pub(crate) struct Edge {
80    level: usize,
81    // Empty for non-tree edges; otherwise one handle pair for each F_0..F_level.
82    arcs: tinyvec::TinyVec<[Arcs; LEVEL_ARCS_INLINE_CAPACITY]>,
83}
84
85// F_0 is dense to keep queries free of an extra translation. Higher levels
86// materialize only touched vertices. Missing vertices are implicit isolated
87// singletons with no incidences. A sparse record that becomes an isolated
88// singleton with no exact-level incidence is released: its global mapping is
89// removed and its local slot (vertex token, empty sets) waits in `free_locals`
90// for the next materialization. Upper-level records therefore track the
91// vertices currently in F_i or holding level-i incidences, not every vertex
92// ever promoted. Local handles of live records never change.
93#[derive(Debug, Default)]
94struct Level {
95    forest: Forest,
96    tree: Vec<BTreeSet<usize>>,
97    non_tree: Vec<BTreeSet<usize>>,
98    dense: bool,
99    local_ids: FxHashMap<usize, usize>,
100    global_ids: Vec<usize>,
101    free_locals: Vec<usize>,
102}
103impl Level {
104    fn local(&self, v: usize) -> Option<usize> {
105        if self.dense {
106            (v < self.tree.len()).then_some(v)
107        } else {
108            self.local_ids.get(&v).copied()
109        }
110    }
111    fn ensure(&mut self, v: usize) -> usize {
112        if let Some(local) = self.local(v) {
113            return local;
114        }
115        if let Some(local) = self.free_locals.pop() {
116            // A released slot is an unmarked singleton with empty sets.
117            self.local_ids.insert(v, local);
118            self.global_ids[local] = v;
119            return local;
120        }
121        let local = self.tree.len();
122        if self.dense {
123            assert_eq!(v, local);
124        } else {
125            self.local_ids.insert(v, local);
126            self.global_ids.push(v);
127        }
128        self.forest.add_vertex();
129        self.tree.push(BTreeSet::new());
130        self.non_tree.push(BTreeSet::new());
131        local
132    }
133    /// Releases global vertex `v`'s sparse record if it is an isolated
134    /// singleton without exact-level incidences. Such a record is
135    /// indistinguishable from an implicit missing vertex, so queries and
136    /// replacement search are unchanged. Dense F_0 records are never released.
137    /// One expected O(1) ID-map probe, plus O(log V) for the root lookup
138    /// only when both incidence sets are empty.
139    fn release_if_isolated(&mut self, v: usize) {
140        if self.dense {
141            return;
142        }
143        let Some(local) = self.local(v) else {
144            return;
145        };
146        if self.tree[local].is_empty()
147            && self.non_tree[local].is_empty()
148            && self.forest.component_size(local) == 1
149        {
150            self.local_ids.remove(&v);
151            self.global_ids[local] = usize::MAX;
152            self.free_locals.push(local);
153        }
154    }
155    fn connected(&self, a: usize, b: usize) -> bool {
156        if a == b {
157            return true;
158        }
159        match (self.local(a), self.local(b)) {
160            (Some(a), Some(b)) => self.forest.connected(a, b),
161            _ => false,
162        }
163    }
164    fn component_size(&self, v: usize) -> usize {
165        self.local(v)
166            .map_or(1, |local| self.forest.component_size(local))
167    }
168    fn marked_vertex(&self, v: usize, tree: bool) -> Option<usize> {
169        let local = self.forest.marked_vertex(self.local(v)?, tree)?;
170        Some(if self.dense {
171            local
172        } else {
173            self.global_ids[local]
174        })
175    }
176    fn first_neighbor(&self, v: usize, tree: bool) -> usize {
177        let local = self.local(v).expect("marked vertex exists");
178        let sets = if tree { &self.tree } else { &self.non_tree };
179        *sets[local].first().expect("marked incidence exists")
180    }
181    fn link(&mut self, a: usize, b: usize) -> Arcs {
182        let a = self.ensure(a);
183        let b = self.ensure(b);
184        self.forest.link(a, b)
185    }
186    fn refresh(&mut self, local: usize) {
187        self.forest.set_marks(
188            local,
189            !self.tree[local].is_empty(),
190            !self.non_tree[local].is_empty(),
191        );
192    }
193    // Sets always store global indices; only the owning vertex is translated.
194    // Creating a sparse record is charged to its first edge promotion, O(log V).
195    // Return the stable local endpoints so callers can reuse this translation.
196    fn incidence(&mut self, a: usize, b: usize, tree: bool, insert: bool) -> (usize, usize) {
197        let (local_a, local_b) = if insert {
198            (self.ensure(a), self.ensure(b))
199        } else {
200            (
201                self.local(a).expect("live endpoint"),
202                self.local(b).expect("live endpoint"),
203            )
204        };
205        let sets = if tree {
206            &mut self.tree
207        } else {
208            &mut self.non_tree
209        };
210        if insert {
211            sets[local_a].insert(b);
212            sets[local_b].insert(a);
213        } else {
214            remove_incidence(&mut sets[local_a], b);
215            remove_incidence(&mut sets[local_b], a);
216        }
217        self.refresh(local_a);
218        self.refresh(local_b);
219        // No release here: a removed non-tree incidence leaves its endpoints
220        // connected in F_i, and a tree incidence is removed before its forest
221        // cut, which `HdtGraph::cut` follows with the release check.
222        (local_a, local_b)
223    }
224}
225
226/// Exact connectivity using deterministic HDT levels and AVL tours.
227///
228/// Preserves the [`crate::Graph`] contract, including growing arbitrary `u64`
229/// vertices. This is an experimental implementation, not a production latency
230/// guarantee. Compact BFS remains the default engine.
231///
232/// **Stable interface, experimental engine.** This type, its methods and its
233/// trait implementations are stable for 1.x: they are removed or changed
234/// incompatibly only after a deprecation and in a major release. The
235/// experimental qualification covers performance, maturity and usage
236/// recommendation only: the cost bounds below describe the current
237/// implementation and are not a compatibility promise
238/// ([compatibility policy](https://github.com/knotrel/knotrel/blob/main/docs/compatibility.md#22-stable-interface-experimental-engine)).
239///
240/// Queries cost O(log V) algorithmically on the base forest, with expected O(1) hash map ID lookup, and allocate no
241/// scratch. Across a history with at most N registered vertices, edge updates
242/// have O(log² N) amortized cost; one cut may still inspect many edges. Logical
243/// storage is O(E + V log V): each level holds one spanning-forest copy of its
244/// tree edges and records only for vertices currently in that forest or holding
245/// exact-level incidences. Records that become isolated are released for reuse
246/// and emptied incidence sets free their nodes, so storage follows the live
247/// level structure rather than the history of promotions; arena and vector
248/// capacities, and released record slots, still retain their peaks (vector
249/// capacity is at most twice the peak length).
250/// Vertex insertion costs O(1) amortized for base forest, including ID indexing. Upper
251/// levels store only vertices touched by promotions; creating these records is
252/// charged to promotions. Vector reallocations can still cause linear spikes.
253/// Neither graph state nor query answers are protected by internal locks.
254#[derive(Debug, Default)]
255pub struct HdtGraph {
256    // Read by `ConnectivityGraph`'s bulk listing.
257    pub(crate) ids: FxHashMap<NodeId, usize>,
258    pub(crate) edges: FxHashMap<Key, Edge>,
259    levels: Vec<Level>,
260    stats: HdtStats,
261}
262
263impl HdtGraph {
264    /// Reports whether `node` is registered; expected O(1) ID-map lookup.
265    pub(crate) fn contains_node(&self, node: NodeId) -> bool {
266        self.ids.contains_key(&node)
267    }
268
269    pub(crate) fn contains_edge(&self, source: NodeId, target: NodeId) -> bool {
270        let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
271            return false;
272        };
273        self.edges.contains_key(&(a.min(b), a.max(b)))
274    }
275
276    /// Creates an empty graph in O(1) time.
277    #[must_use]
278    pub fn new() -> Self {
279        Self::default()
280    }
281
282    /// Registers an isolated vertex, returning false if already present.
283    ///
284    /// Registers only in the base forest. Growing the universe relaxes upper
285    /// level size bounds; implicit isolated vertices need no upper records.
286    pub fn add_node(&mut self, node: NodeId) -> bool {
287        self.index_or_insert(node).1
288    }
289
290    /// Returns `node`'s dense index and whether this call registered it.
291    ///
292    /// One ID-map probe through the entry API; registration appends the
293    /// vertex to the base level. Expected O(1), amortized for arena growth.
294    fn index_or_insert(&mut self, node: NodeId) -> (usize, bool) {
295        let index = self.ids.len();
296        match self.ids.entry(node) {
297            Entry::Occupied(entry) => (*entry.get(), false),
298            Entry::Vacant(entry) => {
299                if self.levels.is_empty() {
300                    self.levels.push(Level {
301                        dense: true,
302                        ..Default::default()
303                    });
304                }
305                self.levels[0].ensure(index);
306                entry.insert(index);
307                (index, true)
308            }
309        }
310    }
311
312    /// Inserts an edge at level zero, creating absent endpoints.
313    ///
314    /// Returns false for a duplicate, including reversed endpoints.
315    /// # Errors
316    /// Rejects self-loops before creating any vertex.
317    pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
318        GraphError::check_distinct(source, target)?;
319        let (a, _) = self.index_or_insert(source);
320        let (b, _) = self.index_or_insert(target);
321        let Entry::Vacant(slot) = self.edges.entry(Self::key(a, b)) else {
322            return Ok(false);
323        };
324        let tree = !self.levels[0].forest.connected(a, b);
325        let arcs = if tree {
326            tinyvec::tiny_vec!([Arcs; LEVEL_ARCS_INLINE_CAPACITY] => self.levels[0].forest.link(a, b))
327        } else {
328            tinyvec::TinyVec::new()
329        };
330        self.levels[0].incidence(a, b, tree, true);
331        slot.insert(Edge { level: 0, arcs });
332        Ok(true)
333    }
334
335    /// Removes an edge, retaining all vertices; absent edges return false.
336    ///
337    /// Every repair completes before returning. A single expensive cut is still
338    /// possible: the update bound is amortized over edge lifetimes and promotions.
339    /// # Errors
340    /// Rejects self-loops without changing state.
341    pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
342        GraphError::check_distinct(source, target)?;
343        let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
344            return Ok(false);
345        };
346        let Some(edge) = self.edges.remove(&Self::key(a, b)) else {
347            return Ok(false);
348        };
349        let tree = !edge.arcs.is_empty();
350        self.levels[edge.level].incidence(a, b, tree, false);
351        if tree {
352            self.stats.tree_cuts = self.stats.tree_cuts.saturating_add(1);
353            for (i, arcs) in edge.arcs.into_iter().enumerate() {
354                let level = &mut self.levels[i];
355                level.forest.cut(arcs);
356                level.release_if_isolated(a);
357                level.release_if_isolated(b);
358            }
359            self.replace(a, b, edge.level);
360        }
361        Ok(true)
362    }
363
364    /// HDT Replace: promote all exact-level tree edges of the smaller side before
365    /// visiting its non-tree edges; skip a level if the side has no candidates.
366    /// Each failed candidate moves up one level and
367    /// can be charged only O(log N) times per lifetime. Marked root-to-leaf
368    /// searches cost O(log V); no uncharged whole-component enumeration occurs.
369    /// A crossing replacement rejoins F_0..F_i, restoring every lower forest.
370    fn replace(&mut self, a: usize, b: usize, start: usize) {
371        for i in (0..=start).rev() {
372            self.stats.levels_visited = self.stats.levels_visited.saturating_add(1);
373            let forest = &self.levels[i];
374            let small = if forest.component_size(a) <= forest.component_size(b) {
375                a
376            } else {
377                b
378            };
379            // No exact-level incidence on this side means no crossing edge at
380            // this level. Skipping promotions preserves nesting and size bounds:
381            // the cut only splits trees. Higher-level replacements were already
382            // excluded. This extra lookup costs O(log V) per visited level.
383            if self.levels[i].marked_vertex(small, false).is_none() {
384                continue;
385            }
386            while let Some(v) = self.levels[i].marked_vertex(small, true) {
387                let w = self.levels[i].first_neighbor(v, true);
388                self.promote(v, w, i, true);
389            }
390            while let Some(v) = self.levels[i].marked_vertex(small, false) {
391                let w = self.levels[i].first_neighbor(v, false);
392                self.stats.candidate_edges = self.stats.candidate_edges.saturating_add(1);
393                if self.levels[i].connected(v, w) {
394                    self.promote(v, w, i, false);
395                } else {
396                    self.levels[i].incidence(v, w, false, false);
397                    self.levels[i].incidence(v, w, true, true);
398                    let mut arcs = tinyvec::TinyVec::new();
399                    for level in &mut self.levels[..=i] {
400                        arcs.push(level.link(v, w));
401                    }
402                    self.edges
403                        .get_mut(&Self::key(v, w))
404                        .expect("live replacement")
405                        .arcs = arcs;
406                    self.stats.replacements = self.stats.replacements.saturating_add(1);
407                    return;
408                }
409            }
410        }
411    }
412
413    /// Raise one edge; the smaller-side size bound ensures the next level exists.
414    /// Tree promotions precede non-tree promotions, so an internal non-tree edge
415    /// already has a path in F_(i+1). Only a tree promotion adds a new tour copy.
416    fn promote(&mut self, a: usize, b: usize, i: usize, tree: bool) {
417        debug_assert!(i + 1 < (usize::BITS - (self.ids.len() - 1).leading_zeros()) as usize + 1);
418        if i + 1 == self.levels.len() {
419            self.levels.push(Level::default());
420        }
421        self.levels[i].incidence(a, b, tree, false);
422        let (local_a, local_b) = self.levels[i + 1].incidence(a, b, tree, true);
423        let arcs = if tree {
424            // Incidence insertion already materialized and translated both endpoints.
425            Some(self.levels[i + 1].forest.link(local_a, local_b))
426        } else {
427            debug_assert!(self.levels[i + 1].connected(a, b));
428            None
429        };
430        let edge = self
431            .edges
432            .get_mut(&Self::key(a, b))
433            .expect("live promoted edge");
434        debug_assert_eq!(edge.level, i);
435        edge.level += 1;
436        if let Some(arcs) = arcs {
437            edge.arcs.push(arcs);
438            self.stats.tree_promotions = self.stats.tree_promotions.saturating_add(1);
439        } else {
440            self.stats.non_tree_promotions = self.stats.non_tree_promotions.saturating_add(1);
441        }
442    }
443
444    /// Answers exact connectivity in O(log V) algorithmic tree root time on level 0, with expected O(1) hash map ID lookup, without allocation or mutation.
445    ///
446    /// A known vertex connects to itself. Unknown source is reported first.
447    /// # Errors
448    /// Returns [`GraphError::UnknownNode`] for an unregistered endpoint.
449    pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
450        let a = *self
451            .ids
452            .get(&source)
453            .ok_or(GraphError::UnknownNode { node: source })?;
454        let b = *self
455            .ids
456            .get(&target)
457            .ok_or(GraphError::UnknownNode { node: target })?;
458        Ok(self.levels[0].forest.connected(a, b))
459    }
460
461    /// Returns the number of registered vertices in O(1).
462    #[must_use]
463    pub fn node_count(&self) -> usize {
464        self.ids.len()
465    }
466    /// Returns the number of graph edges in O(1).
467    #[must_use]
468    pub fn edge_count(&self) -> usize {
469        self.edges.len()
470    }
471    /// Returns the diagnostic counters accumulated since creation or the last
472    /// [`Self::reset_stats`], in O(1) without changing any state.
473    ///
474    /// [`HdtStats`] lists which properties of the values are guaranteed.
475    #[must_use]
476    pub fn stats(&self) -> HdtStats {
477        self.stats
478    }
479    /// Sets every diagnostic counter to zero without altering graph state.
480    pub fn reset_stats(&mut self) {
481        self.stats = HdtStats::default();
482    }
483
484    /// Collects structural storage accounting without changing graph state.
485    ///
486    /// The values are computed at the call and describe the graph at that
487    /// moment; the returned snapshot does not follow later mutations. Calling
488    /// it changes neither the graph nor [`Self::stats`]. Takes O(V log V + E)
489    /// time in the worst case and allocates the returned per-level snapshot.
490    /// Call outside measured operations. Vector capacities exclude allocator
491    /// overhead; mapping payload excludes hash table overhead and spare slots.
492    /// This is deliberately not a total heap or RSS estimate.
493    ///
494    /// [`crate::HdtStorageStats`] and [`crate::HdtLevelStorage`] list which
495    /// properties of the values are guaranteed and which are
496    /// implementation-dependent.
497    #[must_use]
498    pub fn storage_stats(&self) -> crate::HdtStorageStats {
499        let levels: Vec<_> = self
500            .levels
501            .iter()
502            .enumerate()
503            .map(|(i, level)| {
504                let mut storage = level.forest.storage();
505                storage.level = i;
506                storage.mapping_capacity_bytes = (level.global_ids.capacity()
507                    + level.free_locals.capacity())
508                    * size_of::<usize>();
509                storage.mapping_payload_bytes = level.local_ids.len() * size_of::<(usize, usize)>();
510                storage.tree_incidences = level.tree.iter().map(BTreeSet::len).sum();
511                storage.non_tree_incidences = level.non_tree.iter().map(BTreeSet::len).sum();
512                storage.adjacency_capacity_bytes = (level.tree.capacity()
513                    + level.non_tree.capacity())
514                    * size_of::<BTreeSet<usize>>();
515                storage
516            })
517            .collect();
518        let edge_arc_capacity_bytes = self
519            .edges
520            .values()
521            .map(|edge| edge.arcs.capacity() * size_of::<Arcs>())
522            .sum::<usize>();
523        let level_capacity_bytes = self.levels.capacity() * size_of::<Level>();
524        let vector_capacity_bytes = level_capacity_bytes
525            + edge_arc_capacity_bytes
526            + levels
527                .iter()
528                .map(|s| {
529                    s.token_capacity_bytes
530                        + s.vertex_index_capacity_bytes
531                        + s.free_list_capacity_bytes
532                        + s.adjacency_capacity_bytes
533                        + s.mapping_capacity_bytes
534                })
535                .sum::<usize>();
536        let ordered_payload_bytes = self.ids.len() * size_of::<(NodeId, usize)>()
537            + self.edges.len() * size_of::<(Key, Edge)>()
538            + levels
539                .iter()
540                .map(|s| {
541                    (s.tree_incidences + s.non_tree_incidences) * size_of::<usize>()
542                        + s.mapping_payload_bytes
543                })
544                .sum::<usize>();
545        crate::HdtStorageStats {
546            vertex_count: self.ids.len(),
547            edge_count: self.edges.len(),
548            available_levels: if self.ids.is_empty() {
549                0
550            } else {
551                (usize::BITS - (self.ids.len() - 1).leading_zeros()) as usize + 1
552            },
553            vector_capacity_bytes,
554            ordered_payload_bytes,
555            edge_arc_capacity_bytes,
556            level_capacity_bytes,
557            levels,
558        }
559    }
560
561    fn key(a: usize, b: usize) -> Key {
562        (a.min(b), a.max(b))
563    }
564}
565
566#[cfg(test)]
567mod tests {
568    use super::*;
569
570    /// Counters saturate at `u64::MAX` instead of wrapping (a guaranteed
571    /// property of `HdtStats`), and keep their documented relations.
572    #[test]
573    fn stats_counters_saturate_instead_of_wrapping() {
574        let mut graph = HdtGraph::new();
575        for (a, b) in [(1, 2), (2, 3), (3, 1)] {
576            graph.link(a, b).unwrap();
577        }
578        graph.stats = HdtStats {
579            tree_cuts: u64::MAX,
580            candidate_edges: u64::MAX,
581            replacements: u64::MAX,
582            tree_promotions: u64::MAX,
583            non_tree_promotions: u64::MAX,
584            levels_visited: u64::MAX,
585        };
586        // A spanning-edge cut with a replacement touches every counter that
587        // a replacement search updates.
588        let tree_edge = [(1, 2), (2, 3), (3, 1)]
589            .into_iter()
590            .find(|&(a, b)| {
591                let key = HdtGraph::key(graph.ids[&a], graph.ids[&b]);
592                !graph.edges[&key].arcs.is_empty()
593            })
594            .expect("a triangle has spanning edges");
595        assert_eq!(graph.cut(tree_edge.0, tree_edge.1), Ok(true));
596        assert!(graph.connected(1, 3).unwrap());
597        assert_eq!(graph.stats().tree_cuts, u64::MAX);
598        assert_eq!(graph.stats().candidate_edges, u64::MAX);
599        assert_eq!(graph.stats().replacements, u64::MAX);
600        assert_eq!(graph.stats().levels_visited, u64::MAX);
601    }
602
603    /// The dense base level never releases a record, even when isolated.
604    #[test]
605    fn dense_level_records_are_never_released() {
606        let mut graph = HdtGraph::new();
607        graph.link(1, 2).unwrap();
608        graph.cut(1, 2).unwrap();
609        let level = &mut graph.levels[0];
610        let slots = level.tree.len();
611        level.release_if_isolated(0);
612        assert_eq!(level.tree.len(), slots);
613        assert_eq!(level.local(0), Some(0));
614        assert!(level.free_locals.is_empty());
615    }
616
617    /// Independent closure of all edges at/above each level must match that
618    /// forest. Also verify size bounds, exact-level incidences and arc counts.
619    fn validate(graph: &HdtGraph) {
620        let n = graph.node_count();
621        let universe = n.max(1).next_power_of_two();
622        for (i, level) in graph.levels.iter().enumerate() {
623            level.forest.validate();
624            validate_records(level);
625            let mut closure = vec![vec![false; n]; n];
626            for (v, row) in closure.iter_mut().enumerate() {
627                row[v] = true;
628                assert!(level.component_size(v) <= universe >> i);
629                if let Some(local) = level.local(v) {
630                    assert_eq!(
631                        level.forest.marks(local),
632                        (
633                            !level.tree[local].is_empty(),
634                            !level.non_tree[local].is_empty()
635                        )
636                    );
637                    for (tree, adjacency) in [(true, &level.tree), (false, &level.non_tree)] {
638                        for &w in &adjacency[local] {
639                            assert!(adjacency[level.local(w).unwrap()].contains(&v));
640                            let edge = &graph.edges[&HdtGraph::key(v, w)];
641                            assert_eq!(edge.level, i);
642                            assert_eq!(!edge.arcs.is_empty(), tree);
643                        }
644                    }
645                } else {
646                    assert_eq!(level.marked_vertex(v, true), None);
647                    assert_eq!(level.marked_vertex(v, false), None);
648                }
649            }
650            for (&(a, b), edge) in &graph.edges {
651                assert!(edge.level < graph.levels.len());
652                assert_eq!(
653                    edge.arcs.len(),
654                    if edge.arcs.is_empty() {
655                        0
656                    } else {
657                        edge.level + 1
658                    }
659                );
660                if edge.level >= i {
661                    closure[a][b] = true;
662                    closure[b][a] = true;
663                }
664                if edge.level == i {
665                    let sets = if edge.arcs.is_empty() {
666                        &level.non_tree
667                    } else {
668                        &level.tree
669                    };
670                    assert!(
671                        sets[level.local(a).unwrap()].contains(&b)
672                            && sets[level.local(b).unwrap()].contains(&a)
673                    );
674                }
675            }
676            for k in 0..n {
677                for a in 0..n {
678                    for b in 0..n {
679                        closure[a][b] |= closure[a][k] && closure[k][b];
680                    }
681                }
682            }
683            for (a, row) in closure.iter().enumerate() {
684                for (b, &expected) in row.iter().enumerate() {
685                    assert_eq!(level.connected(a, b), expected, "level {i}, pair {a},{b}");
686                }
687            }
688        }
689    }
690
691    /// Sparse records: the mapping is a bijection between live records and
692    /// global IDs; every released slot is an unmarked singleton with empty
693    /// sets and no mapping; every live record is non-isolated or has an
694    /// exact-level incidence (no isolated record is retained).
695    fn validate_records(level: &Level) {
696        assert_eq!(level.tree.len(), level.non_tree.len());
697        assert_eq!(level.tree.len(), level.forest.vertex_tokens.len());
698        if level.dense {
699            assert!(level.free_locals.is_empty() && level.local_ids.is_empty());
700            return;
701        }
702        assert_eq!(level.global_ids.len(), level.tree.len());
703        assert_eq!(
704            level.local_ids.len() + level.free_locals.len(),
705            level.tree.len()
706        );
707        for (&v, &local) in &level.local_ids {
708            assert_eq!(level.global_ids[local], v);
709            assert!(
710                !level.tree[local].is_empty()
711                    || !level.non_tree[local].is_empty()
712                    || level.forest.component_size(local) > 1,
713                "retained isolated record for vertex {v}"
714            );
715        }
716        let free: BTreeSet<_> = level.free_locals.iter().copied().collect();
717        assert_eq!(free.len(), level.free_locals.len());
718        for &local in &level.free_locals {
719            assert_eq!(level.global_ids[local], usize::MAX);
720            assert!(level.tree[local].is_empty() && level.non_tree[local].is_empty());
721            assert_eq!(level.forest.component_size(local), 1);
722            assert_eq!(level.forest.marks(local), (false, false));
723        }
724    }
725
726    /// Regression for upper-level record retention: repeatedly isolating
727    /// and restoring vertices (the engine-level effect of node deactivation)
728    /// must not accumulate isolated records. Records of every sparse level
729    /// stay bounded by the vertices currently present in F_i or holding
730    /// level-i incidences, and released slots are reused. Before the fix,
731    /// records grew with the history of promoted vertices.
732    #[test]
733    fn isolating_churn_releases_and_reuses_upper_level_records() {
734        let n = 96_u64;
735        let mut seed = 7_u64;
736        let mut next = move || {
737            seed = seed
738                .wrapping_mul(6364136223846793005)
739                .wrapping_add(1442695040888963407);
740            seed >> 33
741        };
742        let mut adjacency = vec![Vec::new(); n as usize];
743        let mut graph = HdtGraph::new();
744        for v in 0..n {
745            graph.add_node(v);
746        }
747        for _ in 0..3 * n {
748            let (a, b) = (next() % n, next() % n);
749            if a != b && graph.link(a, b).unwrap() {
750                adjacency[a as usize].push(b);
751                adjacency[b as usize].push(a);
752            }
753        }
754        let mut off = vec![false; n as usize];
755        let mut slots_high_water = 0;
756        let mut released = false;
757        for round in 0..60 {
758            let picks: Vec<u64> = (0..8).map(|_| next() % n).collect();
759            for &v in &picks {
760                if !off[v as usize] {
761                    for &w in &adjacency[v as usize] {
762                        if !off[w as usize] {
763                            graph.cut(v, w).unwrap();
764                            validate(&graph);
765                        }
766                    }
767                    off[v as usize] = true;
768                }
769            }
770            for v in 0..n {
771                if off[v as usize] {
772                    off[v as usize] = false;
773                    for &w in &adjacency[v as usize] {
774                        if !off[w as usize] {
775                            graph.link(v, w).unwrap();
776                        }
777                    }
778                }
779            }
780            validate(&graph);
781            for level in &graph.levels[1..] {
782                released |= !level.free_locals.is_empty();
783            }
784            let slots: usize = graph.levels[1..].iter().map(|l| l.tree.len()).sum();
785            if round == 20 {
786                slots_high_water = slots;
787            } else if round > 20 {
788                // Slots are reused: no new slot unless live records need it.
789                let live: usize = graph.levels[1..].iter().map(|l| l.local_ids.len()).sum();
790                assert!(slots <= slots_high_water.max(live));
791                slots_high_water = slots_high_water.max(slots);
792            }
793        }
794        assert!(released, "the churn must exercise record release");
795        assert!(
796            graph.levels.len() > 2,
797            "the churn must exercise upper levels"
798        );
799    }
800
801    #[test]
802    fn promoted_tree_uses_local_handles_for_sparse_global_indices() {
803        let mut level = super::Level::default();
804        level.ensure(900);
805        level.ensure(400);
806        let (a, b) = level.incidence(400, 900, true, true);
807        let arcs = level.forest.link(a, b);
808        assert!(level.connected(400, 900));
809        assert_eq!(level.component_size(400), 2);
810        assert!(level.marked_vertex(900, true).is_some());
811        level.forest.cut(arcs);
812        assert!(!level.connected(400, 900));
813        level.incidence(400, 900, true, false);
814        assert!(level.marked_vertex(900, true).is_none());
815        assert!(level.marked_vertex(400, true).is_none());
816    }
817
818    #[test]
819    fn growing_mixed_updates_preserve_every_level_and_incidence() {
820        for initial_seed in [1_u64, 97, 1337] {
821            let mut graph = HdtGraph::new();
822            let mut seed = initial_seed;
823            for step in 0..600 {
824                seed = seed
825                    .wrapping_mul(6364136223846793005)
826                    .wrapping_add(1442695040888963407);
827                let bound = 2 + (step / 40).min(18);
828                let a = (seed >> 32) % bound;
829                let b = (seed >> 48) % bound;
830                if step % 2 == 0 {
831                    let _ = graph.cut(a, b);
832                } else {
833                    let _ = graph.link(a, b);
834                }
835                validate(&graph);
836            }
837            let ids: Vec<_> = graph.ids.keys().copied().collect();
838            for &a in &ids {
839                for &b in &ids {
840                    let _ = graph.cut(a, b);
841                    validate(&graph);
842                }
843            }
844            assert_eq!(graph.edge_count(), 0);
845        }
846    }
847
848    #[test]
849    fn empty_higher_level_search_still_finds_lower_replacement() {
850        let mut graph = HdtGraph::new();
851        for v in 0..8 {
852            graph.add_node(v);
853        }
854        for v in 0..7 {
855            graph.link(v, v + 1).unwrap();
856        }
857        graph.link(0, 2).unwrap();
858        graph.cut(2, 3).unwrap();
859        assert_eq!(graph.edges[&(0, 1)].level, 1);
860        graph.cut(0, 2).unwrap();
861        graph.link(0, 2).unwrap(); // Reinsert as a level-zero non-tree edge.
862        graph.reset_stats();
863        graph.cut(0, 1).unwrap();
864        assert_eq!(graph.stats().levels_visited, 2);
865        assert_eq!(graph.stats().replacements, 1);
866        assert_eq!(graph.stats().tree_promotions, 0);
867        assert_eq!(graph.connected(0, 1), Ok(true));
868        validate(&graph);
869    }
870
871    #[test]
872    fn promoted_tree_deletions_repair_all_lower_forests_after_growth() {
873        let mut graph = HdtGraph::new();
874        for v in 0..32 {
875            graph.add_node(v);
876        }
877        for v in 0..31 {
878            graph.link(v, v + 1).unwrap();
879        }
880        // Fixed four-vertex cliques supply internal candidates as the path's
881        // inter-block bridges split progressively smaller components.
882        for base in (0..32).step_by(4) {
883            for a in base..base + 4 {
884                for b in a + 1..base + 4 {
885                    graph.link(a, b).unwrap();
886                }
887            }
888        }
889        for v in [15, 7, 23, 3, 11, 19, 27, 1, 5, 9, 13] {
890            graph.cut(v, v + 1).unwrap();
891            validate(&graph);
892        }
893        assert!(graph.edges.values().any(|edge| edge.level >= 3));
894        for v in 32..34 {
895            graph.add_node(v);
896            validate(&graph);
897        }
898        for v in 0..33 {
899            graph.link(v, v + 1).unwrap();
900            validate(&graph);
901        }
902        // Add cycles, then delete every old tree edge including promoted ones.
903        for v in 0..32 {
904            graph.link(v, v + 2).unwrap();
905        }
906        for v in 0..33 {
907            graph.cut(v, v + 1).unwrap();
908            validate(&graph);
909        }
910        let state = (
911            graph.node_count(),
912            graph.edge_count(),
913            graph.connected(0, 32),
914        );
915        graph.reset_stats();
916        assert_eq!(graph.stats(), HdtStats::default());
917        assert_eq!(
918            state,
919            (
920                graph.node_count(),
921                graph.edge_count(),
922                graph.connected(0, 32)
923            )
924        );
925    }
926
927    #[test]
928    fn empty_graph_storage_stats() {
929        let graph = HdtGraph::new();
930        let stats = graph.storage_stats();
931        assert_eq!(stats.vertex_count, 0);
932        assert_eq!(stats.available_levels, 0);
933    }
934}