knotrel-core 1.2.0

Exact in-memory connectivity for undirected graphs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! Explicit engine selection, independent of any transport or environment.

use crate::{ForestGraph, Graph, GraphError, HdtGraph, NodeId, cluster_forest::ClusterForestGraph};

/// Immutable cardinality ceilings for one graph instance.
///
/// `None` is unlimited (the default); zero forbids new entries. Cuts retain
/// vertices. These limits do not bound allocator capacity or resident memory.
/// Enforced by [`ConnectivityGraph`]; raw algorithm types remain unlimited.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GraphLimits {
    /// Maximum registered vertices, including isolated vertices.
    pub max_nodes: Option<usize>,
    /// Maximum live undirected edges.
    pub max_edges: Option<usize>,
}

/// The implementation chosen when creating a graph.
///
/// Selection is immutable for the lifetime of a [`ConnectivityGraph`].
/// No automatic switching or answer cache is introduced by this configuration.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum EngineConfig {
    /// Compact adjacency with a fresh BFS for each connectivity query.
    #[default]
    CompactBfs,
    /// Euler-tour forest with candidate-pruned replacement search: a stable
    /// interface for an experimental engine.
    ///
    /// This is not HDT and does not provide polylogarithmic update bounds.
    /// The variant, its selector `"ett"` ([`EngineConfig::as_str`]) and the
    /// [`ForestGraph`] API stay compatible across 1.x, like
    /// [`EngineConfig::Hdt`]: they are removed or renamed only after a
    /// deprecation and in a major release, and `#[non_exhaustive]` on this
    /// enum does not authorize removing them. "Experimental" qualifies only the
    /// engine's performance, maturity and usage recommendation
    /// ([`EngineConfig::is_experimental`] returns `true`).
    EulerTour,
    /// Deterministic HDT with level-based replacement search: a stable
    /// interface for an experimental engine.
    ///
    /// The variant, its selector `"hdt"` ([`EngineConfig::as_str`]) and the
    /// [`HdtGraph`] API stay compatible across 1.x: they are removed or
    /// renamed only after a deprecation and in a major release, and
    /// `#[non_exhaustive]` on this enum does not authorize removing them.
    /// "Experimental" qualifies only the engine's performance, maturity and
    /// usage recommendation ([`EngineConfig::is_experimental`] returns `true`):
    /// it carries no performance, latency or memory promise, lifecycle support
    /// is not available, and [`EngineConfig::CompactBfs`] remains the default.
    Hdt,
    /// Cluster forest (Wulff-Nilsen, SODA 2013, §3, with the path compression
    /// of De Man et al., PVLDB 2025, §4): a stable interface for an
    /// experimental engine, new in 1.1.
    ///
    /// The variant and its selector `"cluster-forest"`
    /// ([`EngineConfig::as_str`]) stay compatible across 1.x like
    /// [`EngineConfig::EulerTour`] and [`EngineConfig::Hdt`]: they are
    /// removed or renamed only after a deprecation and in a major release,
    /// and `#[non_exhaustive]` on this enum does not authorize removing them.
    /// "Experimental" qualifies only the engine's performance, maturity and
    /// usage recommendation ([`EngineConfig::is_experimental`] returns
    /// `true`): it carries no performance, latency or memory promise, and
    /// [`EngineConfig::CompactBfs`] remains the default. The backend type
    /// itself is internal: use the engine through [`ConnectivityGraph`] or
    /// [`crate::LifecycleGraph`], which supports it.
    ///
    /// Updates are `O(log² N)` amortized by this project's derivation for
    /// this variant (ADR 0014), not by a published theorem; queries walk to
    /// the roots in `O(log N)`. It accepts at most 2²⁸ vertices and 2²⁸ edges
    /// and reports more as [`GraphError::NodeLimitExceeded`] or
    /// [`GraphError::EdgeLimitExceeded`] carrying that limit (or the
    /// configured [`GraphLimits`] value, when lower). Under
    /// [`crate::LifecycleGraph`] the enforced limits are 2²⁷ − 512 nodes and
    /// 2²⁸ edges, leaving room for retired slots. Through
    /// [`ConnectivityGraph`] the configured limits are checked first (node
    /// before edge), then the engine's capacity: at that capacity a
    /// configured edge limit can therefore be reported before the engine's
    /// node capacity.
    ClusterForest,
}

