Skip to main content

knotrel_core/
topology.rs

1//! Registered topology with node-active and edge-enabled flags (M10).
2//!
3//! [`LifecycleGraph`] separates the *registered* topology (every node and edge
4//! the application declared, with independent flags) from the *effective*
5//! graph used for connectivity. An edge is effective exactly when it is
6//! registered, enabled, and both endpoints are registered and active.
7//!
8//! # Design
9//!
10//! The facade owns two representations:
11//!
12//! - a **catalog**: for each registered node, its `active` flag and a vector
13//!   of incident registered edges sorted by neighbor ID, each carrying the
14//!   edge's `enabled` flag. The flag is stored at both endpoints and the two
15//!   copies are always updated together;
16//! - an inner **engine** ([`ConnectivityGraph`] without limits) holding every
17//!   registered node as a vertex and exactly the effective edges.
18//!
19//! **Invariants,** restored before every public method returns:
20//!
21//! 1. `v` is in `incident(u)` with flag `f` iff `u` is in `incident(v)` with
22//!    flag `f`; incident vectors are strictly sorted and never contain the
23//!    owner itself.
24//! 2. Every registered node is an engine vertex. Engine vertices that are not
25//!    registered are *retired* slots: isolated, with no incident engine edge.
26//! 3. The engine's edge set equals the effective edge set.
27//! 4. The maintained counters equal the counts they name.
28//!
29//! Each mutation validates every ordinary error before changing either
30//! representation. After validation, engine calls cannot fail (self-loops are
31//! excluded and the engine has no limits), so a method that returns `Err`
32//! made no change.
33//!
34//! # Retired engine slots
35//!
36//! The engines do not delete vertices. Removing a node cuts its effective
37//! edges, which leaves its engine vertex isolated; registering the same ID
38//! again reuses that vertex, which therefore carries no stale adjacency.
39//! A retired slot keeps no adjacency allocation (it is released on removal),
40//! only its engine ID-map entry and an empty vector header. When retired
41//! slots exceed `max(V, 1024)`, the engine is rebuilt from the catalog.
42//! A rebuild costs `O(V log V + E)` (an ID sort plus one scan of the active
43//! nodes' incidences, with `V + E_eff` sequential engine insertions); more
44//! than `max(V, 1024)` removals separate two rebuilds, so the amortized cost
45//! is `O(log V + E / V)` per removal, and engine vertices stay at most
46//! `V + max(V, 1024)`, where `V` is the registered node count. (A
47//! `max(V / 4, 1024)` threshold was evaluated for v0.6.0 and rejected: it
48//! made fresh-ID churn about 90% slower in diagnostics.)
49//!
50//! # Catalog tombstones
51//!
52//! Removing a node from the catalog hash table can leave a tombstone, which
53//! uses insert headroom without holding an entry. Under fresh-ID churn the
54//! headroom runs out while live entries stay constant, and the table would
55//! double although it is far from full (at 100,000 nodes, from 131,072 to
56//! 262,144 buckets within a few percent of churn). Before an insert that would
57//! grow the table, the catalog is instead rebuilt into a fresh table sized for
58//! its live entries when they are at most 90% of the table's full capacity
59//! (its capacity right after its last growth or rebuild): entries move, no
60//! incident vector is copied, and the tombstones are dropped. A table sized
61//! for the live entries has the same bucket count whenever they exceed half
62//! of the old capacity (the case under churn), and fewer buckets otherwise; it
63//! is never larger. In the rare case where the live entries exactly fill the
64//! new table's capacity, the pending insert then grows it, which costs a
65//! second `O(V)` pass. A rebuild costs
66//! `O(V)` and runs only after at least 10% of the full capacity has been
67//! consumed by tombstones since the last one, so its amortized cost is `O(1)`
68//! per insertion; it holds the old and the new table only while it runs, as a
69//! growth does, with the new table no larger than the old one. Otherwise the
70//! table grows as usual. (Diagnostic D2c of the v0.7.0 qualification: at
71//! 100,000 nodes this removes the growth, lowers peak and steady-state heap by
72//! about 5 MiB, and leaves construction unchanged.)
73
74use crate::{ConnectivityGraph, EngineConfig, GraphError, GraphLimits, NodeId};
75use rustc_hash::FxHashMap;
76use std::{error::Error, fmt};
77
78/// Minimum number of retired engine slots before a compaction is considered.
79const MIN_RETIRED_BEFORE_COMPACTION: usize = 1024;
80
81/// Smallest incident-vector capacity that is ever shrunk.
82const MIN_SHRINK_CAPACITY: usize = 16;
83
84/// A catalog insert that would grow the table rebuilds it instead when live
85/// entries are at most `REBUILD_LIVE_NUMERATOR / REBUILD_LIVE_DENOMINATOR` of
86/// the table's full capacity (see the module documentation).
87const REBUILD_LIVE_NUMERATOR: usize = 9;
88const REBUILD_LIVE_DENOMINATOR: usize = 10;
89
90/// One registered node for [`LifecycleGraph::try_from_topology`].
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub struct NodeSpec {
93    /// The node identifier.
94    pub node: NodeId,
95    /// Whether the node is active.
96    pub active: bool,
97}
98
99/// One registered undirected edge for [`LifecycleGraph::try_from_topology`].
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub struct EdgeSpec {
102    /// One endpoint.
103    pub source: NodeId,
104    /// The other endpoint; orientation is not significant.
105    pub target: NodeId,
106    /// Whether the edge is enabled.
107    pub enabled: bool,
108}
109
110/// Flags of one registered edge, returned by [`LifecycleGraph::edge_state`].
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112#[non_exhaustive]
113pub struct EdgeState {
114    /// The edge's own flag, independent of its endpoints.
115    pub enabled: bool,
116    /// Whether the edge participates in connectivity: enabled, with both
117    /// endpoints active.
118    pub effective: bool,
119}
120
121impl EdgeState {
122    /// Creates edge flags with the given values.
123    ///
124    /// [`LifecycleGraph::edge_state`] is the normal source of an `EdgeState`.
125    /// This constructor exists because the struct is `#[non_exhaustive]` (a
126    /// future release may add a flag), so code outside this crate cannot use a
127    /// struct literal; use it to build expected values in comparisons, for
128    /// example in a test or a reference model. The values are not validated:
129    /// `LifecycleGraph` never reports `effective` without `enabled`.
130    ///
131    /// ```
132    /// use knotrel_core::{EdgeState, EngineConfig, LifecycleGraph};
133    /// let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs)?;
134    /// graph.link(1, 2)?;
135    /// graph.set_node_active(2, false)?;
136    /// assert_eq!(graph.edge_state(1, 2), Some(EdgeState::new(true, false)));
137    /// # Ok::<(), Box<dyn std::error::Error>>(())
138    /// ```
139    #[must_use]
140    pub const fn new(enabled: bool, effective: bool) -> Self {
141        Self { enabled, effective }
142    }
143}
144
145/// Storage diagnostics of a [`LifecycleGraph`], from
146/// [`LifecycleGraph::storage_stats`].
147///
148/// Logical sizes and retained capacities are reported separately: vectors
149/// and hash maps keep capacity after removals, so capacity can exceed the
150/// logical size. Capacities count elements, not bytes, and exclude allocator
151/// overhead and the inner engine's own capacities.
152///
153/// The type, its six fields and its trait implementations are stable. It is
154/// `#[non_exhaustive]`: a minor release may add fields, but none of these is
155/// removed or changes meaning or unit in 1.x.
156///
157/// # Guaranteed
158///
159/// For a value `s` returned by `g.storage_stats()`:
160///
161/// - Every field is a count of elements (entries, vertices or slots), never
162///   bytes.
163/// - The values are computed at the call; `s` is a copy that does not follow
164///   later mutations of `g`.
165/// - `s.catalog_nodes == g.node_count()`,
166///   `s.engine_vertices == g.engine_vertex_count()`,
167///   `s.engine_vertices == s.catalog_nodes + s.retired_vertices` and
168///   `s.incident_entries == 2 * g.edge_count()` (registered edges, enabled or
169///   not, counted at both endpoints).
170/// - `s.catalog_node_capacity >= s.catalog_nodes` and
171///   `s.incident_capacity >= s.incident_entries`.
172/// - `s.engine_vertices <= 2 * s.catalog_nodes + 1024`, the bound of
173///   [`LifecycleGraph::engine_vertex_count`].
174/// - On a graph with no registered node and no removal (for example a new
175///   one), `engine_vertices`, `retired_vertices`, `catalog_nodes` and
176///   `incident_entries` are `0`.
177///
178/// # Implementation-dependent
179///
180/// The capacities (initial values, growth, what is retained after removals
181/// and catalog rebuilds), and how many retired slots exist below the bound
182/// above, that is when retired slots are compacted, depend on the
183/// implementation, the operation history and the standard library's growth
184/// policy, and may change in any release. None of the values measures heap
185/// usage or RSS.
186///
187/// # Examples
188///
189/// ```
190/// use knotrel_core::{EngineConfig, LifecycleGraph};
191///
192/// let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs)?;
193/// graph.link(1, 2)?;
194/// graph.link(2, 3)?;
195/// assert!(graph.remove_node(3));
196/// let storage = graph.storage_stats();
197/// assert_eq!(storage.catalog_nodes, graph.node_count());
198/// assert_eq!(storage.incident_entries, 2 * graph.edge_count());
199/// assert_eq!(
200///     storage.engine_vertices,
201///     storage.catalog_nodes + storage.retired_vertices
202/// );
203/// assert!(storage.incident_capacity >= storage.incident_entries);
204/// # Ok::<(), Box<dyn std::error::Error>>(())
205/// ```
206#[derive(Debug, Clone, Copy, PartialEq, Eq)]
207#[non_exhaustive]
208pub struct LifecycleStorage {
209    /// Vertices held by the inner engine, including retired slots.
210    pub engine_vertices: usize,
211    /// Retired engine slots of removed nodes not yet compacted.
212    pub retired_vertices: usize,
213    /// Registered nodes in the catalog.
214    pub catalog_nodes: usize,
215    /// Capacity of the catalog's node map (elements).
216    pub catalog_node_capacity: usize,
217    /// Incidence entries in the catalog: two per registered edge.
218    pub incident_entries: usize,
219    /// Sum of the incident vectors' capacities (elements).
220    pub incident_capacity: usize,
221}
222
223/// Errors returned by lifecycle-specific [`LifecycleGraph`] operations.
224///
225/// The enum is non-exhaustive so that later lifecycle errors can be added
226/// without breaking matches.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228#[non_exhaustive]
229pub enum LifecycleError {
230    /// A graph error shared with the plain engines: a limit, a self-loop or
231    /// an unknown node.
232    Graph(GraphError),
233    /// Both endpoints are registered but the edge between them is not.
234    UnknownEdge {
235        /// The first endpoint, as supplied.
236        source: NodeId,
237        /// The second endpoint, as supplied.
238        target: NodeId,
239    },
240    /// [`LifecycleGraph::try_from_topology`] received the same node twice
241    /// with different `active` flags.
242    ConflictingNode {
243        /// The repeated node.
244        node: NodeId,
245    },
246    /// [`LifecycleGraph::try_from_topology`] received the same unordered
247    /// edge twice with different `enabled` flags.
248    ConflictingEdge {
249        /// The first endpoint of the repeated entry, as supplied.
250        source: NodeId,
251        /// The second endpoint of the repeated entry, as supplied.
252        target: NodeId,
253    },
254    /// Lifecycle support is not available for this engine. In v0.5.0 only
255    /// [`EngineConfig::CompactBfs`] is supported; `ett` and `hdt` lifecycle
256    /// support is deferred. No graph is created and no engine is substituted.
257    UnsupportedEngine {
258        /// The requested engine.
259        engine: EngineConfig,
260    },
261}
262
263impl fmt::Display for LifecycleError {
264    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
265        match self {
266            Self::Graph(error) => error.fmt(formatter),
267            Self::UnknownEdge { source, target } => {
268                write!(formatter, "unknown edge: {source}-{target}")
269            }
270            Self::ConflictingNode { node } => {
271                write!(
272                    formatter,
273                    "node {node} is repeated with a different active flag"
274                )
275            }
276            Self::ConflictingEdge { source, target } => write!(
277                formatter,
278                "edge {source}-{target} is repeated with a different enabled flag"
279            ),
280            Self::UnsupportedEngine { engine } => write!(
281                formatter,
282                "node and edge lifecycle support is not available for engine {}; \
283                 supported engines: compact-bfs, cluster-forest",
284                engine.as_str()
285            ),
286        }
287    }
288}
289
290impl Error for LifecycleError {
291    fn source(&self) -> Option<&(dyn Error + 'static)> {
292        match self {
293            Self::Graph(error) => Some(error),
294            _ => None,
295        }
296    }
297}
298
299impl From<GraphError> for LifecycleError {
300    fn from(error: GraphError) -> Self {
301        Self::Graph(error)
302    }
303}
304
305/// One incident registered edge, stored at an endpoint.
306#[derive(Debug, Clone, Copy)]
307struct Incidence {
308    neighbor: NodeId,
309    enabled: bool,
310}
311
312/// Catalog entry of one registered node.
313#[derive(Debug, Default)]
314struct NodeRecord {
315    active: bool,
316    /// Construction-only scratch, zero between public calls: the saturating
317    /// degree count that sizes `incident` in bulk import (only a capacity
318    /// hint), then the node's engine index during
319    /// [`LifecycleGraph::build_engine`]. It occupies the record's padding, so
320    /// the record stays 32 bytes on 64-bit targets.
321    pending: u32,
322    /// Incident registered edges, strictly sorted by `neighbor`.
323    incident: Vec<Incidence>,
324}
325
326impl NodeRecord {
327    fn active() -> Self {
328        Self {
329            active: true,
330            pending: 0,
331            incident: Vec::new(),
332        }
333    }
334
335    fn position(&self, neighbor: NodeId) -> Result<usize, usize> {
336        self.incident
337            .binary_search_by_key(&neighbor, |incidence| incidence.neighbor)
338    }
339
340    /// Removes the incidence at `index`, shrinking a mostly empty vector.
341    fn remove_at(&mut self, index: usize) -> Incidence {
342        let removed = self.incident.remove(index);
343        let capacity = self.incident.capacity();
344        if capacity > MIN_SHRINK_CAPACITY && self.incident.len() * 4 < capacity {
345            self.incident.shrink_to(self.incident.len() * 2);
346        }
347        removed
348    }
349}
350
351/// A graph with reversible node activation, reversible edge enabling and
352/// permanent node removal.
353///
354/// Connectivity is answered over the **effective graph**: active nodes and
355/// the registered edges that are enabled and have two active endpoints. The
356/// plain operations [`add_node`](Self::add_node), [`link`](Self::link) and
357/// [`cut`](Self::cut) keep their [`ConnectivityGraph`] meaning on the
358/// registered topology: `add_node` never reactivates a node, `link` never
359/// re-enables an edge and `cut` removes a registered edge whether or not it is
360/// effective.
361///
362/// [`GraphLimits`] bound **registered** nodes and edges, including inactive
363/// nodes and disabled edges.
364///
365/// # Costs
366///
367/// Let `d` be the registered degree of the node concerned and `U` the cost of
368/// one effective edge update in the selected engine. Deactivation and
369/// activation cost `O(d)` plus one engine update per effective incident edge.
370/// Removal also edits every neighbor's incident vector, `O(d + sum of
371/// neighbor degrees)`, and pays an amortized share of engine compaction (see
372/// the module documentation). None of these bounds is logarithmic.
373///
374/// Memory holds the registered topology in a catalog and the effective graph
375/// in the engine, roughly twice the plain engine for an all-active graph.
376///
377/// # Failure
378///
379/// A method that returns `Err` made no change. A panic during a mutation
380/// leaves the graph unspecified; discard it.
381///
382/// # Examples
383///
384/// ```rust
385/// use knotrel_core::{EngineConfig, LifecycleGraph};
386///
387/// let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs)?;
388/// graph.link(1, 2)?;
389/// graph.link(2, 3)?;
390///
391/// // Deactivate node 2: both incident edges stop being effective.
392/// assert!(graph.set_node_active(2, false)?);
393/// assert!(!graph.connected(1, 3)?);
394///
395/// // Disable one incident edge while node 2 is inactive.
396/// assert!(graph.set_edge_enabled(2, 3, false)?);
397///
398/// // Reactivate: only the still-enabled edge returns.
399/// assert!(graph.set_node_active(2, true)?);
400/// assert!(graph.connected(1, 2)?);
401/// assert!(!graph.connected(1, 3)?);
402///
403/// // Removal is permanent; re-adding the ID creates an isolated node.
404/// assert!(graph.remove_node(2));
405/// assert!(graph.add_node(2)?);
406/// assert!(!graph.connected(1, 2)?);
407/// # Ok::<(), Box<dyn std::error::Error>>(())
408/// ```
409#[derive(Debug)]
410pub struct LifecycleGraph {
411    // `FxHashMap`, not the identity-hashed `IntMap`: with hashbrown, identity
412    // hashes of small IDs or IDs sharing their high bits collide in the 7-bit
413    // control tag and degrade probing (measured in the v0.5.0 qualification).
414    nodes: FxHashMap<NodeId, NodeRecord>,
415    engine: ConnectivityGraph,
416    /// Configured limits, as returned by [`Self::limits`].
417    limits: GraphLimits,
418    /// Limits actually enforced: the configured ones tightened by the
419    /// engine's own capacity ([`Self::bounded`]).
420    checks: GraphLimits,
421    active_nodes: usize,
422    registered_edges: usize,
423    enabled_edges: usize,
424    effective_edges: usize,
425    /// The catalog's `capacity()` right after its last growth or rebuild;
426    /// tombstones lower `capacity()` below it.
427    catalog_full_capacity: usize,
428}
429
430impl LifecycleGraph {
431    /// Reports whether lifecycle support is available for `engine`.
432    ///
433    /// [`EngineConfig::CompactBfs`] and, from 1.1,
434    /// [`EngineConfig::ClusterForest`] are supported. Lifecycle support for
435    /// the experimental `ett` and `hdt` engines is deferred; their plain
436    /// [`ConnectivityGraph`] use is unaffected.
437    #[must_use]
438    pub const fn supports_engine(engine: EngineConfig) -> bool {
439        matches!(
440            engine,
441            EngineConfig::CompactBfs | EngineConfig::ClusterForest
442        )
443    }
444
445    /// Tightens `limits` by the engine's capacity, so the engine never
446    /// rejects (or panics on) a mutation the catalog accepted.
447    ///
448    /// `cluster-forest` holds at most `max_elements()` (2²⁸) vertices and
449    /// edges. Engine vertices include retired slots, at most
450    /// `max(catalog, 1024)` of them between compactions (see
451    /// [`Self::compact_if_needed`]), so at most `2 × catalog + 1024`: the
452    /// catalog is capped at `(2²⁸ − 1024) / 2` nodes and registered edges
453    /// (an upper bound of effective edges) at 2²⁸. Other engines are
454    /// unlimited.
455    fn bounded(engine: EngineConfig, limits: GraphLimits) -> GraphLimits {
456        if engine != EngineConfig::ClusterForest {
457            return limits;
458        }
459        let capacity = crate::cluster_forest::max_elements();
460        let nodes = capacity.saturating_sub(MIN_RETIRED_BEFORE_COMPACTION) / 2;
461        let tighten = |configured: Option<usize>, cap: usize| {
462            Some(configured.map_or(cap, |limit| limit.min(cap)))
463        };
464        GraphLimits {
465            max_nodes: tighten(limits.max_nodes, nodes),
466            max_edges: tighten(limits.max_edges, capacity),
467        }
468    }
469
470    fn check_engine(engine: EngineConfig) -> Result<(), LifecycleError> {
471        if Self::supports_engine(engine) {
472            Ok(())
473        } else {
474            Err(LifecycleError::UnsupportedEngine { engine })
475        }
476    }
477
478    /// Creates an empty unlimited graph using `engine` for connectivity.
479    ///
480    /// # Errors
481    ///
482    /// [`LifecycleError::UnsupportedEngine`] unless
483    /// [`supports_engine`](Self::supports_engine) holds for `engine`.
484    pub fn new(engine: EngineConfig) -> Result<Self, LifecycleError> {
485        Self::with_limits(engine, GraphLimits::default())
486    }
487
488    /// Creates an empty graph with cardinality limits on registered topology.
489    ///
490    /// # Errors
491    ///
492    /// [`LifecycleError::UnsupportedEngine`] unless
493    /// [`supports_engine`](Self::supports_engine) holds for `engine`.
494    pub fn with_limits(engine: EngineConfig, limits: GraphLimits) -> Result<Self, LifecycleError> {
495        Self::check_engine(engine)?;
496        Ok(Self {
497            nodes: FxHashMap::default(),
498            engine: ConnectivityGraph::new(engine),
499            limits,
500            checks: Self::bounded(engine, limits),
501            active_nodes: 0,
502            registered_edges: 0,
503            enabled_edges: 0,
504            effective_edges: 0,
505            catalog_full_capacity: 0,
506        })
507    }
508
509    /// Builds a graph from complete registered topology.
510    ///
511    /// Registers `nodes` in order, then `edges` in order, creating missing
512    /// edge endpoints as active nodes. Repeated entries with identical flags
513    /// are accepted once; edges compare as unordered pairs.
514    ///
515    /// The catalog is assembled first and incident vectors are sorted once,
516    /// `O((V + E) log E)`; the engine is then built in one pass from the
517    /// catalog with exactly the effective edges, `O(V log V + E)`.
518    ///
519    /// # Errors
520    ///
521    /// [`LifecycleError::UnsupportedEngine`] first, before any entry is
522    /// examined, unless [`supports_engine`](Self::supports_engine) holds for
523    /// `engine`. Otherwise processing stops at the first failing entry, in
524    /// input order:
525    /// [`LifecycleError::ConflictingNode`] or
526    /// [`LifecycleError::ConflictingEdge`] for a repeated entry with a
527    /// different flag; [`GraphError::SelfLoop`], then
528    /// [`GraphError::NodeLimitExceeded`], then
529    /// [`GraphError::EdgeLimitExceeded`] (for a new edge) wrapped in
530    /// [`LifecycleError::Graph`].
531    pub fn try_from_topology(
532        engine: EngineConfig,
533        limits: GraphLimits,
534        nodes: &[NodeSpec],
535        edges: &[EdgeSpec],
536    ) -> Result<Self, LifecycleError> {
537        Self::check_engine(engine)?;
538        let checks = Self::bounded(engine, limits);
539        match Self::catalog_fast(checks, nodes, edges) {
540            Some((catalog, order)) => Ok(Self::finish(engine, limits, catalog, order)),
541            None => Self::catalog_exact(checks, nodes, edges)
542                .map(|(catalog, order)| Self::finish(engine, limits, catalog, order)),
543        }
544    }
545
546    /// Catalog assembly for inputs that cannot fail: returns `None`, without
547    /// side effects, whenever an error could arise (a self-loop, a conflicting
548    /// repeated node or edge, a node limit reached, or more edge entries than
549    /// the edge limit), and [`Self::catalog_exact`] then reproduces the exact
550    /// first error in input order.
551    ///
552    /// Edges are appended without a per-edge duplicate lookup: incident lists
553    /// are sorted once and adjacent repeats are dropped (a repeated edge with a
554    /// different flag returns `None`). Without a node limit each endpoint costs
555    /// two expected O(1) catalog probes (counting pass and fill pass; two more
556    /// per edge with a node limit) instead of the exact path's duplicate-map
557    /// lookup and insertion plus endpoint probes. `O(V + E log E)` time
558    /// overall, the same bound as the exact path. An input that fails is
559    /// detected here first, so error paths pay up to about twice the work.
560    fn catalog_fast(
561        limits: GraphLimits,
562        nodes: &[NodeSpec],
563        edges: &[EdgeSpec],
564    ) -> Option<(FxHashMap<NodeId, NodeRecord>, Vec<NodeId>)> {
565        if limits.max_edges.is_some_and(|limit| edges.len() > limit) {
566            return None;
567        }
568        let mut catalog: FxHashMap<NodeId, NodeRecord> = FxHashMap::default();
569        catalog.reserve(nodes.len());
570        let mut order: Vec<NodeId> = Vec::with_capacity(nodes.len());
571        for spec in nodes {
572            match catalog.entry(spec.node) {
573                std::collections::hash_map::Entry::Occupied(entry) => {
574                    if entry.get().active != spec.active {
575                        return None;
576                    }
577                }
578                std::collections::hash_map::Entry::Vacant(entry) => {
579                    if limits.max_nodes.is_some_and(|limit| order.len() >= limit) {
580                        return None;
581                    }
582                    entry.insert(NodeRecord {
583                        active: spec.active,
584                        pending: 0,
585                        incident: Vec::new(),
586                    });
587                    order.push(spec.node);
588                }
589            }
590        }
591        for spec in edges {
592            if spec.source == spec.target {
593                return None;
594            }
595            if let Some(limit) = limits.max_nodes {
596                let missing = usize::from(!catalog.contains_key(&spec.source))
597                    + usize::from(!catalog.contains_key(&spec.target));
598                if missing > limit.saturating_sub(order.len()) {
599                    return None;
600                }
601            }
602            // Count degrees first so each incident vector is allocated once:
603            // exactly sized for duplicate-free input (repeated entries are
604            // counted, so such vectors are shrunk by `finish`).
605            for endpoint in [spec.source, spec.target] {
606                let record = catalog.entry(endpoint).or_insert_with(|| {
607                    order.push(endpoint);
608                    NodeRecord::active()
609                });
610                record.pending = record.pending.saturating_add(1);
611            }
612        }
613        for record in catalog.values_mut() {
614            record.incident = Vec::with_capacity(record.pending as usize);
615            record.pending = 0;
616        }
617        for spec in edges {
618            for (endpoint, neighbor) in [(spec.source, spec.target), (spec.target, spec.source)] {
619                catalog
620                    .get_mut(&endpoint)
621                    .expect("endpoint registered by the counting pass")
622                    .incident
623                    .push(Incidence {
624                        neighbor,
625                        enabled: spec.enabled,
626                    });
627            }
628        }
629        for record in catalog.values_mut() {
630            record
631                .incident
632                .sort_unstable_by_key(|incidence| incidence.neighbor);
633            let mut conflict = false;
634            record.incident.dedup_by(|later, kept| {
635                let repeat = later.neighbor == kept.neighbor;
636                conflict |= repeat && later.enabled != kept.enabled;
637                repeat
638            });
639            if conflict {
640                return None;
641            }
642        }
643        Some((catalog, order))
644    }
645
646    /// Exact catalog assembly: processes entries in input order and stops at
647    /// the first failing one (see [`Self::try_from_topology`]). Incident lists
648    /// are sorted here. `O((V + E) log E)` time.
649    fn catalog_exact(
650        limits: GraphLimits,
651        nodes: &[NodeSpec],
652        edges: &[EdgeSpec],
653    ) -> Result<(FxHashMap<NodeId, NodeRecord>, Vec<NodeId>), LifecycleError> {
654        let mut catalog: FxHashMap<NodeId, NodeRecord> = FxHashMap::default();
655        catalog.reserve(nodes.len());
656        let mut order: Vec<NodeId> = Vec::with_capacity(nodes.len());
657        let node_limit = limits.max_nodes;
658        for spec in nodes {
659            if let Some(record) = catalog.get(&spec.node) {
660                if record.active != spec.active {
661                    return Err(LifecycleError::ConflictingNode { node: spec.node });
662                }
663                continue;
664            }
665            if let Some(limit) = node_limit
666                && order.len() >= limit
667            {
668                return Err(GraphError::NodeLimitExceeded { limit }.into());
669            }
670            catalog.insert(
671                spec.node,
672                NodeRecord {
673                    active: spec.active,
674                    pending: 0,
675                    incident: Vec::new(),
676                },
677            );
678            order.push(spec.node);
679        }
680
681        let mut seen: FxHashMap<(NodeId, NodeId), bool> = FxHashMap::default();
682        seen.reserve(edges.len());
683        for spec in edges {
684            GraphError::check_distinct(spec.source, spec.target)?;
685            let missing = usize::from(!catalog.contains_key(&spec.source))
686                + usize::from(!catalog.contains_key(&spec.target));
687            if let Some(limit) = node_limit
688                && missing > limit.saturating_sub(order.len())
689            {
690                return Err(GraphError::NodeLimitExceeded { limit }.into());
691            }
692            let key = (spec.source.min(spec.target), spec.source.max(spec.target));
693            if let Some(&enabled) = seen.get(&key) {
694                if enabled != spec.enabled {
695                    return Err(LifecycleError::ConflictingEdge {
696                        source: spec.source,
697                        target: spec.target,
698                    });
699                }
700                continue;
701            }
702            if let Some(limit) = limits.max_edges
703                && seen.len() >= limit
704            {
705                return Err(GraphError::EdgeLimitExceeded { limit }.into());
706            }
707            for endpoint in [spec.source, spec.target] {
708                catalog.entry(endpoint).or_insert_with(|| {
709                    order.push(endpoint);
710                    NodeRecord::active()
711                });
712            }
713            seen.insert(key, spec.enabled);
714            let incidence = |neighbor| Incidence {
715                neighbor,
716                enabled: spec.enabled,
717            };
718            catalog
719                .get_mut(&spec.source)
720                .expect("endpoint registered above")
721                .incident
722                .push(incidence(spec.target));
723            catalog
724                .get_mut(&spec.target)
725                .expect("endpoint registered above")
726                .incident
727                .push(incidence(spec.source));
728        }
729        drop(seen);
730
731        for record in catalog.values_mut() {
732            record
733                .incident
734                .sort_unstable_by_key(|incidence| incidence.neighbor);
735        }
736        Ok((catalog, order))
737    }
738
739    /// Shrinks incident lists, computes counts and builds the engine from the
740    /// effective edges of a validated catalog with sorted, duplicate-free
741    /// incident lists. `O(V log V + E)` (see [`Self::build_engine`]).
742    fn finish(
743        engine: EngineConfig,
744        limits: GraphLimits,
745        mut catalog: FxHashMap<NodeId, NodeRecord>,
746        order: Vec<NodeId>,
747    ) -> Self {
748        let mut active_nodes = 0;
749        let mut registered_edges = 0;
750        let mut enabled_incidences = 0;
751        for record in catalog.values_mut() {
752            record.incident.shrink_to_fit();
753            registered_edges += record.incident.len();
754            enabled_incidences += record.incident.iter().filter(|i| i.enabled).count();
755            active_nodes += usize::from(record.active);
756        }
757        let (engine_graph, effective_edges) = Self::build_engine(engine, &mut catalog, &order);
758        let catalog_full_capacity = catalog.capacity();
759        Self {
760            nodes: catalog,
761            engine: engine_graph,
762            limits,
763            checks: Self::bounded(engine, limits),
764            active_nodes,
765            registered_edges: registered_edges / 2,
766            enabled_edges: enabled_incidences / 2,
767            effective_edges,
768            catalog_full_capacity,
769        }
770    }
771
772    /// Builds an unlimited engine holding every catalog node as a vertex and
773    /// exactly the effective edges; returns it with the effective edge count.
774    ///
775    /// For `compact-bfs` the engine
776    /// is built in one pass ([`Graph::from_sorted_adjacency`](crate::Graph::from_sorted_adjacency)): node IDs are
777    /// sorted and receive engine indices in ascending ID order (the index is
778    /// parked in the construction-only `pending` field, reset to zero
779    /// afterwards). Each effective edge costs one catalog probe, from its
780    /// smaller endpoint, and is appended to both adjacency lists; visiting
781    /// nodes in index order keeps every list strictly sorted. Each
782    /// adjacency vector is allocated once with capacity equal to the node's
783    /// enabled registered degree (an upper bound of its effective degree), so
784    /// no vector grows. `O(V log V + E)` time with expected `O(1)` probes;
785    /// scratch memory is the `O(V)` sorted ID vector.
786    ///
787    /// `cluster-forest` (the other lifecycle engine), and catalogs too large
788    /// for 32-bit indices, use the
789    /// incremental [`Self::build_engine_incremental`]. `order` is used only
790    /// by that path, as the vertex insertion order when it lists every catalog
791    /// node; otherwise (compaction passes an empty slice) the catalog's keys
792    /// are used, so no registered node is ever left out of the engine.
793    fn build_engine(
794        engine: EngineConfig,
795        catalog: &mut FxHashMap<NodeId, NodeRecord>,
796        order: &[NodeId],
797    ) -> (ConnectivityGraph, usize) {
798        if engine != EngineConfig::CompactBfs || u32::try_from(catalog.len()).is_err() {
799            // `order` may be empty (compaction passes none): every catalog node
800            // must still become a vertex, so fall back to the catalog's keys.
801            if order.len() == catalog.len() {
802                return Self::build_engine_incremental(engine, catalog, order);
803            }
804            let keys: Vec<NodeId> = catalog.keys().copied().collect();
805            return Self::build_engine_incremental(engine, catalog, &keys);
806        }
807        let mut ids: Vec<NodeId> = catalog.keys().copied().collect();
808        ids.sort_unstable();
809        for (index, node) in ids.iter().enumerate() {
810            catalog
811                .get_mut(node)
812                .expect("listed node is registered")
813                .pending = u32::try_from(index).expect("node count checked above");
814        }
815        let records: Vec<&NodeRecord> = ids.iter().map(|node| &catalog[node]).collect();
816        let mut adjacency: Vec<Vec<usize>> = records
817            .iter()
818            .map(|record| {
819                if record.active {
820                    Vec::with_capacity(record.incident.iter().filter(|i| i.enabled).count())
821                } else {
822                    Vec::new()
823                }
824            })
825            .collect();
826        // Each effective edge {u, v} with u < v is found once, from u, and
827        // pushed to both lists. Nodes are visited in ascending index order, so
828        // `adjacency[x]` first receives its smaller neighbors (pushed while
829        // visiting them, in ascending order) and then its larger ones (from
830        // its own sorted incident list): every list ends strictly sorted.
831        let mut edges = 0;
832        for (index, record) in records.iter().enumerate() {
833            if !record.active {
834                continue;
835            }
836            let node = ids[index];
837            for incidence in &record.incident {
838                if incidence.neighbor < node || !incidence.enabled {
839                    continue;
840                }
841                let neighbor = &catalog[&incidence.neighbor];
842                if neighbor.active {
843                    let other = neighbor.pending as usize;
844                    adjacency[index].push(other);
845                    adjacency[other].push(index);
846                    edges += 1;
847                }
848            }
849        }
850        drop(records);
851        for record in catalog.values_mut() {
852            record.pending = 0;
853        }
854        let graph = crate::Graph::from_sorted_adjacency(ids, adjacency);
855        (ConnectivityGraph::from(graph), edges)
856    }
857
858    /// Incremental engine construction through
859    /// [`ConnectivityGraph::try_from_edges`]: vertices in `order`, then the
860    /// effective edges. `O(V + E)` catalog work plus one engine insertion per
861    /// effective edge. Used for engines other than `compact-bfs` and as the
862    /// differential reference in tests.
863    fn build_engine_incremental(
864        engine: EngineConfig,
865        catalog: &FxHashMap<NodeId, NodeRecord>,
866        order: &[NodeId],
867    ) -> (ConnectivityGraph, usize) {
868        let mut effective: Vec<(NodeId, NodeId)> = Vec::new();
869        for &node in order {
870            let record = &catalog[&node];
871            if !record.active {
872                continue;
873            }
874            for incidence in &record.incident {
875                if node < incidence.neighbor
876                    && incidence.enabled
877                    && catalog[&incidence.neighbor].active
878                {
879                    effective.push((node, incidence.neighbor));
880                }
881            }
882        }
883        let graph =
884            ConnectivityGraph::try_from_edges(engine, GraphLimits::default(), order, &effective)
885                .expect("an unlimited engine accepts a validated simple graph");
886        (graph, effective.len())
887    }
888
889    /// Returns the **configured** limits on registered topology, exactly as
890    /// passed at construction; they are not adjusted for the engine.
891    ///
892    /// The **enforced** limits are the configured ones, except with
893    /// [`EngineConfig::ClusterForest`], where they can be lower:
894    /// at most `2²⁷ − 512` registered nodes and `2²⁸` registered edges,
895    /// whatever is configured (the engine's capacity, with room for retired
896    /// slots); mutations beyond them return [`GraphError::NodeLimitExceeded`]
897    /// or [`GraphError::EdgeLimitExceeded`] carrying the enforced limit.
898    #[must_use]
899    pub fn limits(&self) -> GraphLimits {
900        self.limits
901    }
902
903    /// Returns the engine that answers connectivity.
904    #[must_use]
905    pub fn engine(&self) -> EngineConfig {
906        self.engine.engine()
907    }
908
909    /// Registers `node` as an active isolated node.
910    ///
911    /// Returns `Ok(false)` if the node is already registered; an inactive
912    /// node stays inactive. Use [`set_node_active`](Self::set_node_active) to
913    /// reactivate it. A previously removed ID is registered as a fresh node
914    /// without its former edges.
915    ///
916    /// # Errors
917    ///
918    /// [`GraphError::NodeLimitExceeded`] when registering a new node would
919    /// exceed the enforced node limit: `max_nodes`, or the engine's lower
920    /// capacity (see [`Self::limits`]). The error carries the enforced value.
921    pub fn add_node(&mut self, node: NodeId) -> Result<bool, GraphError> {
922        if self.nodes.contains_key(&node) {
923            return Ok(false);
924        }
925        if let Some(limit) = self.checks.max_nodes
926            && self.nodes.len() >= limit
927        {
928            return Err(GraphError::NodeLimitExceeded { limit });
929        }
930        self.register(node);
931        Ok(true)
932    }
933
934    /// Registers a node known to be absent and within limits.
935    fn register(&mut self, node: NodeId) {
936        self.reserve_catalog_slot();
937        self.nodes.insert(node, NodeRecord::active());
938        // A retired engine slot for `node` is isolated and is reused as is.
939        self.engine
940            .add_node(node)
941            .expect("an unlimited engine accepts any vertex");
942        self.active_nodes += 1;
943    }
944
945    /// Makes room for one new catalog entry without growing a table whose
946    /// headroom was consumed by tombstones (see the module documentation):
947    /// when the next insert would grow the table and live entries are at most
948    /// 90% of its full capacity, the catalog is rebuilt into a fresh table
949    /// sized for its live entries (never larger than the old one). `O(V)` when
950    /// it rebuilds, `O(1)` otherwise.
951    fn reserve_catalog_slot(&mut self) {
952        let capacity = self.nodes.capacity();
953        self.catalog_full_capacity = self.catalog_full_capacity.max(capacity);
954        let live = self.nodes.len();
955        if capacity == live
956            && live * REBUILD_LIVE_DENOMINATOR
957                <= self.catalog_full_capacity * REBUILD_LIVE_NUMERATOR
958        {
959            let mut fresh: FxHashMap<NodeId, NodeRecord> =
960                FxHashMap::with_capacity_and_hasher(live, Default::default());
961            fresh.extend(self.nodes.drain());
962            self.nodes = fresh;
963            self.catalog_full_capacity = self.nodes.capacity();
964        }
965    }
966
967    /// Registers the undirected edge `{source, target}` as enabled.
968    ///
969    /// Missing endpoints are registered as active nodes. The edge is
970    /// effective only if both endpoints are active. Returns `Ok(false)` if
971    /// the edge is already registered, enabled or disabled; a disabled edge
972    /// stays disabled.
973    ///
974    /// # Errors
975    ///
976    /// In precedence order: [`GraphError::SelfLoop`];
977    /// [`GraphError::NodeLimitExceeded`] when the missing endpoints do not
978    /// fit; [`GraphError::EdgeLimitExceeded`] for a new edge at the enforced
979    /// edge limit. Both carry the enforced value, which can be lower than the
980    /// configured one (see [`Self::limits`]).
981    pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
982        GraphError::check_distinct(source, target)?;
983        let source_known = self.nodes.contains_key(&source);
984        let target_known = self.nodes.contains_key(&target);
985        if let Some(limit) = self.checks.max_nodes {
986            let missing = usize::from(!source_known) + usize::from(!target_known);
987            if missing > limit.saturating_sub(self.nodes.len()) {
988                return Err(GraphError::NodeLimitExceeded { limit });
989            }
990        }
991        let exists = source_known && target_known && self.nodes[&source].position(target).is_ok();
992        if exists {
993            return Ok(false);
994        }
995        if let Some(limit) = self.checks.max_edges
996            && self.registered_edges >= limit
997        {
998            return Err(GraphError::EdgeLimitExceeded { limit });
999        }
1000        if !source_known {
1001            self.register(source);
1002        }
1003        if !target_known {
1004            self.register(target);
1005        }
1006        self.insert_edge(source, target, true);
1007        Ok(true)
1008    }
1009
1010    /// Inserts a validated, absent edge between registered distinct nodes.
1011    fn insert_edge(&mut self, source: NodeId, target: NodeId, enabled: bool) {
1012        for (owner, neighbor) in [(source, target), (target, source)] {
1013            let record = self.nodes.get_mut(&owner).expect("endpoint is registered");
1014            let index = record
1015                .position(neighbor)
1016                .expect_err("edge is absent at both endpoints");
1017            record
1018                .incident
1019                .insert(index, Incidence { neighbor, enabled });
1020        }
1021        self.registered_edges += 1;
1022        if enabled {
1023            self.enabled_edges += 1;
1024            if self.nodes[&source].active && self.nodes[&target].active {
1025                self.engine_link(source, target);
1026            }
1027        }
1028    }
1029
1030    fn engine_link(&mut self, source: NodeId, target: NodeId) {
1031        let changed = self
1032            .engine
1033            .link(source, target)
1034            .expect("an unlimited engine links distinct vertices");
1035        debug_assert!(changed, "engine edge set equals the effective edge set");
1036        self.effective_edges += 1;
1037    }
1038
1039    fn engine_cut(&mut self, source: NodeId, target: NodeId) {
1040        let changed = self
1041            .engine
1042            .cut(source, target)
1043            .expect("the engine cuts distinct vertices");
1044        debug_assert!(changed, "engine edge set equals the effective edge set");
1045        self.effective_edges -= 1;
1046    }
1047
1048    /// Removes the registered edge `{source, target}`, whether or not it is
1049    /// enabled or effective. Both endpoints stay registered.
1050    ///
1051    /// Returns `Ok(false)` if the edge or an endpoint is not registered.
1052    ///
1053    /// # Errors
1054    ///
1055    /// [`GraphError::SelfLoop`] if `source == target`.
1056    pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
1057        GraphError::check_distinct(source, target)?;
1058        let (Some(source_record), Some(target_record)) =
1059            (self.nodes.get(&source), self.nodes.get(&target))
1060        else {
1061            return Ok(false);
1062        };
1063        let Ok(index) = source_record.position(target) else {
1064            return Ok(false);
1065        };
1066        let both_active = source_record.active && target_record.active;
1067        let removed = self
1068            .nodes
1069            .get_mut(&source)
1070            .expect("source is registered")
1071            .remove_at(index);
1072        let target_record = self.nodes.get_mut(&target).expect("target is registered");
1073        let reverse = target_record
1074            .position(source)
1075            .expect("incidence is symmetric");
1076        target_record.remove_at(reverse);
1077        self.registered_edges -= 1;
1078        if removed.enabled {
1079            self.enabled_edges -= 1;
1080            if both_active {
1081                self.engine_cut(source, target);
1082            }
1083        }
1084        Ok(true)
1085    }
1086
1087    /// Sets the `active` flag of a registered node.
1088    ///
1089    /// Incident registered edges and their `enabled` flags are preserved.
1090    /// Activation makes effective exactly the incident edges that are enabled
1091    /// and whose other endpoint is active. Returns `Ok(false)` if the flag
1092    /// already has this value.
1093    ///
1094    /// Costs `O(d)` for registered degree `d`, plus one engine update for
1095    /// each incident edge whose effectiveness changes.
1096    ///
1097    /// # Errors
1098    ///
1099    /// [`GraphError::UnknownNode`] (wrapped) if `node` is not registered.
1100    pub fn set_node_active(&mut self, node: NodeId, active: bool) -> Result<bool, LifecycleError> {
1101        let record = self
1102            .nodes
1103            .get(&node)
1104            .ok_or(GraphError::UnknownNode { node })?;
1105        if record.active == active {
1106            return Ok(false);
1107        }
1108        // Effective incident edges are visited in descending neighbor order
1109        // (see `remove_node` for why).
1110        let mut affected = Vec::new();
1111        for incidence in record.incident.iter().rev() {
1112            if incidence.enabled && self.nodes[&incidence.neighbor].active {
1113                affected.push(incidence.neighbor);
1114            }
1115        }
1116        for neighbor in affected {
1117            if active {
1118                self.engine_link(node, neighbor);
1119            } else {
1120                self.engine_cut(node, neighbor);
1121            }
1122        }
1123        self.nodes
1124            .get_mut(&node)
1125            .expect("node is registered")
1126            .active = active;
1127        if active {
1128            self.active_nodes += 1;
1129        } else {
1130            self.active_nodes -= 1;
1131        }
1132        Ok(true)
1133    }
1134
1135    /// Sets the `enabled` flag of a registered edge, including while an
1136    /// endpoint is inactive; the flag then takes effect when both endpoints
1137    /// are active. Returns `Ok(false)` if the flag already has this value.
1138    ///
1139    /// # Errors
1140    ///
1141    /// In precedence order: [`GraphError::SelfLoop`];
1142    /// [`GraphError::UnknownNode`] for `source`, then for `target`;
1143    /// [`LifecycleError::UnknownEdge`] if both nodes are registered but the
1144    /// edge is not.
1145    pub fn set_edge_enabled(
1146        &mut self,
1147        source: NodeId,
1148        target: NodeId,
1149        enabled: bool,
1150    ) -> Result<bool, LifecycleError> {
1151        GraphError::check_distinct(source, target)?;
1152        let source_record = self
1153            .nodes
1154            .get(&source)
1155            .ok_or(GraphError::UnknownNode { node: source })?;
1156        let target_record = self
1157            .nodes
1158            .get(&target)
1159            .ok_or(GraphError::UnknownNode { node: target })?;
1160        let index = source_record
1161            .position(target)
1162            .map_err(|_| LifecycleError::UnknownEdge { source, target })?;
1163        if source_record.incident[index].enabled == enabled {
1164            return Ok(false);
1165        }
1166        let both_active = source_record.active && target_record.active;
1167        let reverse = target_record
1168            .position(source)
1169            .expect("incidence is symmetric");
1170        self.nodes
1171            .get_mut(&source)
1172            .expect("source is registered")
1173            .incident[index]
1174            .enabled = enabled;
1175        self.nodes
1176            .get_mut(&target)
1177            .expect("target is registered")
1178            .incident[reverse]
1179            .enabled = enabled;
1180        if enabled {
1181            self.enabled_edges += 1;
1182            if both_active {
1183                self.engine_link(source, target);
1184            }
1185        } else {
1186            self.enabled_edges -= 1;
1187            if both_active {
1188                self.engine_cut(source, target);
1189            }
1190        }
1191        Ok(true)
1192    }
1193
1194    /// Permanently removes `node` and every incident registered edge,
1195    /// including disabled edges and edges to inactive neighbors.
1196    ///
1197    /// Returns `false` if `node` is not registered. Registering the same ID
1198    /// later creates a fresh active isolated node.
1199    ///
1200    /// Costs `O(d + sum of neighbor degrees)` catalog work for registered
1201    /// degree `d`, one engine update per effective incident edge, and an
1202    /// amortized share of engine compaction.
1203    pub fn remove_node(&mut self, node: NodeId) -> bool {
1204        let Some(record) = self.nodes.remove(&node) else {
1205            return false;
1206        };
1207        // Descending neighbor order. For `compact-bfs`, the only engine with
1208        // lifecycle support, whose adjacency vectors are sorted, this removes
1209        // from the end of the node's vector, so each removal shifts no elements
1210        // instead of up to `d`. (Earlier candidates also measured this order on
1211        // the now-deferred `ett` and `hdt` lifecycle support.)
1212        for incidence in record.incident.iter().rev() {
1213            let neighbor = self
1214                .nodes
1215                .get_mut(&incidence.neighbor)
1216                .expect("neighbor is registered");
1217            let neighbor_active = neighbor.active;
1218            let reverse = neighbor.position(node).expect("incidence is symmetric");
1219            neighbor.remove_at(reverse);
1220            self.registered_edges -= 1;
1221            if incidence.enabled {
1222                self.enabled_edges -= 1;
1223                if record.active && neighbor_active {
1224                    self.engine_cut(node, incidence.neighbor);
1225                }
1226            }
1227        }
1228        if record.active {
1229            self.active_nodes -= 1;
1230        }
1231        // The retired slot is isolated now; release its adjacency allocation
1232        // so it retains only its ID-map entry and an empty vector header.
1233        self.engine.release_isolated_storage(node);
1234        self.compact_if_needed();
1235        true
1236    }
1237
1238    /// Rebuilds the engine when retired slots exceed
1239    /// `max(registered nodes, MIN_RETIRED_BEFORE_COMPACTION)`, through
1240    /// [`Self::build_engine`]. The old engine is dropped after the new one is
1241    /// built, so both are live at the peak.
1242    fn compact_if_needed(&mut self) {
1243        let retired = self.engine.node_count() - self.nodes.len();
1244        if retired <= self.nodes.len().max(MIN_RETIRED_BEFORE_COMPACTION) {
1245            return;
1246        }
1247        let (engine, effective) = Self::build_engine(self.engine.engine(), &mut self.nodes, &[]);
1248        debug_assert_eq!(effective, self.effective_edges);
1249        self.engine = engine;
1250    }
1251
1252    /// Returns whether `source` and `target` are connected in the effective
1253    /// graph.
1254    ///
1255    /// An inactive endpoint returns `Ok(false)`, including
1256    /// `connected(n, n)`. An active node is connected to itself.
1257    ///
1258    /// # Errors
1259    ///
1260    /// [`GraphError::UnknownNode`] for `source`, then for `target`, if not
1261    /// registered.
1262    pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
1263        let source_record = self
1264            .nodes
1265            .get(&source)
1266            .ok_or(GraphError::UnknownNode { node: source })?;
1267        let target_record = self
1268            .nodes
1269            .get(&target)
1270            .ok_or(GraphError::UnknownNode { node: target })?;
1271        if !source_record.active || !target_record.active {
1272            return Ok(false);
1273        }
1274        self.engine.connected(source, target)
1275    }
1276
1277    /// Returns `Some(active)` for a registered node, `None` otherwise.
1278    #[must_use]
1279    pub fn node_active(&self, node: NodeId) -> Option<bool> {
1280        self.nodes.get(&node).map(|record| record.active)
1281    }
1282
1283    /// Returns the number of registered edges incident to `node` (enabled or
1284    /// not), or `None` if it is not registered. Expected O(1).
1285    #[must_use]
1286    pub fn degree(&self, node: NodeId) -> Option<usize> {
1287        self.nodes.get(&node).map(|record| record.incident.len())
1288    }
1289
1290    /// Iterates the registered edges incident to `node` in ascending neighbor
1291    /// ID, starting strictly after the neighbor `after` (or from the start),
1292    /// with each edge's flags. Returns `None` if `node` is not registered.
1293    ///
1294    /// `after` is a pagination cursor: it need not be registered or still
1295    /// linked, so every edge that stays registered while a caller pages through
1296    /// the list is visited exactly once; edges registered or removed meanwhile
1297    /// may or may not be visited.
1298    ///
1299    /// Positioning is O(log deg(node)); each step costs one expected-O(1)
1300    /// catalog lookup of the neighbor (for `effective`).
1301    ///
1302    /// ```rust
1303    /// use knotrel_core::{EngineConfig, LifecycleGraph};
1304    ///
1305    /// let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs)?;
1306    /// graph.link(5, 9)?;
1307    /// graph.link(5, 1)?;
1308    /// graph.set_node_active(9, false)?;
1309    /// let edges: Vec<_> = graph.incident_after(5, None).unwrap().collect();
1310    /// assert_eq!(edges.len(), 2);
1311    /// assert_eq!(edges[0].0, 1); // ascending neighbor ID
1312    /// assert!(edges[0].1.effective);
1313    /// assert!(edges[1].1.enabled && !edges[1].1.effective); // 9 is inactive
1314    /// assert_eq!(graph.incident_after(5, Some(1)).unwrap().count(), 1);
1315    /// # Ok::<(), Box<dyn std::error::Error>>(())
1316    /// ```
1317    pub fn incident_after(
1318        &self,
1319        node: NodeId,
1320        after: Option<NodeId>,
1321    ) -> Option<impl Iterator<Item = (NodeId, EdgeState)> + '_> {
1322        let record = self.nodes.get(&node)?;
1323        let start = after.map_or(0, |cursor| {
1324            record
1325                .incident
1326                .partition_point(|incidence| incidence.neighbor <= cursor)
1327        });
1328        Some(record.incident[start..].iter().map(move |incidence| {
1329            let neighbor_active = self.nodes[&incidence.neighbor].active;
1330            (
1331                incidence.neighbor,
1332                EdgeState {
1333                    enabled: incidence.enabled,
1334                    effective: incidence.enabled && record.active && neighbor_active,
1335                },
1336            )
1337        }))
1338    }
1339
1340    /// Returns the flags of the registered edge `{source, target}`, or `None`
1341    /// if it is not registered. A self-loop pair is never registered.
1342    #[must_use]
1343    pub fn edge_state(&self, source: NodeId, target: NodeId) -> Option<EdgeState> {
1344        let source_record = self.nodes.get(&source)?;
1345        let index = source_record.position(target).ok()?;
1346        let enabled = source_record.incident[index].enabled;
1347        let effective = enabled && source_record.active && self.nodes[&target].active;
1348        Some(EdgeState { enabled, effective })
1349    }
1350
1351    /// Calls `visit` once for every registered node with its flag, in
1352    /// unspecified order.
1353    ///
1354    /// **Experimental** (new in 1.3): with [`for_each_edge`](Self::for_each_edge),
1355    /// a bulk read whose output [`try_from_topology`](Self::try_from_topology)
1356    /// accepts as is, for snapshots and exports. `O(V)` time; allocates
1357    /// nothing.
1358    ///
1359    /// ```rust
1360    /// use knotrel_core::{EngineConfig, LifecycleGraph, NodeSpec};
1361    ///
1362    /// let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs)?;
1363    /// graph.link(1, 2)?;
1364    /// graph.set_node_active(2, false)?;
1365    /// let mut nodes = Vec::new();
1366    /// graph.for_each_node(|spec| nodes.push(spec));
1367    /// nodes.sort_unstable_by_key(|spec| spec.node);
1368    /// assert_eq!(
1369    ///     nodes,
1370    ///     [NodeSpec { node: 1, active: true }, NodeSpec { node: 2, active: false }]
1371    /// );
1372    /// # Ok::<(), Box<dyn std::error::Error>>(())
1373    /// ```
1374    pub fn for_each_node(&self, mut visit: impl FnMut(NodeSpec)) {
1375        for (&node, record) in &self.nodes {
1376            visit(NodeSpec {
1377                node,
1378                active: record.active,
1379            });
1380        }
1381    }
1382
1383    /// Calls `visit` once for every registered edge with its own flag, with
1384    /// `source < target`, in unspecified order.
1385    ///
1386    /// **Experimental** (new in 1.3): see [`for_each_node`](Self::for_each_node).
1387    /// The flag is the edge's own `enabled` flag, independent of its
1388    /// endpoints. `O(V + E)` time; allocates nothing.
1389    ///
1390    /// ```rust
1391    /// use knotrel_core::{EdgeSpec, EngineConfig, LifecycleGraph};
1392    ///
1393    /// let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs)?;
1394    /// graph.link(9, 4)?;
1395    /// graph.set_edge_enabled(4, 9, false)?;
1396    /// let mut edges = Vec::new();
1397    /// graph.for_each_edge(|spec| edges.push(spec));
1398    /// assert_eq!(edges, [EdgeSpec { source: 4, target: 9, enabled: false }]);
1399    /// # Ok::<(), Box<dyn std::error::Error>>(())
1400    /// ```
1401    pub fn for_each_edge(&self, mut visit: impl FnMut(EdgeSpec)) {
1402        for (&node, record) in &self.nodes {
1403            let start = record
1404                .incident
1405                .partition_point(|incidence| incidence.neighbor <= node);
1406            for incidence in &record.incident[start..] {
1407                visit(EdgeSpec {
1408                    source: node,
1409                    target: incidence.neighbor,
1410                    enabled: incidence.enabled,
1411                });
1412            }
1413        }
1414    }
1415
1416    /// Returns the number of registered nodes, active or inactive.
1417    #[must_use]
1418    pub fn node_count(&self) -> usize {
1419        self.nodes.len()
1420    }
1421
1422    /// Returns the number of registered edges, enabled or disabled.
1423    #[must_use]
1424    pub fn edge_count(&self) -> usize {
1425        self.registered_edges
1426    }
1427
1428    /// Returns the number of registered nodes whose flag is active.
1429    #[must_use]
1430    pub fn active_node_count(&self) -> usize {
1431        self.active_nodes
1432    }
1433
1434    /// Returns the number of registered edges whose flag is enabled.
1435    #[must_use]
1436    pub fn enabled_edge_count(&self) -> usize {
1437        self.enabled_edges
1438    }
1439
1440    /// Returns the number of effective edges: enabled, with both endpoints
1441    /// active.
1442    #[must_use]
1443    pub fn effective_edge_count(&self) -> usize {
1444        self.effective_edges
1445    }
1446
1447    /// Returns the number of vertices held by the inner engine: every
1448    /// registered node plus retired slots of removed nodes not yet compacted.
1449    ///
1450    /// It is a storage diagnostic, bounded by `2 × node_count() + 1024`.
1451    #[must_use]
1452    pub fn engine_vertex_count(&self) -> usize {
1453        self.engine.node_count()
1454    }
1455
1456    /// Returns storage diagnostics: logical sizes and retained capacities.
1457    ///
1458    /// Costs `O(V)` time (one pass over the catalog) and no allocation, and
1459    /// changes no state. [`LifecycleStorage`] lists which properties of the
1460    /// values are guaranteed and which are implementation-dependent.
1461    #[must_use]
1462    pub fn storage_stats(&self) -> LifecycleStorage {
1463        let (incident_entries, incident_capacity) =
1464            self.nodes.values().fold((0, 0), |(len, cap), record| {
1465                (
1466                    len + record.incident.len(),
1467                    cap + record.incident.capacity(),
1468                )
1469            });
1470        let engine_vertices = self.engine.node_count();
1471        LifecycleStorage {
1472            engine_vertices,
1473            retired_vertices: engine_vertices - self.nodes.len(),
1474            catalog_nodes: self.nodes.len(),
1475            catalog_node_capacity: self.nodes.capacity(),
1476            incident_entries,
1477            incident_capacity,
1478        }
1479    }
1480
1481    /// Verifies every internal invariant; panics on violation. Test support.
1482    #[cfg(test)]
1483    pub(crate) fn validate(&self) {
1484        let mut registered = 0;
1485        let mut enabled = 0;
1486        let mut effective = 0;
1487        let mut active = 0;
1488        for (&node, record) in &self.nodes {
1489            active += usize::from(record.active);
1490            assert!(self.engine.contains_node(node));
1491            for pair in record.incident.windows(2) {
1492                assert!(pair[0].neighbor < pair[1].neighbor);
1493            }
1494            for incidence in &record.incident {
1495                assert_ne!(incidence.neighbor, node);
1496                let other = &self.nodes[&incidence.neighbor];
1497                let back = other.position(node).expect("symmetric");
1498                assert_eq!(other.incident[back].enabled, incidence.enabled);
1499                if node < incidence.neighbor {
1500                    registered += 1;
1501                    enabled += usize::from(incidence.enabled);
1502                    if incidence.enabled && record.active && other.active {
1503                        effective += 1;
1504                    }
1505                }
1506            }
1507        }
1508        assert_eq!(registered, self.registered_edges);
1509        assert_eq!(enabled, self.enabled_edges);
1510        assert_eq!(effective, self.effective_edges);
1511        assert_eq!(active, self.active_nodes);
1512        assert_eq!(effective, self.engine.edge_count());
1513        assert!(self.engine.node_count() <= 2 * self.nodes.len() + MIN_RETIRED_BEFORE_COMPACTION);
1514    }
1515}
1516
1517#[cfg(test)]
1518mod tests {
1519    use super::*;
1520
1521    /// `incident_after` pages in ascending neighbor ID, reports flags, and keeps
1522    /// working with a cursor whose neighbor was removed.
1523    #[test]
1524    fn incident_pages_follow_neighbor_ids_and_survive_removal() {
1525        let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs).unwrap();
1526        for neighbor in [30, 10, 20, u64::MAX] {
1527            graph.link(5, neighbor).unwrap();
1528        }
1529        graph.set_edge_enabled(5, 20, false).unwrap();
1530        graph.set_node_active(u64::MAX, false).unwrap();
1531        let first: Vec<_> = graph.incident_after(5, None).unwrap().take(2).collect();
1532        assert_eq!(first.iter().map(|e| e.0).collect::<Vec<_>>(), [10, 20]);
1533        assert!(first[0].1.effective);
1534        assert!(!first[1].1.enabled && !first[1].1.effective);
1535        assert!(graph.remove_node(20));
1536        let rest: Vec<_> = graph.incident_after(5, Some(20)).unwrap().collect();
1537        assert_eq!(rest.iter().map(|e| e.0).collect::<Vec<_>>(), [30, u64::MAX]);
1538        assert!(rest[1].1.enabled && !rest[1].1.effective);
1539        assert_eq!(graph.degree(5), Some(3));
1540        assert_eq!(graph.degree(20), None);
1541        assert!(graph.incident_after(20, None).is_none());
1542    }
1543
1544    /// `Error::source` exposes only wrapped graph errors.
1545    #[test]
1546    fn lifecycle_error_source_wraps_only_graph_errors() {
1547        let graph = LifecycleError::Graph(GraphError::SelfLoop { node: 1 });
1548        assert!(graph.source().is_some());
1549        for other in [
1550            LifecycleError::UnknownEdge {
1551                source: 1,
1552                target: 2,
1553            },
1554            LifecycleError::ConflictingNode { node: 1 },
1555            LifecycleError::UnsupportedEngine {
1556                engine: EngineConfig::Hdt,
1557            },
1558        ] {
1559            assert!(other.source().is_none(), "{other}");
1560        }
1561    }
1562
1563    /// Incident vectors shrink after most incidences are cut; a link to an
1564    /// inactive endpoint is registered without an engine edge; compaction
1565    /// skips inactive nodes' incidences.
1566    #[test]
1567    fn shrink_inactive_links_and_compaction_with_inactive_nodes() {
1568        let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs).unwrap();
1569        for neighbor in 1..=64 {
1570            graph.link(0, neighbor).unwrap();
1571        }
1572        let before = graph.nodes[&0].incident.capacity();
1573        for neighbor in 1..=60 {
1574            graph.cut(0, neighbor).unwrap();
1575        }
1576        assert!(graph.nodes[&0].incident.capacity() < before);
1577        graph.validate();
1578
1579        graph.add_node(200).unwrap();
1580        graph.set_node_active(200, false).unwrap();
1581        assert_eq!(graph.link(0, 200), Ok(true));
1582        assert_eq!(graph.edge_state(0, 200).map(|s| s.effective), Some(false));
1583        graph.validate();
1584
1585        // More than 1,024 removals while node 200 (with an incident edge)
1586        // stays inactive trigger a compaction that must skip it.
1587        for node in 1_000..2_200 {
1588            graph.link(node, node + 10_000).unwrap();
1589        }
1590        let vertices = graph.engine_vertex_count();
1591        for node in 1_000..2_200 {
1592            graph.remove_node(node);
1593            graph.remove_node(node + 10_000);
1594        }
1595        assert!(graph.engine_vertex_count() < vertices, "a compaction ran");
1596        assert_eq!(graph.node_active(200), Some(false));
1597        assert_eq!(graph.edge_state(0, 200).map(|s| s.effective), Some(false));
1598        graph.validate();
1599    }
1600
1601    /// A removed node's retired engine slot keeps no adjacency allocation,
1602    /// whatever its former degree, and its same-ID reuse starts empty.
1603    #[test]
1604    fn removal_releases_retired_slot_adjacency() {
1605        let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs).unwrap();
1606        for leaf in 1..=300 {
1607            graph.link(0, leaf).unwrap();
1608        }
1609        assert!(graph.engine.adjacency_capacity(0).unwrap() >= 300);
1610        assert!(graph.remove_node(0));
1611        assert_eq!(graph.engine.adjacency_capacity(0), Some(0), "retired slot");
1612        assert_eq!(graph.storage_stats().retired_vertices, 1);
1613        assert!(graph.add_node(0).unwrap());
1614        assert_eq!(graph.engine.adjacency_capacity(0), Some(0));
1615        assert!(!graph.connected(0, 1).unwrap());
1616        graph.validate();
1617    }
1618
1619    #[cfg(target_pointer_width = "64")]
1620    #[test]
1621    fn node_record_degree_hint_fits_in_padding() {
1622        assert_eq!(size_of::<NodeRecord>(), 32);
1623    }
1624
1625    /// The fast catalog path agrees with the exact path: identical catalogs
1626    /// and registration order whenever it succeeds, and `None` on every input
1627    /// the exact path rejects. Inputs mix duplicates (same and reversed
1628    /// endpoints, same and different flags), self-loops and tight limits.
1629    #[test]
1630    fn fast_catalog_matches_exact_catalog() {
1631        let mut seed = 0x51_u64;
1632        let mut next = move |bound: u64| {
1633            seed = seed
1634                .wrapping_mul(6364136223846793005)
1635                .wrapping_add(1442695040888963407);
1636            (seed >> 33) % bound
1637        };
1638        let mut fast_successes = 0;
1639        let mut exact_errors = 0;
1640        let mut fallback_successes = 0;
1641        for case in 0..3_000 {
1642            let n = 2 + next(60);
1643            let nodes: Vec<NodeSpec> = (0..next(10))
1644                .map(|_| NodeSpec {
1645                    node: next(n),
1646                    active: next(12) != 0,
1647                })
1648                .collect();
1649            let mut edges: Vec<EdgeSpec> = (0..next(25))
1650                .map(|_| EdgeSpec {
1651                    source: next(n),
1652                    target: next(n),
1653                    enabled: next(12) != 0,
1654                })
1655                .collect();
1656            for _ in 0..next(4) {
1657                // Repeated edges, often reversed, sometimes with a flipped flag.
1658                if let Some(&e) = edges.get(next(edges.len().max(1) as u64) as usize) {
1659                    let flip = next(5) == 0;
1660                    edges.push(EdgeSpec {
1661                        source: e.target,
1662                        target: e.source,
1663                        enabled: e.enabled != flip,
1664                    });
1665                }
1666            }
1667            let limits = GraphLimits {
1668                max_nodes: (case % 3 == 0).then(|| next(14) as usize),
1669                max_edges: (case % 4 == 0).then(|| next(26) as usize),
1670            };
1671            let exact = LifecycleGraph::catalog_exact(limits, &nodes, &edges);
1672            let fast = LifecycleGraph::catalog_fast(limits, &nodes, &edges);
1673            match (&exact, fast) {
1674                (Ok((exact_catalog, exact_order)), Some((fast_catalog, fast_order))) => {
1675                    fast_successes += 1;
1676                    assert_eq!(exact_order, &fast_order, "case {case}");
1677                    assert_eq!(exact_catalog.len(), fast_catalog.len());
1678                    for (node, record) in exact_catalog {
1679                        let other = &fast_catalog[node];
1680                        assert_eq!(record.active, other.active);
1681                        let pairs = |r: &NodeRecord| {
1682                            r.incident
1683                                .iter()
1684                                .map(|i| (i.neighbor, i.enabled))
1685                                .collect::<Vec<_>>()
1686                        };
1687                        assert_eq!(pairs(record), pairs(other), "case {case}");
1688                    }
1689                }
1690                (Err(_), None) => exact_errors += 1,
1691                (Ok(_), None) => fallback_successes += 1,
1692                (Err(error), Some(_)) => panic!("case {case}: fast path accepted {error:?}"),
1693            }
1694        }
1695        assert!(fast_successes > 600, "{fast_successes}");
1696        assert!(exact_errors > 300, "{exact_errors}");
1697        // Only an edge-limit pre-check with duplicates may defer a success.
1698        assert!(
1699            fallback_successes < fast_successes / 10,
1700            "{fallback_successes}"
1701        );
1702    }
1703
1704    /// Bulk engine construction agrees with incremental construction on
1705    /// random flagged catalogs: same vertex and edge counts, the same
1706    /// connectivity on every pair, and every internal invariant. Compaction
1707    /// uses the same builder, so a compacted graph is checked as well.
1708    #[test]
1709    fn bulk_engine_build_matches_incremental_build() {
1710        let mut seed = 0x9e37_79b9_u64;
1711        let mut next = move |bound: u64| {
1712            seed ^= seed << 13;
1713            seed ^= seed >> 7;
1714            seed ^= seed << 17;
1715            seed % bound
1716        };
1717        for case in 0..400 {
1718            // IDs are spread over a wide range and inserted out of order, so
1719            // ascending-ID indices differ from registration order.
1720            let n = 2 + next(40);
1721            let id = |k: u64| k.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (case % 40);
1722            let nodes: Vec<NodeSpec> = (0..next(n))
1723                .map(|_| NodeSpec {
1724                    node: id(next(n)),
1725                    active: next(3) != 0,
1726                })
1727                .collect();
1728            let mut edges = Vec::new();
1729            for _ in 0..next(3 * n) {
1730                let (source, target) = (id(next(n)), id(next(n)));
1731                let enabled = next(4) != 0;
1732                if source != target {
1733                    edges.push(EdgeSpec {
1734                        source,
1735                        target,
1736                        enabled,
1737                    });
1738                }
1739            }
1740            let Ok((mut catalog, order)) =
1741                LifecycleGraph::catalog_exact(GraphLimits::default(), &nodes, &edges)
1742            else {
1743                continue; // conflicting repeated flags
1744            };
1745            let (incremental, incremental_edges) = LifecycleGraph::build_engine_incremental(
1746                EngineConfig::CompactBfs,
1747                &catalog,
1748                &order,
1749            );
1750            let (bulk, bulk_edges) =
1751                LifecycleGraph::build_engine(EngineConfig::CompactBfs, &mut catalog, &order);
1752            assert_eq!(bulk_edges, incremental_edges, "case {case}");
1753            assert_eq!(bulk.edge_count(), incremental.edge_count(), "case {case}");
1754            assert_eq!(bulk.node_count(), incremental.node_count(), "case {case}");
1755            assert!(catalog.values().all(|record| record.pending == 0));
1756            for &a in &order {
1757                for &b in &order {
1758                    assert_eq!(
1759                        bulk.connected(a, b),
1760                        incremental.connected(a, b),
1761                        "case {case}: {a}-{b}"
1762                    );
1763                }
1764            }
1765            let graph = LifecycleGraph::finish(
1766                EngineConfig::CompactBfs,
1767                GraphLimits::default(),
1768                catalog,
1769                order,
1770            );
1771            graph.validate();
1772        }
1773    }
1774
1775    /// The incremental fallback of `build_engine` (non-`compact-bfs`
1776    /// engines) registers every catalog node, whether it receives the full
1777    /// insertion order or the empty slice that compaction passes, and agrees
1778    /// with the one-pass `compact-bfs` build on edges and connectivity.
1779    #[test]
1780    fn fallback_engine_build_registers_every_catalog_node() {
1781        let nodes: Vec<NodeSpec> = [(9, true), (3, false), (7, true), (1, true), (5, true)]
1782            .into_iter()
1783            .map(|(node, active)| NodeSpec { node, active })
1784            .collect();
1785        let edges: Vec<EdgeSpec> = [(9, 7, true), (7, 1, true), (3, 9, true), (5, 1, false)]
1786            .into_iter()
1787            .map(|(source, target, enabled)| EdgeSpec {
1788                source,
1789                target,
1790                enabled,
1791            })
1792            .collect();
1793        let (mut catalog, order) =
1794            LifecycleGraph::catalog_exact(GraphLimits::default(), &nodes, &edges).unwrap();
1795        let (compact, compact_edges) =
1796            LifecycleGraph::build_engine(EngineConfig::CompactBfs, &mut catalog, &order);
1797        for given in [&order[..], &[][..]] {
1798            let (fallback, fallback_edges) =
1799                LifecycleGraph::build_engine(EngineConfig::EulerTour, &mut catalog, given);
1800            assert_eq!(fallback.engine(), EngineConfig::EulerTour);
1801            assert_eq!(fallback.node_count(), catalog.len());
1802            assert_eq!(fallback_edges, compact_edges);
1803            assert_eq!(fallback.edge_count(), compact.edge_count());
1804            for &a in &order {
1805                for &b in &order {
1806                    assert_eq!(fallback.connected(a, b), compact.connected(a, b), "{a}-{b}");
1807                }
1808            }
1809        }
1810    }
1811
1812    /// Random mixed operations, including high-degree hubs, keep every
1813    /// internal invariant (catalog symmetry, engine edge set, counters).
1814    #[test]
1815    fn random_operations_preserve_internal_invariants() {
1816        // `ett` and `hdt` lifecycle support is deferred (rejected by the constructors).
1817        for engine in [EngineConfig::CompactBfs] {
1818            let mut state = 0x1234_5678_u64;
1819            let mut next = move |bound: u64| {
1820                state ^= state << 13;
1821                state ^= state >> 7;
1822                state ^= state << 17;
1823                state % bound
1824            };
1825            let mut graph = LifecycleGraph::new(engine).unwrap();
1826            for _ in 0..4_000 {
1827                // Node 0 is a hub that most edges touch.
1828                let a = if next(3) == 0 { 0 } else { next(40) };
1829                let b = next(40);
1830                let flag = next(2) == 0;
1831                match next(9) {
1832                    0..=2 => drop(graph.link(a, b)),
1833                    3 => drop(graph.cut(a, b)),
1834                    4 => drop(graph.set_node_active(a, flag)),
1835                    5 | 6 => drop(graph.set_edge_enabled(a, b, flag)),
1836                    7 => drop(graph.remove_node(a)),
1837                    _ => drop(graph.add_node(a)),
1838                }
1839                graph.validate();
1840            }
1841        }
1842    }
1843
1844    #[test]
1845    fn compaction_bounds_retired_slots_and_preserves_connectivity() {
1846        // `ett` and `hdt` lifecycle support is deferred (rejected by the constructors).
1847        for engine in [EngineConfig::CompactBfs] {
1848            let mut graph = LifecycleGraph::new(engine).unwrap();
1849            graph.link(0, 1).unwrap();
1850            graph.link(1, 2).unwrap();
1851            graph.set_edge_enabled(1, 2, false).unwrap();
1852            for round in 0..3_000_u64 {
1853                let node = 10 + round;
1854                graph.link(2, node).unwrap();
1855                assert!(graph.remove_node(node));
1856                graph.validate();
1857            }
1858            assert!(graph.engine_vertex_count() <= 2 * graph.node_count() + 1024);
1859            let storage = graph.storage_stats();
1860            assert_eq!(storage.catalog_nodes, graph.node_count());
1861            assert_eq!(storage.incident_entries, 2 * graph.edge_count());
1862            assert!(storage.incident_capacity >= storage.incident_entries);
1863            assert_eq!(
1864                storage.engine_vertices,
1865                storage.catalog_nodes + storage.retired_vertices
1866            );
1867            assert!(graph.connected(0, 1).unwrap());
1868            assert!(!graph.connected(0, 2).unwrap());
1869            assert_eq!(
1870                graph.edge_state(1, 2).map(|state| state.enabled),
1871                Some(false)
1872            );
1873        }
1874    }
1875
1876    /// Fresh-ID churn at constant size: tombstones never make the catalog grow;
1877    /// rebuilds happen and keep every entry, flag, incidence and connectivity.
1878    #[test]
1879    fn fresh_id_churn_rebuilds_the_catalog_instead_of_growing_it() {
1880        // 3,200 entries fill a 4,096-bucket table (capacity 3,584) to 78% of its buckets
1881        // and 89% of its capacity, as at 100,000 nodes (131,072 buckets: 76%, 87%):
1882        // removals leave tombstones, and live entries are within the 90% rebuild bound. A
1883        // lightly loaded table mostly frees slots outright and never needs a rebuild; above
1884        // 90% of capacity the table grows, as before.
1885        const N: u64 = 3_200;
1886        let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs).unwrap();
1887        for v in 0..N {
1888            graph.add_node(v).unwrap();
1889        }
1890        for v in 1..N {
1891            graph.link(0, v).unwrap();
1892        }
1893        graph.set_node_active(N - 1, false).unwrap();
1894        let full = graph.nodes.capacity();
1895        assert_eq!(graph.catalog_full_capacity, full);
1896        // Node 0 (the hub) and node N - 1 (inactive) stay; the others are churned.
1897        let mut live: std::collections::VecDeque<u64> = (1..N - 1).collect();
1898        let mut rebuilds = 0;
1899        for round in 0..(8 * N) {
1900            let before = graph.nodes.capacity();
1901            let old = live.pop_front().unwrap();
1902            assert!(graph.remove_node(old));
1903            let fresh = 10 * N + round;
1904            graph.link(0, fresh).unwrap();
1905            live.push_back(fresh);
1906            let after = graph.nodes.capacity();
1907            assert!(after <= full, "round {round}: the catalog grew to {after}");
1908            // A rebuild restores the headroom that tombstones had consumed: a jump
1909            // of more than one (a plain insert into a tombstone slot adds at most one).
1910            if after > before + 1 {
1911                rebuilds += 1;
1912            }
1913            if round % 1_024 == 0 {
1914                graph.validate();
1915            }
1916        }
1917        graph.validate();
1918        assert!(rebuilds > 0, "the churn produced no tombstone rebuild");
1919        assert_eq!(graph.catalog_full_capacity, full);
1920        assert_eq!(graph.node_count(), N as usize);
1921        assert_eq!(graph.node_active(N - 1), Some(false));
1922        assert!(graph.connected(0, *live.back().unwrap()).unwrap());
1923        assert!(!graph.connected(0, N - 1).unwrap());
1924    }
1925
1926    /// Growing the number of live entries still grows the catalog.
1927    #[test]
1928    fn live_growth_still_grows_the_catalog() {
1929        let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs).unwrap();
1930        for v in 0..1_000 {
1931            graph.add_node(v).unwrap();
1932        }
1933        let first = graph.nodes.capacity();
1934        for v in 1_000..10_000 {
1935            graph.add_node(v).unwrap();
1936        }
1937        assert!(graph.nodes.capacity() > first);
1938        assert!(graph.catalog_full_capacity >= graph.nodes.capacity());
1939        graph.validate();
1940    }
1941}