Expand description
Exact, in-memory dynamic connectivity for undirected simple graphs.
Knotrel maintains exact reachability queries (“is vertex u connected to vertex v
via some path?”) while edges are dynamically inserted and deleted over time.
It is a specialized dynamic connectivity engine, not a generic graph database.
§Graph Model
- Undirected simple graphs: Edges have no orientation and connect two distinct endpoints.
- 64-bit integer identifiers: Vertices are identified by
NodeId(u64). - No self-loops: Attempting to link a vertex to itself returns
GraphError::SelfLoop. - No multi-edges: Linking an already existing edge is an idempotent no-op returning
Ok(false). - Dynamic vertex registration: Calling
ConnectivityGraph::add_nodeexplicitly registers an isolated vertex; callingConnectivityGraph::linkimplicitly creates missing endpoints. - Cuts retain vertices: Calling
ConnectivityGraph::cutremoves the edge, but both endpoints remain registered in the graph universe.
§Quick Start
Add the latest published knotrel-core release to your project:
cargo add knotrel-coreBasic usage with ConnectivityGraph:
use knotrel_core::{ConnectivityGraph, EngineConfig};
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Create a graph using the default compact BFS engine.
let mut graph = ConnectivityGraph::new(EngineConfig::CompactBfs);
// Add nodes and link edges.
graph.add_node(1)?;
graph.add_node(2)?;
graph.link(1, 2)?;
graph.link(2, 3)?;
// Query connectivity.
assert!(graph.connected(1, 3)?);
// Cut an edge and observe the split.
assert!(graph.cut(2, 3)?);
assert!(!graph.connected(1, 3)?);
// Existing endpoints are preserved after cuts.
assert_eq!(graph.node_count(), 3);
Ok(())
}§Bulk Initialization
If you have existing vertex and edge collections, construct a graph using
ConnectivityGraph::try_from_edges:
use knotrel_core::{ConnectivityGraph, EngineConfig, GraphLimits};
let isolated_nodes = [99];
let edges = [(1, 2), (2, 3), (3, 4)];
let mut graph = ConnectivityGraph::try_from_edges(
EngineConfig::CompactBfs,
GraphLimits::default(),
&isolated_nodes,
&edges,
)?;
assert!(graph.connected(1, 4)?);
assert!(!graph.connected(1, 99)?);
// The resulting graph supports continued dynamic mutations:
graph.link(4, 99)?;
assert!(graph.connected(1, 99)?);Construction processes all explicit nodes first, then inserts edges in input order.
It is atomic with respect to publication: on the first validation error, the partially
constructed graph is dropped and the error is returned.
§Node and Edge Lifecycle
LifecycleGraph adds reversible node activation, reversible edge
enabling and permanent node removal on the compact-bfs engine (ett and
hdt lifecycle support is deferred and rejected with
LifecycleError::UnsupportedEngine). It keeps the registered
topology with flags and answers connectivity over the effective graph:
enabled edges whose endpoints are both active. ConnectivityGraph is
unchanged and carries no lifecycle bookkeeping.
use knotrel_core::{EngineConfig, LifecycleGraph};
let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs)?;
graph.link(1, 2)?;
graph.set_edge_enabled(1, 2, false)?;
assert!(!graph.connected(1, 2)?);
assert_eq!(graph.edge_count(), 1);
assert_eq!(graph.effective_edge_count(), 0);§Listing Neighbors (since 0.8)
Neighbors can be listed page by page with a cursor, for browsing tools.
On compact-bfs, Graph::neighbors_after needs a one-time opt-in
(ConnectivityGraph::enable_neighbor_listing, O(V)) because it keeps an
index-to-ID vector (8 bytes per node) that ordinary use does not need.
LifecycleGraph::incident_after lists neighbors with their edge state,
in ascending neighbor ID. A cursor is the last neighbor returned; pages are
not a snapshot of a graph that changes between them.
use knotrel_core::{ConnectivityGraph, EngineConfig};
let mut graph = ConnectivityGraph::new(EngineConfig::CompactBfs);
graph.link(1, 2)?;
graph.link(1, 3)?;
assert!(graph.enable_neighbor_listing());
let compact = graph.as_compact().expect("compact-bfs engine");
assert_eq!(compact.degree(1), Some(2));
let first: Vec<_> = compact.neighbors_after(1, None)?.take(1).collect();
let rest: Vec<_> = compact.neighbors_after(1, first.last().copied())?.collect();
assert_eq!(first.len() + rest.len(), 2);§Listing Every Node and Edge (experimental, since 1.3)
ConnectivityGraph::for_each_node and ConnectivityGraph::for_each_edge
visit every node and every undirected edge (low < high) once, in
unspecified order, on every engine. LifecycleGraph::for_each_node and
LifecycleGraph::for_each_edge also report each node’s active and each
edge’s enabled flag. They are bulk reads for snapshots and exports,
O(V + E), and are classified Experimental.
§Choosing a Backend Engine
Knotrel provides four dynamic connectivity engines through EngineConfig; every engine
returns the same exact answers. The canonical selection guide, with the 1.1 qualification
results, is Choosing an engine.
§Algorithmic Complexity and API Assumptions
The asymptotic costs in the table below describe the core graph and forest algorithms
operating on internal indices. The public API maps external 64-bit NodeId keys to internal
indices using hash maps (FxHash, and an ID-folding hasher for Graph), which rely on
expected O(1) lookups and do not provide deterministic worst-case constant-time bounds for
arbitrary ID distributions.
Furthermore, collection and arena vector growth is amortized; a single vertex insertion or
capacity reallocation may take O(V) in the worst case.
| Engine | Configuration | Query Cost | Link Cost | Cut Cost | Logical Memory |
|---|---|---|---|---|---|
| Compact BFS (Default) | EngineConfig::CompactBfs | O(V + E) worst-case | O(deg(u) + deg(v)) amortized | O(deg(u) + deg(v)) worst-case | O(V + E) |
| Euler Tour Trees (ETT) | EngineConfig::EulerTour | O(log V) algorithmically | O(log V + log E) amortized | O(log V + log E + s + c log V) amortized | O(V + E) |
| HDT | EngineConfig::Hdt | O(log V) algorithmically | O(log V) amortized | O(log² V) amortized | O(E + V log V) |
| Cluster forest (new in 1.1, experimental) | EngineConfig::ClusterForest | O(log N) worst-case | O(log N) actual | O(log² N) amortized (project derivation) | O(V + E) |
N is the high-water vertex count. Note on memory: O(V + E) and O(E + V log V) represent logical graph entity storage.
Allocated memory capacities are retained after cuts and do not bound process heap memory or RSS.
§1. Compact BFS (EngineConfig::CompactBfs)
- Algorithmic properties: Represents adjacency as compact, sorted vectors of stable internal indices.
Queries perform a fresh breadth-first traversal in
O(V + E)worst-case time usingO(V)temporary scratch space. Link and cut shift sorted vectors inO(deg(u) + deg(v))time. Adding a vertex can trigger anO(V)outer-vector reallocation. - Workload expectations: Contiguous memory layout and low allocation overhead. Suitable as a general-purpose engine when mutations are frequent or graph components are small-to-moderate in size.
§2. Euler Tour Trees (EngineConfig::EulerTour)
- Algorithmic properties: Maintains a spanning forest using AVL-balanced Euler tour sequences.
Reachability queries compare tour roots in
O(log V)algorithmic steps without graph traversals. Non-tree edge cuts takeO(log V + log E)amortized time. Tree cuts partition the tree and scan non-tree edges of the smaller component (svertices,ccandidate edges) using candidate-pruned subtrees; this search costsO(log V + log E + s + c log V)amortized and allocatesO(s)scratch space. - Workload expectations: Effective for query-dominated workloads and tree-like topologies where bridge cuts rarely split large components. Because it lacks edge-level hierarchies, repeated bridge cuts in dense cyclic components can trigger repeated scans over the same non-tree edges.
§3. Holm–de Lichtenberg–Thorup (EngineConfig::Hdt)
- Algorithmic properties: Experimental deterministic implementation based on Holm, de Lichtenberg, and
Thorup (2001), extended with an append-only growth policy for expanding vertex universes.
Maintains a hierarchy of
O(log V)levels, materializing upper levels lazily as edge promotions require them. Queries run on the base level inO(log V)algorithmic steps. Tree cuts search for replacement edges starting at the cut edge’s level downwards; examined tree edges and non-tree edges on the smaller component are promoted to upper levels, bounding the amortized update cost toO(log² V)across operation sequences. - Workload expectations: Designed to prevent repeated scan storms in dense graphs undergoing frequent bridge cuts. However, its amortized bounds represent sequence averages rather than worst-case per-request latency guarantees; large individual promotion passes or vector reallocations can cause latency spikes, and it may have higher constant factors on small or sparse graphs; verify against your actual workload.
§4. Cluster forest (EngineConfig::ClusterForest, new in 1.1, experimental)
- Algorithmic properties: Experimental sequential cluster forest of Wulff-Nilsen (SODA 2013, §3) with the
path compression of De Man et al. (PVLDB 2025, §4) and insertion at the lowest common cluster. Edges carry
levels; clusters are the components of each level and are stored only where an edge of their level lies
inside them. Queries walk both vertices to their roots. A deletion runs two alternating searches from the
endpoints’ clusters, pushes the explored edges of the smaller side one level down and splits clusters when
no replacement exists. The
O(log² N)amortized update bound is this project’s derivation for this variant (ADR 0014), not a published theorem; the sources state it for related variants only. At most 2²⁸ vertices and edges. Also supported byLifecycleGraph. The backend type is internal. - Workload expectations (1.1 qualification, CF5: one host, candidate
02cba68, the measured workloads only; results): much faster than Compact BFS where Compact BFS answers queries by search (server mixed traffic, the components and hub families), faster than every other engine on dense bridge churn, and faster than ETT and HDT on construction; slower than Compact BFS on updates and construction, with more memory, and slower than all three on path- and ring-like bridge churn. Under sustained lifecycle churn on a sparse 1 000-node graph two heap-growth checks failed (projected growth, a documented limitation). It stays experimental and Compact BFS stays the default. See the selection guide.
use knotrel_core::{ConnectivityGraph, EngineConfig, GraphError};
fn main() -> Result<(), GraphError> {
let mut graph = ConnectivityGraph::new(EngineConfig::ClusterForest);
graph.link(1, 2)?;
graph.link(2, 3)?;
assert!(graph.connected(1, 3)?);
graph.cut(2, 3)?;
assert!(!graph.connected(1, 3)?);
assert!(graph.engine().is_experimental());
Ok(())
}With node and edge lifecycle:
use knotrel_core::{EngineConfig, LifecycleGraph};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut graph = LifecycleGraph::new(EngineConfig::ClusterForest)?;
for (u, v) in [(1, 2), (2, 4), (1, 3), (3, 4)] {
graph.link(u, v)?;
}
graph.set_node_active(2, false)?;
assert!(graph.connected(1, 4)?); // through 3
graph.set_node_active(3, false)?;
assert!(!graph.connected(1, 4)?);
graph.set_node_active(2, true)?;
assert!(graph.connected(1, 4)?); // the edges of 2 are back
Ok(())
}§Pragmatic Guidance
- No universal winner: Micro-benchmarks demonstrate that no single engine dominates across all graph topologies and operation mixes.
- Empirical evaluation: If your workload characteristics (topology, scale, mutation mix) are uncertain, profile empirically rather than assuming polylogarithmic engines will outperform Compact BFS.
- Starting point: Start with Compact BFS (
EngineConfig::CompactBfs); evaluate ETT (EngineConfig::EulerTour) for query-dominated workloads on tree-like graphs, HDT (EngineConfig::Hdt) for workloads with repeated bridge replacement searches, or cluster forest (EngineConfig::ClusterForest) for query-heavy workloads where Compact BFS searches, also withLifecycleGraph, measuring actual topology, scale, and mutation mix. To go back, construct the graph withEngineConfig::CompactBfs; there is no in-place conversion.
§Error and Resource Limit Handling
All operations that may fail return Result<T, GraphError>. The possible errors in GraphError are:
GraphError::SelfLoop: The source and target node identifiers were identical.GraphError::UnknownNode: A reachability query referenced a vertex that was never added or linked.GraphError::NodeLimitExceeded: A mutation would exceed the configuredGraphLimits::max_nodes.GraphError::EdgeLimitExceeded: A mutation would exceed the configuredGraphLimits::max_edges.
§Cardinality Limits vs. Memory
GraphLimits enforce strict ceilings on registered vertex and live edge counts.
These limits bound logical graph cardinality, not allocator heap memory or process RSS.
Rejected mutations leave the graph completely unmodified.
§Guarantees and Limitations
- Exact answers: Knotrel computes exact connectivity; answers are never heuristic or approximate.
- Synchronous execution: All graph algorithms execute synchronously on the caller’s thread.
- Zero internal locking: Graphs do not contain internal mutexes. For concurrent multi-threaded access,
wrap
ConnectivityGraphin standard Rust synchronization primitives (such asstd::sync::Mutexorstd::sync::RwLock). - In-memory volatile state: Graph data lives solely in memory. There is no write-ahead log (WAL), disk persistence, or crash recovery.
- No generic graph properties: Knotrel is not an attributed property graph; it does not store node labels, edge weights, directed edges, or multi-edges.
- Stability classes: every public item is classified stable, experimental or internal in the
stability classification. Stable items change
only as the compatibility policy allows,
after a deprecation. The ETT engine (
EngineConfig::EulerTour,ForestGraph,ForestStats) and the HDT engine (EngineConfig::Hdt,HdtGraph,HdtStats,HdtStorageStats,HdtLevelStorage) are stable interfaces with an experimental engine: their public API stays compatible across 1.x, while their performance, maturity and usage recommendation carry no promise (EngineConfig::is_experimentalreturnstrue).EngineConfig::ClusterForest(new in 1.1) is a stable interface with an experimental engine too; its backend type is not exported.LifecycleStorageis stable. For these diagnostic structs, the fields, units and the properties their documentation lists as guaranteed are stable; the exact values are implementation-dependent.ReferenceGraphis an internal test oracle.
Structs§
- BfsWorkspace
- Reusable temporary storage for
Graph::connected_with_workspace. - Connectivity
Graph - An owned graph with an explicitly selected, immutable implementation.
- Edge
Spec - One registered undirected edge for
LifecycleGraph::try_from_topology. - Edge
State - Flags of one registered edge, returned by
LifecycleGraph::edge_state. - Forest
Graph - Exact connectivity with deterministic Euler-tour trees.
- Forest
Stats - Cumulative replacement-search work, from
ForestGraph::stats. - Graph
- An undirected simple graph with compact adjacency and exact BFS queries.
- Graph
Limits - Immutable cardinality ceilings for one graph instance.
- HdtGraph
- Exact connectivity using deterministic HDT levels and AVL tours.
- HdtLevel
Storage - Storage and live incidences of one materialized HDT level, an element of
HdtStorageStats::levels. - HdtStats
- Cumulative HDT repair work, from
HdtGraph::stats. - HdtStorage
Stats - Structural storage snapshot of an
crate::HdtGraph, fromcrate::HdtGraph::storage_stats, collected outside timed graph operations. - Lifecycle
Graph - A graph with reversible node activation, reversible edge enabling and permanent node removal.
- Lifecycle
Storage - Storage diagnostics of a
LifecycleGraph, fromLifecycleGraph::storage_stats. - Node
Spec - One registered node for
LifecycleGraph::try_from_topology. - Reference
Graph - An undirected simple graph with exact connectivity queries.
Enums§
- Engine
Config - The implementation chosen when creating a graph.
- Graph
Error - An invalid graph operation.
- Incidence
Error - Why an incidence listing could not start.
- Lifecycle
Error - Errors returned by lifecycle-specific
LifecycleGraphoperations.
Type Aliases§
- NodeId
- A vertex identifier.