impl EngineConfig {
    /// Returns the stable external selector for this engine.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::CompactBfs => "compact-bfs",
            Self::EulerTour => "ett",
            Self::Hdt => "hdt",
            Self::ClusterForest => "cluster-forest",
        }
    }

    /// Whether this engine is qualified as experimental: its performance,
    /// maturity and usage recommendation carry no promise, although its
    /// public interface may be stable.
    ///
    /// Returns `false` for [`EngineConfig::CompactBfs`] and `true` for
    /// [`EngineConfig::EulerTour`], [`EngineConfig::Hdt`] and
    /// [`EngineConfig::ClusterForest`] in this release. The value for the
    /// experimental engines may stay `true` for the whole 1.x
    /// series; it becomes `false` only when an engine is promoted, in a minor
    /// release that records it in the release notes, and it never changes
    /// from `false` to `true` for an existing engine. The value says nothing about the interface's
    /// stability class: both variants are stable interfaces either way. The
    /// server reports the same value as the `experimental` field of
    /// `GET /v1/info`.
    ///
    /// # Examples
    ///
    /// ```
    /// use knotrel_core::EngineConfig;
    ///
    /// assert!(!EngineConfig::CompactBfs.is_experimental());
    /// assert!(EngineConfig::EulerTour.is_experimental());
    /// assert!(EngineConfig::Hdt.is_experimental());
    /// assert!(EngineConfig::ClusterForest.is_experimental());
    /// assert_eq!(EngineConfig::Hdt.as_str(), "hdt");
    /// assert_eq!(EngineConfig::ClusterForest.as_str(), "cluster-forest");
    /// ```
    pub fn is_experimental(self) -> bool {
        matches!(self, Self::EulerTour | Self::Hdt | Self::ClusterForest)
    }
}

/// An owned graph with an explicitly selected, immutable implementation.
///
/// All engines preserve the [`Graph`] operation contract, including growing
/// `u64` IDs and retained vertices after cuts. This wrapper adds constant-time
/// enum dispatch; operation costs are those of [`Graph`], [`ForestGraph`], [`HdtGraph`]
/// or the internal cluster forest ([`EngineConfig::ClusterForest`]).
/// It reads no environment variables or files and performs no internal locking.
///
/// ```
/// use knotrel_core::{ConnectivityGraph, EngineConfig};
/// let mut graph = ConnectivityGraph::new(EngineConfig::EulerTour);
/// graph.link(1, u64::MAX)?;
/// assert!(graph.connected(1, u64::MAX)?);
/// # Ok::<(), knotrel_core::GraphError>(())
/// ```
#[derive(Debug)]
pub struct ConnectivityGraph {
    backend: Backend,
    limits: GraphLimits,
}

#[derive(Debug)]
enum Backend {
    Compact(Graph),
    EulerTour(ForestGraph),
    Hdt(HdtGraph),
    /// Boxed: the backend keeps reusable search buffers inline.
    ClusterForest(Box<ClusterForestGraph>),
}

impl Default for ConnectivityGraph {
    fn default() -> Self {
        Self::new(EngineConfig::default())
    }
}

impl From<Graph> for ConnectivityGraph {
    /// Takes ownership without rebuilding or losing existing graph state.
    fn from(graph: Graph) -> Self {
        Self {
            backend: Backend::Compact(graph),
            limits: GraphLimits::default(),
        }
    }
}

impl ConnectivityGraph {
    /// Creates an empty graph. Every typed configuration is supported.
    pub fn new(config: EngineConfig) -> Self {
        Self::with_limits(config, GraphLimits::default())
    }

    /// Creates an empty graph with immutable cardinality ceilings.
    pub fn with_limits(config: EngineConfig, limits: GraphLimits) -> Self {
        Self {
            limits,
            backend: match config {
                EngineConfig::CompactBfs => Backend::Compact(Graph::new()),
                EngineConfig::EulerTour => Backend::EulerTour(ForestGraph::new()),
                EngineConfig::Hdt => Backend::Hdt(HdtGraph::new()),
                EngineConfig::ClusterForest => {
                    Backend::ClusterForest(Box::new(ClusterForestGraph::new()))
                }
            },
        }
    }

