knotrel_core/lib.rs
1//! Exact, in-memory dynamic connectivity for undirected simple graphs.
2//!
3//! Knotrel maintains exact reachability queries ("is vertex `u` connected to vertex `v`
4//! via some path?") while edges are dynamically inserted and deleted over time.
5//! It is a specialized dynamic connectivity engine, not a generic graph database.
6//!
7//! # Graph Model
8//!
9//! - **Undirected simple graphs**: Edges have no orientation and connect two distinct endpoints.
10//! - **64-bit integer identifiers**: Vertices are identified by [`NodeId`] (`u64`).
11//! - **No self-loops**: Attempting to link a vertex to itself returns [`GraphError::SelfLoop`].
12//! - **No multi-edges**: Linking an already existing edge is an idempotent no-op returning `Ok(false)`.
13//! - **Dynamic vertex registration**: Calling [`ConnectivityGraph::add_node`] explicitly registers an isolated vertex;
14//! calling [`ConnectivityGraph::link`] implicitly creates missing endpoints.
15//! - **Cuts retain vertices**: Calling [`ConnectivityGraph::cut`] removes the edge, but both endpoints
16//! remain registered in the graph universe.
17//!
18//! # Quick Start
19//!
20//! Add the latest published `knotrel-core` release to your project:
21//!
22//! ```sh
23//! cargo add knotrel-core
24//! ```
25//!
26//! Basic usage with [`ConnectivityGraph`]:
27//!
28//! ```rust
29//! use knotrel_core::{ConnectivityGraph, EngineConfig};
30//!
31//! fn main() -> Result<(), Box<dyn std::error::Error>> {
32//! // Create a graph using the default compact BFS engine.
33//! let mut graph = ConnectivityGraph::new(EngineConfig::CompactBfs);
34//!
35//! // Add nodes and link edges.
36//! graph.add_node(1)?;
37//! graph.add_node(2)?;
38//! graph.link(1, 2)?;
39//! graph.link(2, 3)?;
40//!
41//! // Query connectivity.
42//! assert!(graph.connected(1, 3)?);
43//!
44//! // Cut an edge and observe the split.
45//! assert!(graph.cut(2, 3)?);
46//! assert!(!graph.connected(1, 3)?);
47//!
48//! // Existing endpoints are preserved after cuts.
49//! assert_eq!(graph.node_count(), 3);
50//!
51//! Ok(())
52//! }
53//! ```
54//!
55//! # Bulk Initialization
56//!
57//! If you have existing vertex and edge collections, construct a graph using
58//! [`ConnectivityGraph::try_from_edges`]:
59//!
60//! ```rust
61//! use knotrel_core::{ConnectivityGraph, EngineConfig, GraphLimits};
62//!
63//! let isolated_nodes = [99];
64//! let edges = [(1, 2), (2, 3), (3, 4)];
65//!
66//! let mut graph = ConnectivityGraph::try_from_edges(
67//! EngineConfig::CompactBfs,
68//! GraphLimits::default(),
69//! &isolated_nodes,
70//! &edges,
71//! )?;
72//!
73//! assert!(graph.connected(1, 4)?);
74//! assert!(!graph.connected(1, 99)?);
75//!
76//! // The resulting graph supports continued dynamic mutations:
77//! graph.link(4, 99)?;
78//! assert!(graph.connected(1, 99)?);
79//! # Ok::<(), knotrel_core::GraphError>(())
80//! ```
81//!
82//! Construction processes all explicit `nodes` first, then inserts `edges` in input order.
83//! It is atomic with respect to publication: on the first validation error, the partially
84//! constructed graph is dropped and the error is returned.
85//!
86//! # Node and Edge Lifecycle
87//!
88//! [`LifecycleGraph`] adds reversible node activation, reversible edge
89//! enabling and permanent node removal on the `compact-bfs` engine (`ett` and
90//! `hdt` lifecycle support is deferred and rejected with
91//! [`LifecycleError::UnsupportedEngine`]). It keeps the registered
92//! topology with flags and answers connectivity over the effective graph:
93//! enabled edges whose endpoints are both active. [`ConnectivityGraph`] is
94//! unchanged and carries no lifecycle bookkeeping.
95//!
96//! ```rust
97//! use knotrel_core::{EngineConfig, LifecycleGraph};
98//!
99//! let mut graph = LifecycleGraph::new(EngineConfig::CompactBfs)?;
100//! graph.link(1, 2)?;
101//! graph.set_edge_enabled(1, 2, false)?;
102//! assert!(!graph.connected(1, 2)?);
103//! assert_eq!(graph.edge_count(), 1);
104//! assert_eq!(graph.effective_edge_count(), 0);
105//! # Ok::<(), Box<dyn std::error::Error>>(())
106//! ```
107//!
108//! # Listing Neighbors (since 0.8)
109//!
110//! Neighbors can be listed page by page with a cursor, for browsing tools.
111//! On `compact-bfs`, [`Graph::neighbors_after`] needs a one-time opt-in
112//! ([`ConnectivityGraph::enable_neighbor_listing`], O(V)) because it keeps an
113//! index-to-ID vector (8 bytes per node) that ordinary use does not need.
114//! [`LifecycleGraph::incident_after`] lists neighbors with their edge state,
115//! in ascending neighbor ID. A cursor is the last neighbor returned; pages are
116//! not a snapshot of a graph that changes between them.
117//!
118//! ```rust
119//! use knotrel_core::{ConnectivityGraph, EngineConfig};
120//!
121//! let mut graph = ConnectivityGraph::new(EngineConfig::CompactBfs);
122//! graph.link(1, 2)?;
123//! graph.link(1, 3)?;
124//! assert!(graph.enable_neighbor_listing());
125//! let compact = graph.as_compact().expect("compact-bfs engine");
126//! assert_eq!(compact.degree(1), Some(2));
127//! let first: Vec<_> = compact.neighbors_after(1, None)?.take(1).collect();
128//! let rest: Vec<_> = compact.neighbors_after(1, first.last().copied())?.collect();
129//! assert_eq!(first.len() + rest.len(), 2);
130//! # Ok::<(), Box<dyn std::error::Error>>(())
131//! ```
132//!
133//! # Listing Every Node and Edge (experimental, since 1.3)
134//!
135//! [`ConnectivityGraph::for_each_node`] and [`ConnectivityGraph::for_each_edge`]
136//! visit every node and every undirected edge (`low < high`) once, in
137//! unspecified order, on every engine. [`LifecycleGraph::for_each_node`] and
138//! [`LifecycleGraph::for_each_edge`] also report each node's `active` and each
139//! edge's `enabled` flag. They are bulk reads for snapshots and exports,
140//! `O(V + E)`, and are classified Experimental.
141//!
142//! # Choosing a Backend Engine
143//!
144//! Knotrel provides four dynamic connectivity engines through [`EngineConfig`]; every engine
145//! returns the same exact answers. The canonical selection guide, with the 1.1 qualification
146//! results, is [Choosing an engine](https://knotrel.github.io/knotrel/choosing-an-engine.html).
147//!
148//! ### Algorithmic Complexity and API Assumptions
149//!
150//! The asymptotic costs in the table below describe the core graph and forest algorithms
151//! operating on internal indices. The public API maps external 64-bit [`NodeId`] keys to internal
152//! indices using hash maps (FxHash, and an ID-folding hasher for [`Graph`]), which rely on
153//! expected `O(1)` lookups and do not provide deterministic worst-case constant-time bounds for
154//! arbitrary ID distributions.
155//! Furthermore, collection and arena vector growth is amortized; a single vertex insertion or
156//! capacity reallocation may take `O(V)` in the worst case.
157//!
158//! | Engine | Configuration | Query Cost | Link Cost | Cut Cost | Logical Memory |
159//! | --- | --- | --- | --- | --- | --- |
160//! | **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)` |
161//! | **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)` |
162//! | **HDT** | [`EngineConfig::Hdt`] | `O(log V)` algorithmically | `O(log V)` amortized | `O(log² V)` amortized | `O(E + V log V)` |
163//! | **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)` |
164//!
165//! `N` is the high-water vertex count. *Note on memory:* `O(V + E)` and `O(E + V log V)` represent *logical* graph entity storage.
166//! Allocated memory capacities are retained after cuts and do not bound process heap memory or RSS.
167//!
168//! ### 1. Compact BFS ([`EngineConfig::CompactBfs`])
169//! - **Algorithmic properties**: Represents adjacency as compact, sorted vectors of stable internal indices.
170//! Queries perform a fresh breadth-first traversal in `O(V + E)` worst-case time using `O(V)` temporary scratch space.
171//! Link and cut shift sorted vectors in `O(deg(u) + deg(v))` time. Adding a vertex can trigger an `O(V)`
172//! outer-vector reallocation.
173//! - **Workload expectations**: Contiguous memory layout and low allocation overhead. Suitable as a general-purpose
174//! engine when mutations are frequent or graph components are small-to-moderate in size.
175//!
176//! ### 2. Euler Tour Trees ([`EngineConfig::EulerTour`])
177//! - **Algorithmic properties**: Maintains a spanning forest using AVL-balanced Euler tour sequences.
178//! Reachability queries compare tour roots in `O(log V)` algorithmic steps without graph traversals. Non-tree edge
179//! cuts take `O(log V + log E)` amortized time. Tree cuts partition the tree and scan non-tree edges of the smaller
180//! component (`s` vertices, `c` candidate edges) using candidate-pruned subtrees; this search costs
181//! `O(log V + log E + s + c log V)` amortized and allocates `O(s)` scratch space.
182//! - **Workload expectations**: Effective for query-dominated workloads and tree-like topologies where bridge cuts
183//! rarely split large components. Because it lacks edge-level hierarchies, repeated bridge cuts in dense cyclic
184//! components can trigger repeated scans over the same non-tree edges.
185//!
186//! ### 3. Holm–de Lichtenberg–Thorup ([`EngineConfig::Hdt`])
187//! - **Algorithmic properties**: Experimental deterministic implementation based on Holm, de Lichtenberg, and
188//! Thorup (2001), extended with an append-only growth policy for expanding vertex universes.
189//! Maintains a hierarchy of `O(log V)` levels, materializing upper levels lazily as edge promotions require them.
190//! Queries run on the base level in `O(log V)` algorithmic steps. Tree cuts search for replacement edges starting
191//! at the cut edge's level downwards; examined tree edges and non-tree edges on the smaller component are promoted
192//! to upper levels, bounding the amortized update cost to `O(log² V)` across operation sequences.
193//! - **Workload expectations**: Designed to prevent repeated scan storms in dense graphs undergoing frequent bridge cuts.
194//! However, its amortized bounds represent sequence averages rather than worst-case per-request latency guarantees;
195//! large individual promotion passes or vector reallocations can cause latency spikes, and it may have higher constant
196//! factors on small or sparse graphs; verify against your actual workload.
197//!
198//! ### 4. Cluster forest ([`EngineConfig::ClusterForest`], new in 1.1, experimental)
199//! - **Algorithmic properties**: Experimental sequential cluster forest of Wulff-Nilsen (SODA 2013, §3) with the
200//! path compression of De Man et al. (PVLDB 2025, §4) and insertion at the lowest common cluster. Edges carry
201//! levels; clusters are the components of each level and are stored only where an edge of their level lies
202//! inside them. Queries walk both vertices to their roots. A deletion runs two alternating searches from the
203//! endpoints' clusters, pushes the explored edges of the smaller side one level down and splits clusters when
204//! no replacement exists. The `O(log² N)` amortized update bound is **this project's derivation** for this
205//! variant ([ADR 0014](https://github.com/knotrel/knotrel/blob/main/docs/architecture/0014-cluster-forest-backend.md)),
206//! not a published theorem; the sources state it for related variants only. At most 2²⁸ vertices and edges.
207//! Also supported by [`LifecycleGraph`]. The backend type is internal.
208//! - **Workload expectations** (1.1 qualification, CF5: one host, candidate `02cba68`, the measured workloads only;
209//! [results](https://knotrel.github.io/knotrel-benchmarks/engines/cluster-forest-cf5-02cba68.html)):
210//! much faster than Compact BFS where Compact BFS answers queries by search (server mixed traffic, the
211//! components and hub families), faster than every other engine on dense bridge churn, and faster than ETT and
212//! HDT on construction; slower than Compact BFS on updates and construction, with more memory, and slower than
213//! all three on path- and ring-like bridge churn. Under sustained lifecycle churn on a sparse 1 000-node graph
214//! two heap-growth checks failed (projected growth, a documented limitation). It stays experimental and
215//! Compact BFS stays the default. See the [selection guide](https://knotrel.github.io/knotrel/choosing-an-engine.html).
216//!
217//! ```rust
218//! use knotrel_core::{ConnectivityGraph, EngineConfig, GraphError};
219//!
220//! fn main() -> Result<(), GraphError> {
221//! let mut graph = ConnectivityGraph::new(EngineConfig::ClusterForest);
222//! graph.link(1, 2)?;
223//! graph.link(2, 3)?;
224//! assert!(graph.connected(1, 3)?);
225//! graph.cut(2, 3)?;
226//! assert!(!graph.connected(1, 3)?);
227//! assert!(graph.engine().is_experimental());
228//! Ok(())
229//! }
230//! ```
231//!
232//! With node and edge lifecycle:
233//!
234//! ```rust
235//! use knotrel_core::{EngineConfig, LifecycleGraph};
236//!
237//! fn main() -> Result<(), Box<dyn std::error::Error>> {
238//! let mut graph = LifecycleGraph::new(EngineConfig::ClusterForest)?;
239//! for (u, v) in [(1, 2), (2, 4), (1, 3), (3, 4)] {
240//! graph.link(u, v)?;
241//! }
242//! graph.set_node_active(2, false)?;
243//! assert!(graph.connected(1, 4)?); // through 3
244//! graph.set_node_active(3, false)?;
245//! assert!(!graph.connected(1, 4)?);
246//! graph.set_node_active(2, true)?;
247//! assert!(graph.connected(1, 4)?); // the edges of 2 are back
248//! Ok(())
249//! }
250//! ```
251//!
252//! ### Pragmatic Guidance
253//! - **No universal winner**: Micro-benchmarks demonstrate that no single engine dominates across all graph topologies
254//! and operation mixes.
255//! - **Empirical evaluation**: If your workload characteristics (topology, scale, mutation mix) are uncertain, profile
256//! empirically rather than assuming polylogarithmic engines will outperform Compact BFS.
257//! - **Starting point**: Start with Compact BFS ([`EngineConfig::CompactBfs`]); evaluate ETT ([`EngineConfig::EulerTour`])
258//! for query-dominated workloads on tree-like graphs, HDT ([`EngineConfig::Hdt`]) for workloads with repeated bridge
259//! replacement searches, or cluster forest ([`EngineConfig::ClusterForest`]) for query-heavy workloads where Compact BFS
260//! searches, also with [`LifecycleGraph`], measuring actual topology, scale, and mutation mix. To go back, construct
261//! the graph with [`EngineConfig::CompactBfs`]; there is no in-place conversion.
262//!
263//! # Error and Resource Limit Handling
264//!
265//! All operations that may fail return [`Result<T, GraphError>`]. The possible errors in [`GraphError`] are:
266//! - [`GraphError::SelfLoop`]: The source and target node identifiers were identical.
267//! - [`GraphError::UnknownNode`]: A reachability query referenced a vertex that was never added or linked.
268//! - [`GraphError::NodeLimitExceeded`]: A mutation would exceed the configured [`GraphLimits::max_nodes`].
269//! - [`GraphError::EdgeLimitExceeded`]: A mutation would exceed the configured [`GraphLimits::max_edges`].
270//!
271//! ### Cardinality Limits vs. Memory
272//! [`GraphLimits`] enforce strict ceilings on registered vertex and live edge counts.
273//! These limits bound logical graph cardinality, not allocator heap memory or process RSS.
274//! Rejected mutations leave the graph completely unmodified.
275//!
276//! # Guarantees and Limitations
277//!
278//! - **Exact answers**: Knotrel computes exact connectivity; answers are never heuristic or approximate.
279//! - **Synchronous execution**: All graph algorithms execute synchronously on the caller's thread.
280//! - **Zero internal locking**: Graphs do not contain internal mutexes. For concurrent multi-threaded access,
281//! wrap [`ConnectivityGraph`] in standard Rust synchronization primitives (such as `std::sync::Mutex` or `std::sync::RwLock`).
282//! - **In-memory volatile state**: Graph data lives solely in memory. There is no write-ahead log (WAL),
283//! disk persistence, or crash recovery.
284//! - **No generic graph properties**: Knotrel is not an attributed property graph; it does not store node labels,
285//! edge weights, directed edges, or multi-edges.
286//! - **Stability classes**: every public item is classified **stable**, **experimental** or **internal** in the
287//! [stability classification](https://github.com/knotrel/knotrel/blob/main/docs/stability.md). Stable items change
288//! only as the [compatibility policy](https://github.com/knotrel/knotrel/blob/main/docs/compatibility.md) allows,
289//! after a deprecation. The ETT engine ([`EngineConfig::EulerTour`], [`ForestGraph`], [`ForestStats`]) and the
290//! HDT engine ([`EngineConfig::Hdt`], [`HdtGraph`], [`HdtStats`], [`HdtStorageStats`], [`HdtLevelStorage`]) are
291//! *stable interfaces with an experimental engine*: their public API stays compatible across 1.x, while their
292//! performance, maturity and usage recommendation carry no promise ([`EngineConfig::is_experimental`] returns
293//! `true`). [`EngineConfig::ClusterForest`] (new in 1.1) is a stable interface with an
294//! experimental engine too; its backend type is not exported. [`LifecycleStorage`] is stable. For these diagnostic structs, the fields, units and the properties
295//! their documentation lists as guaranteed are stable; the exact values are implementation-dependent.
296//! [`ReferenceGraph`] is an internal test oracle.
297
298use std::hash::{BuildHasherDefault, Hasher};
299
300/// Hasher of the [`Graph`] ID map: no multiply, and sequential IDs keep their
301/// order in the table.
302///
303/// The bucket bits are the ID folded onto itself (`x ^ x>>16 ^ x>>32 ^ x>>48`).
304/// Sequential IDs land in consecutive buckets, as with an identity hash, and
305/// IDs that differ only in high bits (such as `i << 16` or `i << 32`, which an
306/// identity hash sends to one bucket) are spread. The 7-bit control tag that
307/// hashbrown takes from the top bits repeats the folded value's low 7 bits, so
308/// consecutive IDs in one probe group carry distinct tags. Like FxHash, this is
309/// not keyed: it is not resistant to IDs chosen to collide.
310#[derive(Default, Clone, Copy)]
311struct IdHasher(u64);
312
313impl Hasher for IdHasher {
314 #[inline]
315 fn finish(&self) -> u64 {
316 let x = self.0;
317 let folded = x ^ (x >> 16) ^ (x >> 32) ^ (x >> 48);
318 folded | (folded << 57)
319 }
320
321 #[inline]
322 fn write_u64(&mut self, n: u64) {
323 self.0 = n;
324 }
325
326 /// Only `NodeId` (`u64`, hashed through `write_u64`) is hashed with this
327 /// hasher; other input is folded in byte by byte.
328 fn write(&mut self, bytes: &[u8]) {
329 for &byte in bytes {
330 self.0 = self.0.rotate_left(8) ^ u64::from(byte);
331 }
332 }
333}
334
335/// The [`Graph`] ID map.
336type IdMap<V> = std::collections::HashMap<NodeId, V, BuildHasherDefault<IdHasher>>;
337use std::{collections::hash_map::Entry, error::Error, fmt};
338
339mod workspace;
340pub use workspace::BfsWorkspace;
341
342mod cluster_forest;
343mod configuration;
344mod dynamic;
345mod forest;
346mod hdt;
347mod hdt_forest;
348mod hdt_profile;
349mod index;
350pub use hdt::{HdtGraph, HdtStats};
351pub use hdt_profile::{HdtLevelStorage, HdtStorageStats};
352mod reference;
353pub use configuration::{ConnectivityGraph, EngineConfig, GraphLimits};
354pub use dynamic::{ForestGraph, ForestStats};
355pub use reference::ReferenceGraph;
356mod topology;
357pub use topology::{
358 EdgeSpec, EdgeState, LifecycleError, LifecycleGraph, LifecycleStorage, NodeSpec,
359};
360
361/// A vertex identifier.
362pub type NodeId = u64;
363
364/// An invalid graph operation.
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366#[non_exhaustive]
367pub enum GraphError {
368 /// A mutation would exceed the registered vertex ceiling.
369 NodeLimitExceeded {
370 /// Configured maximum vertex count.
371 limit: usize,
372 },
373 /// A mutation would exceed the live edge ceiling.
374 EdgeLimitExceeded {
375 /// Configured maximum edge count.
376 limit: usize,
377 },
378 /// A self-loop was requested.
379 SelfLoop {
380 /// The repeated endpoint.
381 node: NodeId,
382 },
383 /// A query referenced an absent vertex.
384 UnknownNode {
385 /// The absent vertex.
386 node: NodeId,
387 },
388}
389
390impl fmt::Display for GraphError {
391 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
392 match self {
393 Self::NodeLimitExceeded { limit } => write!(formatter, "node limit exceeded: {limit}"),
394 Self::EdgeLimitExceeded { limit } => write!(formatter, "edge limit exceeded: {limit}"),
395 Self::SelfLoop { node } => write!(formatter, "self-loops are not supported: {node}"),
396 Self::UnknownNode { node } => write!(formatter, "unknown node: {node}"),
397 }
398 }
399}
400
401impl GraphError {
402 #[inline]
403 pub(crate) fn check_distinct(source: NodeId, target: NodeId) -> Result<(), Self> {
404 if source == target {
405 Err(Self::SelfLoop { node: source })
406 } else {
407 Ok(())
408 }
409 }
410}
411
412impl Error for GraphError {}
413
414/// Why an incidence listing could not start.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416#[non_exhaustive]
417pub enum IncidenceError {
418 /// The node whose incident edges were requested is not registered.
419 UnknownNode,
420 /// The pagination cursor names a node that is not registered.
421 UnknownCursor,
422 /// Neighbor listing was not enabled with [`Graph::enable_neighbor_listing`].
423 NotEnabled,
424}
425
426impl fmt::Display for IncidenceError {
427 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
428 formatter.write_str(match self {
429 Self::UnknownNode => "unknown node",
430 Self::UnknownCursor => "unknown incidence cursor",
431 Self::NotEnabled => "neighbor listing is not enabled",
432 })
433 }
434}
435
436impl Error for IncidenceError {}
437
438/// An undirected simple graph with compact adjacency and exact BFS queries.
439///
440/// External IDs map to stable, append-only indices. Neighbor listing
441/// ([`neighbors_after`](Self::neighbors_after)) is opt-in: after
442/// [`enable_neighbor_listing`](Self::enable_neighbor_listing) the graph also keeps
443/// the ID of every index (8 bytes per vertex); otherwise it keeps nothing extra.
444/// Each sorted adjacency vector contains unique indices, and every edge appears at
445/// both endpoints. Cuts retain vertices. Logical storage is O(V + E). Allocated storage is O(V + H), where H is
446/// the sum of per-vertex adjacency capacities: each is at least the vertex's
447/// historical maximum degree (capacity is retained) and, for a graph built in
448/// bulk by the lifecycle facade, starts at the vertex's enabled registered
449/// degree. No query answers are cached.
450#[derive(Debug, Default)]
451pub struct Graph {
452 ids: IdMap<usize>,
453 /// Inverse of `ids` (the ID registered at each index), kept only after
454 /// [`Graph::enable_neighbor_listing`]. Indices are never reused or removed,
455 /// so it only grows, in step with `adjacency`.
456 nodes: Option<Vec<NodeId>>,
457 adjacency: Vec<Vec<usize>>,
458 edges: usize,
459}
460
461/// Minimum entries examined per round before [`Graph::connected`] chooses a
462/// side again. It amortizes the choice on graphs with tiny frontiers and costs
463/// at most this many extra entries when the sides would have met sooner.
464const MIN_ROUND: usize = 1024;
465
466/// The round floor of the first round of a search. It doubles every round up
467/// to [`MIN_ROUND`], so a side about to run out (a small component) is not
468/// out-waited by a full round of the other side.
469const FIRST_ROUND: usize = 4;
470
471/// Most queue entries one side's scratch keeps between queries (64 KiB).
472const RETAIN_QUEUE: usize = 1 << 13;
473/// Most mark words the scratch keeps between queries (128 KiB: two bits per
474/// vertex, so graphs of up to 524,288 vertices reuse their marks).
475const RETAIN_MARK_WORDS: usize = 1 << 14;
476
477/// Mark bit of the source side; the target side's is the next bit.
478const SOURCE: u64 = 0b01;
479/// Mark bit of the target side.
480const TARGET: u64 = 0b10;
481
482/// Two mark bits per vertex, shared by both sides (32 vertices per word), so
483/// one load tells whether a neighbor is unmarked, marked by this side or
484/// marked by the other. A vertex never carries both bits: the search stops
485/// at the first vertex the other side has marked.
486#[inline]
487fn mark_shift(vertex: usize) -> u32 {
488 // At most 62: (vertex % 32) * 2.
489 ((vertex & 31) * 2) as u32
490}
491
492/// Per-thread scratch of [`Graph::connected`], so queries allocate and zero
493/// nothing in the steady state. Between queries every mark is clear and the
494/// queues are empty. `dirty` is set while a search runs: if one unwinds, the
495/// next query starts from fresh scratch.
496#[derive(Default)]
497struct Scratch {
498 marks: Vec<u64>,
499 source: Vec<usize>,
500 target: Vec<usize>,
501 dirty: bool,
502}
503
504impl Scratch {
505 /// Clears what the last query marked and drops capacity above the caps.
506 /// Clearing costs O(visited), or one pass over the marks when cheaper.
507 fn reset(&mut self) {
508 if self.source.len() + self.target.len() > self.marks.len() {
509 self.marks.fill(0);
510 } else {
511 for &vertex in self.source.iter().chain(&self.target) {
512 self.marks[vertex >> 5] &= !(0b11 << mark_shift(vertex));
513 }
514 }
515 for queue in [&mut self.source, &mut self.target] {
516 queue.clear();
517 if queue.capacity() > RETAIN_QUEUE {
518 *queue = Vec::new();
519 }
520 }
521 if self.marks.len() > RETAIN_MARK_WORDS {
522 self.marks = Vec::new();
523 }
524 }
525}
526
527thread_local! {
528 static SCRATCH: std::cell::RefCell<Scratch> = std::cell::RefCell::new(Scratch::default());
529}
530
531/// One side of the bidirectional search of [`Graph::connected`]: the vertices
532/// it marked, in order, how many of them it has expanded, its mark bit and the
533/// cached degree sum of the rest. A vertex is marked on enqueue, so every
534/// marked vertex is reachable from the side's endpoint and queued once.
535struct SearchSide<'s> {
536 queue: &'s mut Vec<usize>,
537 own: u64,
538 cursor: usize,
539 pending: Option<usize>,
540}
541
542impl<'s> SearchSide<'s> {
543 /// Starts a side at `endpoint` on an empty queue and clean marks.
544 fn new(queue: &'s mut Vec<usize>, marks: &mut [u64], endpoint: usize, own: u64) -> Self {
545 marks[endpoint >> 5] |= own << mark_shift(endpoint);
546 queue.push(endpoint);
547 Self {
548 queue,
549 own,
550 cursor: 0,
551 pending: None,
552 }
553 }
554
555 /// Sum of the degrees of the marked, unexpanded vertices. It is computed
556 /// once per round of this side, over vertices that round produced, so its
557 /// cost is bounded by the entries already examined.
558 fn pending_degree(&mut self, adjacency: &[Vec<usize>]) -> usize {
559 *self.pending.get_or_insert_with(|| {
560 self.queue[self.cursor..]
561 .iter()
562 .map(|&vertex| adjacency[vertex].len())
563 .sum()
564 })
565 }
566
567 /// Expands queued vertices in order for one round of at least
568 /// `max(pending, floor)` entries; the first vertex always expands.
569 /// Returns `Some(true)` on reaching a vertex marked by the other side,
570 /// `Some(false)` when the queue is exhausted, and `None` when the round
571 /// ends undecided.
572 fn expand(
573 &mut self,
574 adjacency: &[Vec<usize>],
575 marks: &mut [u64],
576 pending: usize,
577 floor: usize,
578 ) -> Option<bool> {
579 self.pending = None;
580 expand_round(
581 adjacency,
582 marks,
583 self.own,
584 self.queue,
585 &mut self.cursor,
586 pending.max(floor),
587 )
588 }
589}
590
591/// The loop of [`SearchSide::expand`], with the side's state passed as
592/// separate arguments and the cursor kept in a local.
593fn expand_round(
594 adjacency: &[Vec<usize>],
595 marks: &mut [u64],
596 own: u64,
597 queue: &mut Vec<usize>,
598 cursor_out: &mut usize,
599 budget: usize,
600) -> Option<bool> {
601 let mut cursor = *cursor_out;
602 let mut examined = 0;
603 let outcome = loop {
604 let Some(&vertex) = queue.get(cursor) else {
605 break Some(false);
606 };
607 let neighbors = &adjacency[vertex];
608 if examined > 0 && examined + neighbors.len() > budget {
609 break None;
610 }
611 cursor += 1;
612 examined += neighbors.len();
613 let mut met = false;
614 for &neighbor in neighbors {
615 let word = &mut marks[neighbor >> 5];
616 let shift = mark_shift(neighbor);
617 let bits = (*word >> shift) & 0b11;
618 if bits == 0 {
619 *word |= own << shift;
620 queue.push(neighbor);
621 } else if bits != own {
622 met = true;
623 break;
624 }
625 }
626 if met {
627 break Some(true);
628 }
629 };
630 *cursor_out = cursor;
631 outcome
632}
633
634/// The ID registered at each index: the inverse of an ID map whose indices
635/// are below `len`. One temporary vector of `len` IDs, built in `O(len)`;
636/// indices no entry maps to hold 0 and are never read by the callers.
637pub(crate) fn ids_by_index(
638 entries: impl Iterator<Item = (NodeId, usize)>,
639 len: usize,
640) -> Vec<NodeId> {
641 let mut nodes = vec![0; len];
642 for (node, index) in entries {
643 nodes[index] = node;
644 }
645 nodes
646}
647
648/// Calls `visit(low, high)` once per edge of an engine that keys its edges by
649/// pairs of dense indices below `len`, `low < high`, in the keys' order.
650/// Builds one temporary vector of `len` IDs.
651pub(crate) fn visit_index_edges(
652 ids: impl Iterator<Item = (NodeId, usize)>,
653 len: usize,
654 edges: impl Iterator<Item = (usize, usize)>,
655 mut visit: impl FnMut(NodeId, NodeId),
656) {
657 let nodes = ids_by_index(ids, len);
658 for (a, b) in edges {
659 let (a, b) = (nodes[a], nodes[b]);
660 visit(a.min(b), a.max(b));
661 }
662}
663
664impl Graph {
665 /// Reports whether `node` is registered; expected O(1) ID-map lookup.
666 pub(crate) fn contains_node(&self, node: NodeId) -> bool {
667 self.ids.contains_key(&node)
668 }
669
670 pub(crate) fn contains_edge(&self, source: NodeId, target: NodeId) -> bool {
671 let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
672 return false;
673 };
674 self.adjacency[a].binary_search(&b).is_ok()
675 }
676
677 /// Creates an empty graph in O(1) time.
678 #[must_use]
679 pub fn new() -> Self {
680 Self::default()
681 }
682
683 /// Returns the stable internal index for `node`, registering it if absent.
684 ///
685 /// Preserves append-only indexing and O(1) amortized time.
686 #[inline]
687 fn get_or_insert_index(&mut self, node: NodeId) -> usize {
688 match self.ids.entry(node) {
689 Entry::Occupied(entry) => *entry.get(),
690 Entry::Vacant(entry) => {
691 let index = self.adjacency.len();
692 self.adjacency.push(Vec::new());
693 if let Some(nodes) = &mut self.nodes {
694 nodes.push(node);
695 }
696 entry.insert(index);
697 index
698 }
699 }
700 }
701
702 /// Adds an isolated vertex, returning true only if it was absent.
703 ///
704 /// Existing edges are unchanged. O(1) amortized time; growing the outer
705 /// vector can take O(V) in a single insertion. Indices never change.
706 pub fn add_node(&mut self, node: NodeId) -> bool {
707 if let Entry::Vacant(entry) = self.ids.entry(node) {
708 let index = self.adjacency.len();
709 self.adjacency.push(Vec::new());
710 if let Some(nodes) = &mut self.nodes {
711 nodes.push(node);
712 }
713 entry.insert(index);
714 true
715 } else {
716 false
717 }
718 }
719
720 /// Inserts an undirected edge, creating absent endpoints.
721 ///
722 /// Reversed endpoints identify the same edge; duplicates return false.
723 /// O(1 + deg(source) + deg(target)) amortized time, including sorted
724 /// vector shifts. A new vertex can trigger an O(V) capacity growth.
725 ///
726 /// # Errors
727 /// Returns [`GraphError::SelfLoop`] without creating vertices for equal IDs.
728 pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
729 GraphError::check_distinct(source, target)?;
730 let a = self.get_or_insert_index(source);
731 let b = self.get_or_insert_index(target);
732 let Err(position) = self.adjacency[a].binary_search(&b) else {
733 return Ok(false);
734 };
735 let reverse = self.adjacency[b]
736 .binary_search(&a)
737 .expect_err("symmetric absence");
738 self.adjacency[a].insert(position, b);
739 self.adjacency[b].insert(reverse, a);
740 self.edges += 1;
741 Ok(true)
742 }
743
744 /// Removes an edge, preserving vertices; absent edges return false.
745 ///
746 /// Worst-case time: O(1 + deg(source) + deg(target)), due to vector shifts.
747 ///
748 /// # Errors
749 /// Returns [`GraphError::SelfLoop`] for equal IDs without changing the graph.
750 pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
751 GraphError::check_distinct(source, target)?;
752 let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
753 return Ok(false);
754 };
755 let Ok(position) = self.adjacency[a].binary_search(&b) else {
756 return Ok(false);
757 };
758 let reverse = self.adjacency[b].binary_search(&a).expect("symmetric edge");
759 self.adjacency[a].remove(position);
760 self.adjacency[b].remove(reverse);
761 self.edges -= 1;
762 Ok(true)
763 }
764
765 /// Reports whether a path exists between two existing vertices.
766 ///
767 /// Existing vertices connect to themselves. Worst-case time O(V + E), with
768 /// O(1) endpoint lookup. Scratch is per thread and reused: a query costs
769 /// no allocation or O(V) initialization once the thread's scratch has
770 /// grown, and shared queries need no internal lock. Each thread keeps at
771 /// most 256 KiB of scratch between queries.
772 ///
773 /// The search grows from both endpoints and stops when they meet or when
774 /// either side exhausts its component, so queries between nearby vertices,
775 /// through hubs, or against a small component finish early. On path-like
776 /// graphs it examines the same entries as a one-sided search from `source`.
777 ///
778 /// ```
779 /// let mut graph = knotrel_core::Graph::new();
780 /// graph.link(1, 2)?;
781 /// graph.link(2, 3)?;
782 /// graph.add_node(9);
783 /// assert_eq!(graph.connected(1, 3), Ok(true));
784 /// assert_eq!(graph.connected(1, 9), Ok(false));
785 /// # Ok::<(), knotrel_core::GraphError>(())
786 /// ```
787 ///
788 /// # Errors
789 /// Returns [`GraphError::UnknownNode`] for absent endpoints, source first.
790 pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
791 let a = *self
792 .ids
793 .get(&source)
794 .ok_or(GraphError::UnknownNode { node: source })?;
795 let b = *self
796 .ids
797 .get(&target)
798 .ok_or(GraphError::UnknownNode { node: target })?;
799 if a == b {
800 return Ok(true);
801 }
802 Ok(SCRATCH.with(|cell| match cell.try_borrow_mut() {
803 Ok(mut scratch) => self.search(&mut scratch, a, b),
804 // Re-entrant use on this thread (not expected): private scratch.
805 Err(_) => self.search(&mut Scratch::default(), a, b),
806 }))
807 }
808
809 /// The bidirectional search of [`Self::connected`] between distinct
810 /// internal indices, on `scratch`, which it leaves clean.
811 fn search(&self, scratch: &mut Scratch, a: usize, b: usize) -> bool {
812 if scratch.dirty {
813 *scratch = Scratch::default();
814 }
815 scratch.dirty = true;
816 let words = self.adjacency.len().div_ceil(32);
817 if scratch.marks.len() < words {
818 scratch.marks.resize(words, 0);
819 }
820 let found = {
821 let Scratch {
822 marks,
823 source,
824 target,
825 ..
826 } = &mut *scratch;
827 let mut source_side = SearchSide::new(source, marks, a, SOURCE);
828 let mut target_side = SearchSide::new(target, marks, b, TARGET);
829 // Each round expands the side with fewer pending incidences (the
830 // source on a tie, so path-like graphs do a one-sided search), for
831 // at least `floor` entries, without overshooting into a vertex
832 // whose list would exceed the round. The floor starts at
833 // FIRST_ROUND and doubles up to MIN_ROUND. Any edge between the
834 // two marked sets proves a path; an exhausted queue proves its
835 // endpoint's component holds no vertex of the other side. Each
836 // vertex is expanded at most once: O(V + E).
837 let mut floor = FIRST_ROUND;
838 loop {
839 let source_pending = source_side.pending_degree(&self.adjacency);
840 let target_pending = target_side.pending_degree(&self.adjacency);
841 let outcome = if target_pending < source_pending {
842 target_side.expand(&self.adjacency, marks, target_pending, floor)
843 } else {
844 source_side.expand(&self.adjacency, marks, source_pending, floor)
845 };
846 if let Some(found) = outcome {
847 break found;
848 }
849 floor = (floor * 2).min(MIN_ROUND);
850 }
851 };
852 scratch.reset();
853 scratch.dirty = false;
854 found
855 }
856
857 /// Returns the number of vertices, including isolated ones, in O(1) time.
858 #[must_use]
859 pub fn node_count(&self) -> usize {
860 self.adjacency.len()
861 }
862
863 /// Returns the number of undirected edges in O(1) time.
864 #[must_use]
865 pub fn edge_count(&self) -> usize {
866 self.edges
867 }
868
869 /// Builds a graph in one pass from validated adjacency (bulk construction
870 /// for the lifecycle facade).
871 ///
872 /// `ids[i]` receives internal index `i`; `adjacency[i]` lists the indices
873 /// of its neighbors. The caller guarantees the [`Graph`] invariants:
874 /// distinct IDs, equal lengths, every list strictly sorted, symmetric
875 /// (`j` in `adjacency[i]` iff `i` in `adjacency[j]`) and free of
876 /// self-loops; debug builds verify them. Vectors are taken as they are,
877 /// so their capacities are kept.
878 ///
879 /// `O(V + E)` time plus the ID-map insertions (expected `O(1)` each);
880 /// no adjacency vector is reallocated.
881 pub(crate) fn from_sorted_adjacency(ids: Vec<NodeId>, adjacency: Vec<Vec<usize>>) -> Self {
882 assert_eq!(ids.len(), adjacency.len(), "one adjacency list per ID");
883 let mut map: IdMap<usize> = IdMap::with_capacity_and_hasher(ids.len(), Default::default());
884 for (index, &node) in ids.iter().enumerate() {
885 let previous = map.insert(node, index);
886 debug_assert!(previous.is_none(), "distinct IDs");
887 }
888 let incidences: usize = adjacency.iter().map(Vec::len).sum();
889 debug_assert!(incidences.is_multiple_of(2), "symmetric adjacency");
890 #[cfg(debug_assertions)]
891 for (index, list) in adjacency.iter().enumerate() {
892 for pair in list.windows(2) {
893 debug_assert!(pair[0] < pair[1], "strictly sorted adjacency");
894 }
895 for &neighbor in list {
896 debug_assert_ne!(neighbor, index, "no self-loops");
897 debug_assert!(
898 adjacency[neighbor].binary_search(&index).is_ok(),
899 "symmetric adjacency"
900 );
901 }
902 }
903 Self {
904 ids: map,
905 nodes: None,
906 adjacency,
907 edges: incidences / 2,
908 }
909 }
910
911 /// Returns the number of edges incident to `node`, or `None` if it is not
912 /// registered. Expected O(1).
913 ///
914 /// ```rust
915 /// let mut graph = knotrel_core::Graph::new();
916 /// graph.link(1, 2)?;
917 /// assert_eq!(graph.degree(1), Some(1));
918 /// assert_eq!(graph.degree(9), None);
919 /// # Ok::<(), knotrel_core::GraphError>(())
920 /// ```
921 #[must_use]
922 pub fn degree(&self, node: NodeId) -> Option<usize> {
923 self.ids
924 .get(&node)
925 .map(|&index| self.adjacency[index].len())
926 }
927
928 /// Starts keeping the ID of every internal index, which
929 /// [`neighbors_after`](Self::neighbors_after) needs. Costs 8 bytes per vertex
930 /// and one vector push per new vertex from now on; building the vector for
931 /// the existing vertices is O(V). Calling it again does nothing.
932 ///
933 /// ```rust
934 /// let mut graph = knotrel_core::Graph::new();
935 /// graph.link(1, 2)?;
936 /// assert!(graph.neighbors_after(1, None).is_err());
937 /// graph.enable_neighbor_listing();
938 /// assert_eq!(graph.neighbors_after(1, None)?.collect::<Vec<_>>(), [2]);
939 /// # Ok::<(), Box<dyn std::error::Error>>(())
940 /// ```
941 pub fn enable_neighbor_listing(&mut self) {
942 if self.nodes.is_none() {
943 let mut nodes = vec![0; self.adjacency.len()];
944 for (&node, &index) in &self.ids {
945 nodes[index] = node;
946 }
947 self.nodes = Some(nodes);
948 }
949 }
950
951 /// Iterates the neighbors of `node` in the graph's stable incidence order,
952 /// starting strictly after the neighbor `after` (or from the start).
953 ///
954 /// The order is the neighbors' registration order. It is stable across
955 /// mutations: indices are never reused, so a neighbor present before and
956 /// after a sequence of calls keeps its relative position. That makes
957 /// `after` usable as a pagination cursor: every neighbor that stays linked
958 /// while a caller pages through the list is visited exactly once, and
959 /// neighbors linked or cut meanwhile may or may not be visited. `after`
960 /// need not still be linked to `node`.
961 ///
962 /// Positioning costs O(log deg(node)) expected; each step is O(1).
963 ///
964 /// # Errors
965 ///
966 /// [`IncidenceError::NotEnabled`] before
967 /// [`enable_neighbor_listing`](Self::enable_neighbor_listing),
968 /// [`IncidenceError::UnknownNode`] if `node` is not registered, and
969 /// [`IncidenceError::UnknownCursor`] if `after` is not a registered node.
970 /// Vertices are never removed from a [`Graph`], so a cursor obtained from
971 /// this graph never becomes unknown.
972 ///
973 /// ```rust
974 /// let mut graph = knotrel_core::Graph::new();
975 /// graph.enable_neighbor_listing();
976 /// graph.link(5, 9)?;
977 /// graph.link(5, 1)?;
978 /// graph.link(5, 7)?;
979 /// let all: Vec<_> = graph.neighbors_after(5, None)?.collect();
980 /// assert_eq!(all, [9, 1, 7]); // registration order, not ID order
981 /// let rest: Vec<_> = graph.neighbors_after(5, Some(9))?.collect();
982 /// assert_eq!(rest, [1, 7]);
983 /// # Ok::<(), Box<dyn std::error::Error>>(())
984 /// ```
985 pub fn neighbors_after(
986 &self,
987 node: NodeId,
988 after: Option<NodeId>,
989 ) -> Result<impl Iterator<Item = NodeId> + '_, IncidenceError> {
990 let &index = self.ids.get(&node).ok_or(IncidenceError::UnknownNode)?;
991 let list = &self.adjacency[index];
992 let start = match after {
993 None => 0,
994 Some(cursor) => {
995 let &cursor = self.ids.get(&cursor).ok_or(IncidenceError::UnknownCursor)?;
996 list.partition_point(|&neighbor| neighbor <= cursor)
997 }
998 };
999 let nodes = self.nodes.as_deref().ok_or(IncidenceError::NotEnabled)?;
1000 Ok(list[start..].iter().map(move |&neighbor| nodes[neighbor]))
1001 }
1002
1003 /// Calls `visit` once per registered vertex, in unspecified order.
1004 /// `O(V)` time, no allocation.
1005 pub(crate) fn for_each_node(&self, mut visit: impl FnMut(NodeId)) {
1006 self.ids.keys().for_each(|&node| visit(node));
1007 }
1008
1009 /// Calls `visit(low, high)` once per edge, with `low < high`, in
1010 /// unspecified order. `O(V + E)` time; without neighbor listing it
1011 /// builds one temporary vector of the vertex IDs (8 bytes per vertex).
1012 pub(crate) fn for_each_edge(&self, mut visit: impl FnMut(NodeId, NodeId)) {
1013 let built;
1014 let nodes = match &self.nodes {
1015 Some(nodes) => nodes.as_slice(),
1016 None => {
1017 built = ids_by_index(
1018 self.ids.iter().map(|(&node, &index)| (node, index)),
1019 self.adjacency.len(),
1020 );
1021 built.as_slice()
1022 }
1023 };
1024 for (index, list) in self.adjacency.iter().enumerate() {
1025 let node = nodes[index];
1026 for &neighbor in &list[list.partition_point(|&other| other <= index)..] {
1027 let other = nodes[neighbor];
1028 visit(node.min(other), node.max(other));
1029 }
1030 }
1031 }
1032
1033 /// Releases the adjacency allocation of an isolated vertex.
1034 ///
1035 /// A no-op for an absent node or one that still has edges. The vertex and
1036 /// its index stay registered. `O(1)` expected.
1037 pub(crate) fn release_isolated_storage(&mut self, node: NodeId) {
1038 if let Some(&index) = self.ids.get(&node) {
1039 let list = &mut self.adjacency[index];
1040 if list.is_empty() {
1041 *list = Vec::new();
1042 }
1043 }
1044 }
1045
1046 /// Returns the adjacency capacity (elements) held by `node`, if present.
1047 #[cfg(test)]
1048 pub(crate) fn adjacency_capacity(&self, node: NodeId) -> Option<usize> {
1049 self.ids
1050 .get(&node)
1051 .map(|&index| self.adjacency[index].capacity())
1052 }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058
1059 /// Resetting scratch clears every mark (per vertex, or in one pass when
1060 /// cheaper) and drops buffers above the retention caps.
1061 #[test]
1062 fn scratch_reset_clears_marks_and_enforces_caps() {
1063 let mut scratch = Scratch::default();
1064 scratch.marks.resize(1_000, 0);
1065 scratch.marks[0] |= SOURCE << mark_shift(3);
1066 scratch.marks[1] |= TARGET << mark_shift(40);
1067 scratch.source.push(3);
1068 scratch.target.push(40);
1069 scratch.reset();
1070 assert_eq!(scratch.marks.len(), 1_000);
1071 assert!(scratch.marks.iter().all(|&word| word == 0));
1072 assert!(scratch.source.is_empty() && scratch.target.is_empty());
1073
1074 scratch.marks.resize(RETAIN_MARK_WORDS + 1, 0);
1075 scratch.source.reserve(RETAIN_QUEUE + 1);
1076 scratch.target.reserve(RETAIN_QUEUE + 1);
1077 for vertex in 0..RETAIN_QUEUE {
1078 scratch.marks[vertex >> 5] |= SOURCE << mark_shift(vertex);
1079 scratch.source.push(vertex);
1080 }
1081 scratch.reset();
1082 assert_eq!(
1083 (
1084 scratch.marks.len(),
1085 scratch.source.capacity(),
1086 scratch.target.capacity()
1087 ),
1088 (0, 0, 0)
1089 );
1090 }
1091
1092 /// Two mark bits per vertex: every vertex of a word gets its own pair.
1093 #[test]
1094 fn mark_shift_gives_each_vertex_of_a_word_its_own_pair() {
1095 let shifts: Vec<u32> = (0..32).map(mark_shift).collect();
1096 assert_eq!(shifts, (0..32).map(|i| i * 2).collect::<Vec<_>>());
1097 assert_eq!(mark_shift(32), 0);
1098 assert_eq!(mark_shift(63), 62);
1099 }
1100
1101 /// The ID hasher keeps sequential IDs in order, spreads IDs that differ
1102 /// only in high bits, and repeats the low 7 bits in the control tag.
1103 #[test]
1104 fn id_hasher_folds_high_bits_and_tags_low_bits() {
1105 let hash = |id: u64| {
1106 let mut hasher = IdHasher::default();
1107 hasher.write_u64(id);
1108 hasher.finish()
1109 };
1110 let low = |h: u64| h & ((1 << 57) - 1);
1111 assert_eq!(
1112 (0..100).map(|i| low(hash(i))).collect::<Vec<_>>(),
1113 (0..100).collect::<Vec<_>>()
1114 );
1115 for shift in [16, 32, 48] {
1116 let buckets: std::collections::HashSet<u64> =
1117 (0..1_000).map(|i| low(hash(i << shift)) & 0xFFFF).collect();
1118 assert_eq!(buckets.len(), 1_000, "shift {shift}");
1119 }
1120 assert_eq!(hash(5) >> 57, 5);
1121 assert_eq!(hash(130) >> 57, 2);
1122 let mut bytes = IdHasher::default();
1123 bytes.write(&[1, 2]);
1124 assert_eq!(bytes.0, 0x0102);
1125 }
1126
1127 /// A search that unwound leaves its scratch dirty; the next query starts
1128 /// from fresh scratch, so stale marks cannot change its answer.
1129 #[test]
1130 fn dirty_scratch_is_replaced_before_the_next_query() {
1131 let mut graph = Graph::new();
1132 graph.link(0, 1).unwrap();
1133 graph.link(2, 3).unwrap();
1134 SCRATCH.with(|cell| {
1135 let mut scratch = cell.borrow_mut();
1136 scratch.dirty = true;
1137 scratch.marks = vec![u64::MAX];
1138 scratch.source.push(1);
1139 });
1140 assert!(!graph.connected(0, 3).unwrap());
1141 assert!(graph.connected(2, 3).unwrap());
1142 SCRATCH.with(|cell| {
1143 let scratch = cell.borrow();
1144 assert!(!scratch.dirty);
1145 assert!(scratch.marks.iter().all(|&word| word == 0));
1146 assert!(scratch.source.is_empty() && scratch.target.is_empty());
1147 });
1148 }
1149
1150 /// A query issued while this thread's scratch is borrowed uses private
1151 /// scratch and still answers correctly.
1152 #[test]
1153 fn query_with_borrowed_thread_scratch_uses_private_scratch() {
1154 let mut graph = Graph::new();
1155 graph.link(0, 1).unwrap();
1156 graph.link(1, 2).unwrap();
1157 graph.link(5, 6).unwrap();
1158 SCRATCH.with(|cell| {
1159 let _held = cell.borrow_mut();
1160 assert!(graph.connected(0, 2).unwrap());
1161 assert!(!graph.connected(0, 6).unwrap());
1162 });
1163 }
1164
1165 /// Paging through a hub's neighbors with `neighbors_after` visits every
1166 /// neighbor that stays linked exactly once, even when other edges are cut
1167 /// and added between pages; cursors stay valid after their edge is cut.
1168 #[test]
1169 fn neighbor_pages_visit_stable_neighbors_exactly_once() {
1170 let mut graph = Graph::new();
1171 graph.link(0, 3).unwrap();
1172 assert_eq!(
1173 graph.neighbors_after(0, None).err(),
1174 Some(IncidenceError::NotEnabled)
1175 );
1176 // Enabling after vertices exist rebuilds the index-to-ID vector.
1177 graph.enable_neighbor_listing();
1178 graph.enable_neighbor_listing();
1179 graph.cut(0, 3).unwrap();
1180 for neighbor in 1..=100u64 {
1181 graph.link(0, neighbor * 7).unwrap();
1182 }
1183 let stable: Vec<u64> = (1..=100u64).filter(|n| n % 3 != 0).map(|n| n * 7).collect();
1184 let mut seen = Vec::new();
1185 let mut cursor = None;
1186 let mut round = 0u64;
1187 loop {
1188 let page: Vec<u64> = graph.neighbors_after(0, cursor).unwrap().take(9).collect();
1189 let Some(&last) = page.last() else { break };
1190 seen.extend(page);
1191 cursor = Some(last);
1192 // Between pages: cut neighbors that are not "stable" (including the
1193 // cursor itself) and link new ones.
1194 for n in (1..=100u64).filter(|n| n % 3 == 0) {
1195 let _ = graph.cut(0, n * 7);
1196 }
1197 // New neighbors are appended after the cursor; stop adding them after
1198 // a few rounds so the traversal terminates.
1199 if round < 5 {
1200 round += 1;
1201 graph.link(0, 10_000 + round).unwrap();
1202 }
1203 }
1204 for node in &stable {
1205 assert_eq!(seen.iter().filter(|&&s| s == *node).count(), 1, "{node}");
1206 }
1207 assert_eq!(graph.degree(0), Some(stable.len() + round as usize));
1208 assert_eq!(graph.degree(424_242), None);
1209 assert_eq!(
1210 graph.neighbors_after(424_242, None).err(),
1211 Some(IncidenceError::UnknownNode)
1212 );
1213 assert_eq!(
1214 graph.neighbors_after(0, Some(424_242)).err(),
1215 Some(IncidenceError::UnknownCursor)
1216 );
1217 assert_eq!(
1218 IncidenceError::UnknownCursor.to_string(),
1219 "unknown incidence cursor"
1220 );
1221 assert_eq!(IncidenceError::UnknownNode.to_string(), "unknown node");
1222 assert_eq!(
1223 IncidenceError::NotEnabled.to_string(),
1224 "neighbor listing is not enabled"
1225 );
1226 }
1227
1228 /// A bulk-built graph maps indices back to the same IDs as an incremental one.
1229 #[test]
1230 fn bulk_built_graph_lists_neighbors_by_id() {
1231 let ids = vec![u64::MAX, 3, 9_007_199_254_740_993];
1232 let adjacency = vec![vec![1, 2], vec![0], vec![0]];
1233 let mut graph = Graph::from_sorted_adjacency(ids, adjacency);
1234 graph.enable_neighbor_listing();
1235 let neighbors: Vec<u64> = graph.neighbors_after(u64::MAX, None).unwrap().collect();
1236 assert_eq!(neighbors, [3, 9_007_199_254_740_993]);
1237 assert_eq!(graph.degree(3), Some(1));
1238 }
1239
1240 /// A bulk-built graph keeps every `Graph` invariant and then behaves like
1241 /// an incrementally built one under further `add_node`, `link`, `cut` and
1242 /// `connected` calls.
1243 #[test]
1244 fn bulk_built_graph_matches_incremental_graph_under_mutation() {
1245 let mut seed = 0x2545_f491_u64;
1246 let mut next = move |bound: u64| {
1247 seed ^= seed << 13;
1248 seed ^= seed >> 7;
1249 seed ^= seed << 17;
1250 seed % bound
1251 };
1252 for _case in 0..200 {
1253 let n = 1 + next(30) as usize;
1254 let ids: Vec<NodeId> = (0..n as u64).map(|i| i * 7 + 3).collect();
1255 let mut incremental = Graph::new();
1256 for &id in &ids {
1257 incremental.add_node(id);
1258 }
1259 let mut adjacency = vec![Vec::new(); n];
1260 for _ in 0..next(3 * n as u64 + 1) {
1261 let (a, b) = (next(n as u64) as usize, next(n as u64) as usize);
1262 if a != b && incremental.link(ids[a], ids[b]) == Ok(true) {
1263 adjacency[a].push(b);
1264 adjacency[b].push(a);
1265 }
1266 }
1267 for list in &mut adjacency {
1268 list.sort_unstable();
1269 }
1270 let mut bulk = Graph::from_sorted_adjacency(ids.clone(), adjacency);
1271 assert_eq!(bulk.node_count(), incremental.node_count());
1272 assert_eq!(bulk.edge_count(), incremental.edge_count());
1273 for _ in 0..100 {
1274 let a = next(n as u64 + 5) * 7 + 3;
1275 let b = next(n as u64 + 5) * 7 + 3;
1276 match next(4) {
1277 0 => assert_eq!(bulk.add_node(a), incremental.add_node(a)),
1278 1 => assert_eq!(bulk.link(a, b), incremental.link(a, b)),
1279 2 => assert_eq!(bulk.cut(a, b), incremental.cut(a, b)),
1280 _ => assert_eq!(bulk.connected(a, b), incremental.connected(a, b)),
1281 }
1282 assert_eq!(bulk.edge_count(), incremental.edge_count());
1283 assert_eq!(bulk.node_count(), incremental.node_count());
1284 }
1285 for list in &bulk.adjacency {
1286 assert!(list.windows(2).all(|pair| pair[0] < pair[1]));
1287 }
1288 bulk.release_isolated_storage(ids[0]);
1289 assert_eq!(bulk.connected(ids[0], ids[0]), Ok(true));
1290 }
1291 }
1292
1293 #[test]
1294 fn link_preserves_internal_source_before_target_index_order() {
1295 let mut graph = Graph::new();
1296 // Link two fresh nodes: source 42, target 99.
1297 assert_eq!(graph.link(42, 99), Ok(true));
1298 // Directly verify the internal index mapping:
1299 // source (42) must receive internal index 0; target (99) must receive internal index 1.
1300 assert_eq!(graph.ids.get(&42), Some(&0));
1301 assert_eq!(graph.ids.get(&99), Some(&1));
1302 assert_eq!(graph.adjacency[0], vec![1]);
1303 assert_eq!(graph.adjacency[1], vec![0]);
1304
1305 // Link with one existing endpoint: source 42 (existing index 0), target 1000 (fresh).
1306 assert_eq!(graph.link(42, 1000), Ok(true));
1307 assert_eq!(graph.ids.get(&1000), Some(&2));
1308 assert_eq!(graph.adjacency[0], vec![1, 2]);
1309 assert_eq!(graph.adjacency[2], vec![0]);
1310
1311 // Link with one existing endpoint: source 2000 (fresh), target 99 (existing index 1).
1312 assert_eq!(graph.link(2000, 99), Ok(true));
1313 assert_eq!(graph.ids.get(&2000), Some(&3));
1314 assert_eq!(graph.adjacency[1], vec![0, 3]);
1315 assert_eq!(graph.adjacency[3], vec![1]);
1316
1317 // Link with two existing endpoints: 1000 (index 2) and 2000 (index 3).
1318 assert_eq!(graph.link(1000, 2000), Ok(true));
1319 assert_eq!(graph.ids.get(&1000), Some(&2));
1320 assert_eq!(graph.ids.get(&2000), Some(&3));
1321 assert_eq!(graph.adjacency[2], vec![0, 3]);
1322 assert_eq!(graph.adjacency[3], vec![1, 2]);
1323 }
1324}