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
//! 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_node`] explicitly registers an isolated vertex;
//! calling [`ConnectivityGraph::link`] implicitly creates missing endpoints.
//! - **Cuts retain vertices**: Calling [`ConnectivityGraph::cut`] removes the edge, but both endpoints
//! remain registered in the graph universe.
//!
//! # Quick Start
//!
//! Add the latest published `knotrel-core` release to your project:
//!
//! ```sh
//! cargo add knotrel-core
//! ```
//!
//! Basic usage with [`ConnectivityGraph`]:
//!
//! ```rust
//! 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`]:
//!
//! ```rust
//! 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)?);
//! # Ok::<(), knotrel_core::GraphError>(())
//! ```
//!
//! 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.
//!
//! ```rust
//! 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);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! # Choosing a Backend Engine
//!
//! Knotrel provides three underlying dynamic connectivity engines through [`EngineConfig`].
//!
//! ### 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 (`IntMap` / `FxHashMap`), 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)` |
//!
//! *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 using `O(V)` temporary scratch space.
//! Link and cut shift sorted vectors in `O(deg(u) + deg(v))` time. Adding a vertex can trigger an `O(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 take `O(log V + log E)` amortized time. Tree cuts partition the tree and scan non-tree edges of the smaller
//! component (`s` vertices, `c` candidate edges) using candidate-pruned subtrees; this search costs
//! `O(log V + log E + s + c log V)` amortized and allocates `O(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 in `O(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 to `O(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.
//!
//! ### 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 or HDT ([`EngineConfig::Hdt`]) for workloads with repeated bridge replacement searches,
//! measuring actual topology, scale, and mutation mix.
//!
//! # 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 configured [`GraphLimits::max_nodes`].
//! - [`GraphError::EdgeLimitExceeded`]: A mutation would exceed the configured [`GraphLimits::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 [`ConnectivityGraph`] in standard Rust synchronization primitives (such as `std::sync::Mutex` or `std::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.
//! - **Pre-1.0 stability**: APIs are subject to refinement before 1.0 based on user adoption feedback.
use FixedBitSet;
use IntMap;
use ;
pub use BfsWorkspace;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ReferenceGraph;
pub use ;
/// A vertex identifier.
pub type NodeId = u64;
/// An invalid graph operation.
/// An undirected simple graph with compact adjacency and exact BFS queries.
///
/// External IDs map to stable, append-only indices. Each sorted adjacency vector
/// contains unique indices, and every edge appears at both endpoints. Cuts retain
/// vertices. Logical storage is O(V + E). Allocated storage is O(V + H), where H is
/// the sum of per-vertex historical maximum degrees (capacity is retained). No query answers are cached.