    /// Builds an owned graph by registering `nodes`, then inserting `edges`,
    /// in the supplied order using [`Self::add_node`] and [`Self::link`].
    ///
    /// Duplicate nodes and duplicate/reversed edges are no-ops, including at
    /// capacity. Edges create missing endpoints; `nodes` is not a closed universe.
    /// Empty inputs, isolated vertices and disconnected components are valid.
    /// The returned graph supports the same subsequent dynamic operations and
    /// retains the selected engine and limits.
    ///
    /// Construction is atomic with respect to publication: on error the local
    /// graph is dropped, not returned partially built. This is not an in-place
    /// batch or snapshot restore, and returns no per-item change flags.
    ///
    /// Work and allocation behavior are those of the ordered incremental calls;
    /// the constructor adds O(nodes.len() + edges.len()) iteration overhead and
    /// O(1) auxiliary space. It does not reserve, sort or stage the input.
    /// No performance improvement is promised.
    ///
    /// # Errors
    ///
    /// Returns the first [`GraphError`] from the ordered calls: all explicit
    /// nodes precede every edge; each edge checks self-loop, node limit, then
    /// edge limit. Later invalid input is not inspected ahead of that error.
    /// Limits bound cardinality, not memory. As with incremental construction,
    /// allocation failure is not a recoverable `GraphError`; collection capacity
    /// overflow may panic and memory exhaustion may abort.
    ///
    /// ```
    /// use knotrel_core::{ConnectivityGraph, EngineConfig, GraphLimits};
    /// let mut graph = ConnectivityGraph::try_from_edges(
    ///     EngineConfig::EulerTour,
    ///     GraphLimits::default(),
    ///     &[99, 99],
    ///     &[(1, 2), (2, 1), (2, 3)],
    /// )?;
    /// assert_eq!(graph.node_count(), 4);
    /// assert_eq!(graph.edge_count(), 2);
    /// assert!(graph.connected(1, 3)?);
    /// assert!(!graph.connected(99, 1)?);
    /// assert!(graph.cut(2, 3)?);
    /// assert!(!graph.connected(1, 3)?);
    /// # Ok::<(), knotrel_core::GraphError>(())
    /// ```
    pub fn try_from_edges(
        engine: EngineConfig,
        limits: GraphLimits,
        nodes: &[NodeId],
        edges: &[(NodeId, NodeId)],
    ) -> Result<Self, GraphError> {
        let mut graph = Self::with_limits(engine, limits);
        for &node in nodes {
            graph.add_node(node)?;
        }
        for &(source, target) in edges {
            graph.link(source, target)?;
        }
        Ok(graph)
    }

    /// Returns the immutable limits configured for this instance, as passed
    /// at construction.
    ///
    /// They are the enforced limits for every engine except
    /// [`EngineConfig::ClusterForest`], whose own capacity (2²⁸ vertices and
    /// 2²⁸ edges) also applies: when it is lower, the error carries the
    /// capacity instead of the configured value, which this method still
    /// returns.
    pub fn limits(&self) -> GraphLimits {
        self.limits
    }

    /// Returns the engine that actually owns this graph's state.
    pub fn engine(&self) -> EngineConfig {
        match &self.backend {
            Backend::Compact(_) => EngineConfig::CompactBfs,
            Backend::EulerTour(_) => EngineConfig::EulerTour,
            Backend::Hdt(_) => EngineConfig::Hdt,
            Backend::ClusterForest(_) => EngineConfig::ClusterForest,
        }
    }

    /// Releases the adjacency storage of an isolated vertex (`compact-bfs`
    /// only; a no-op for the other engines and for a vertex with edges).
    pub(crate) fn release_isolated_storage(&mut self, node: NodeId) {
        if let Backend::Compact(graph) = &mut self.backend {
            graph.release_isolated_storage(node);
        }
    }

    /// Returns the adjacency capacity held by `node` (`compact-bfs` only).
    #[cfg(test)]
    pub(crate) fn adjacency_capacity(&self, node: NodeId) -> Option<usize> {
        match &self.backend {
            Backend::Compact(graph) => graph.adjacency_capacity(node),
            _ => None,
        }
    }

    /// Reports whether `node` is registered, in expected O(1) time with every
    /// engine.
    ///
    /// Limit checks use this ID-map lookup instead of a reflexive
    /// [`Self::connected`] query, which costs O(log V) tree-root walks on the
    /// Euler-tour and HDT engines.
    ///
    /// ```rust
    /// use knotrel_core::{ConnectivityGraph, EngineConfig};
    ///
    /// let mut graph = ConnectivityGraph::new(EngineConfig::Hdt);
    /// graph.add_node(u64::MAX)?;
    /// assert!(graph.contains_node(u64::MAX));
    /// assert!(!graph.contains_node(1));
    /// # Ok::<(), knotrel_core::GraphError>(())
    /// ```
    #[must_use]
    pub fn contains_node(&self, node: NodeId) -> bool {
        match &self.backend {
            Backend::Compact(graph) => graph.contains_node(node),
            Backend::EulerTour(graph) => graph.contains_node(node),
            Backend::Hdt(graph) => graph.contains_node(node),
            Backend::ClusterForest(graph) => graph.contains_node(node),
        }
    }

    /// Adds a vertex; returns whether it was absent.
    /// # Errors
    /// Returns [`GraphError::NodeLimitExceeded`] without mutation at capacity.
    /// An existing vertex always returns `Ok(false)`.
    pub fn add_node(&mut self, node: NodeId) -> Result<bool, GraphError> {
        if let Some(limit) = self.limits.max_nodes {
            if self.contains_node(node) {
                return Ok(false);
            }
            if self.node_count() >= limit {
                return Err(GraphError::NodeLimitExceeded { limit });
            }
        }
        Ok(match &mut self.backend {
            Backend::Compact(graph) => graph.add_node(node),
            Backend::EulerTour(graph) => graph.add_node(node),
            Backend::Hdt(graph) => graph.add_node(node),
            Backend::ClusterForest(graph) => graph.add_node(node)?,
        })
    }

    /// Adds an undirected edge, creating absent endpoints.
    ///
    /// Returns whether the edge was absent. A self-loop returns
    /// [`GraphError::SelfLoop`] without creating its endpoint.
    /// Limit checks precede all mutation; node limits take precedence over edge
    /// limits. Duplicate edges succeed unchanged even at capacity. Each check
    /// uses expected O(1) ID-map lookups, never a graph traversal, tree-root
    /// walk or speculative insert.
    /// # Errors
    /// Self-loops or cardinality violations leave the entire graph unchanged.
    pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        if source == target {
            return Err(GraphError::SelfLoop { node: source });
        }
        if let Some(limit) = self.limits.max_nodes {
            let missing =
                usize::from(!self.contains_node(source)) + usize::from(!self.contains_node(target));
            if missing > limit.saturating_sub(self.node_count()) {
                return Err(GraphError::NodeLimitExceeded { limit });
            }
        }
        if let Some(limit) = self.limits.max_edges
            && self.edge_count() >= limit
        {
            let exists = match &self.backend {
                Backend::Compact(g) => g.contains_edge(source, target),
                Backend::EulerTour(g) => g.contains_edge(source, target),
                Backend::Hdt(g) => g.contains_edge(source, target),
                Backend::ClusterForest(g) => g.contains_edge(source, target),
            };
            return if exists {
                Ok(false)
            } else {
                Err(GraphError::EdgeLimitExceeded { limit })
            };
        }
        match &mut self.backend {
            Backend::Compact(graph) => graph.link(source, target),
            Backend::EulerTour(graph) => graph.link(source, target),
            Backend::Hdt(graph) => graph.link(source, target),
            Backend::ClusterForest(graph) => graph.link(source, target),
        }
    }

    /// Removes an edge while retaining vertices.
    ///
    /// Returns false for an absent edge or endpoint. A self-loop returns
    /// [`GraphError::SelfLoop`].
    pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        match &mut self.backend {
            Backend::Compact(graph) => graph.cut(source, target),
            Backend::EulerTour(graph) => graph.cut(source, target),
            Backend::Hdt(graph) => graph.cut(source, target),
            Backend::ClusterForest(graph) => graph.cut(source, target),
        }
    }

    /// Returns exact connectivity in the current graph.
    ///
    /// Returns [`GraphError::UnknownNode`] for an absent endpoint, checking
    /// the source first. A known vertex is connected to itself.
    pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        match &self.backend {
            Backend::Compact(graph) => graph.connected(source, target),
            Backend::EulerTour(graph) => graph.connected(source, target),
            Backend::Hdt(graph) => graph.connected(source, target),
            Backend::ClusterForest(graph) => graph.connected(source, target),
        }
    }

    /// Enables neighbor listing on the [`Graph`] engine
    /// ([`Graph::enable_neighbor_listing`]); does nothing for the experimental
    /// engines, which cannot list neighbors. Returns whether listing is
    /// available.
    pub fn enable_neighbor_listing(&mut self) -> bool {
        match &mut self.backend {
            Backend::Compact(graph) => {
                graph.enable_neighbor_listing();
                true
            }
            Backend::EulerTour(_) | Backend::Hdt(_) | Backend::ClusterForest(_) => false,
        }
    }

    /// Returns the [`Graph`] engine when this graph uses
    /// [`EngineConfig::CompactBfs`], for adjacency inspection with
    /// [`Graph::degree`] and [`Graph::neighbors_after`]. The experimental engines
    /// keep no per-node adjacency list, so they return `None`.
    ///
    /// ```rust
    /// use knotrel_core::{ConnectivityGraph, EngineConfig};
    ///
    /// let mut graph = ConnectivityGraph::new(EngineConfig::CompactBfs);
    /// graph.link(1, 2)?;
    /// assert_eq!(graph.as_compact().and_then(|g| g.degree(1)), Some(1));
    /// assert!(graph.enable_neighbor_listing());
    /// assert!(!ConnectivityGraph::new(EngineConfig::Hdt).enable_neighbor_listing());
    /// assert!(ConnectivityGraph::new(EngineConfig::EulerTour).as_compact().is_none());
    /// # Ok::<(), knotrel_core::GraphError>(())
    /// ```
    #[must_use]
    pub fn as_compact(&self) -> Option<&Graph> {
        match &self.backend {
            Backend::Compact(graph) => Some(graph),
            Backend::EulerTour(_) | Backend::Hdt(_) | Backend::ClusterForest(_) => None,
        }
    }

    /// Returns the number of registered vertices.
    pub fn node_count(&self) -> usize {
        match &self.backend {
            Backend::Compact(graph) => graph.node_count(),
            Backend::EulerTour(graph) => graph.node_count(),
            Backend::Hdt(graph) => graph.node_count(),
            Backend::ClusterForest(graph) => graph.node_count(),
        }
    }

    /// Returns the number of undirected edges.
    pub fn edge_count(&self) -> usize {
        match &self.backend {
            Backend::Compact(graph) => graph.edge_count(),
            Backend::EulerTour(graph) => graph.edge_count(),
            Backend::Hdt(graph) => graph.edge_count(),
            Backend::ClusterForest(graph) => graph.edge_count(),
        }
    }
}

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

    /// Releasing storage is a no-op for a vertex with edges, for an absent
    /// node and for engines other than `compact-bfs`, which report no
    /// adjacency capacity.
    #[test]
    fn release_isolated_storage_is_a_no_op_outside_isolated_compact_vertices() {
        let mut compact = ConnectivityGraph::new(EngineConfig::CompactBfs);
        for leaf in 1..=8 {
            compact.link(0, leaf).unwrap();
        }
        let before = compact.adjacency_capacity(0).unwrap();
        compact.release_isolated_storage(0);
        assert_eq!(compact.adjacency_capacity(0), Some(before));
        compact.release_isolated_storage(99);
        assert_eq!(compact.adjacency_capacity(99), None);
        assert!(compact.connected(0, 8).unwrap());

        for engine in [
            EngineConfig::EulerTour,
            EngineConfig::Hdt,
            EngineConfig::ClusterForest,
        ] {
            let mut other = ConnectivityGraph::new(engine);
            other.add_node(5).unwrap();
            other.release_isolated_storage(5);
            assert_eq!(other.adjacency_capacity(5), None);
            assert!(other.contains_node(5));
        }
    }
}