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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
//! 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>>(())
//! ```
//!
//! # 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.
//!
//! ```rust
//! 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);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! # 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](https://knotrel.github.io/knotrel/choosing-an-engine.html).
//!
//! ### 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 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.
//!
//! ### 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](https://github.com/knotrel/knotrel/blob/main/docs/architecture/0014-cluster-forest-backend.md)),
//!   not a published theorem; the sources state it for related variants only. At most 2²⁸ vertices and edges.
//!   Also supported by [`LifecycleGraph`]. The backend type is internal.
//! - **Workload expectations** (1.1 qualification, CF5: one host, candidate `02cba68`, the measured workloads only;
//!   [results](https://knotrel.github.io/knotrel-benchmarks/engines/cluster-forest-cf5-02cba68.html)):
//!   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](https://knotrel.github.io/knotrel/choosing-an-engine.html).
//!
//! ```rust
//! 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:
//!
//! ```rust
//! 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 with [`LifecycleGraph`], measuring actual topology, scale, and mutation mix. To go back, construct
//!   the graph with [`EngineConfig::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 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.
//! - **Stability classes**: every public item is classified **stable**, **experimental** or **internal** in the
//!   [stability classification](https://github.com/knotrel/knotrel/blob/main/docs/stability.md). Stable items change
//!   only as the [compatibility policy](https://github.com/knotrel/knotrel/blob/main/docs/compatibility.md) 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_experimental`] returns
//!   `true`). [`EngineConfig::ClusterForest`] (new in 1.1) is a stable interface with an
//!   experimental engine too; its backend type is not exported. [`LifecycleStorage`] is stable. For these diagnostic structs, the fields, units and the properties
//!   their documentation lists as guaranteed are stable; the exact values are implementation-dependent.
//!   [`ReferenceGraph`] is an internal test oracle.

use std::hash::{BuildHasherDefault, Hasher};

/// Hasher of the [`Graph`] ID map: no multiply, and sequential IDs keep their
/// order in the table.
///
/// The bucket bits are the ID folded onto itself (`x ^ x>>16 ^ x>>32 ^ x>>48`).
/// Sequential IDs land in consecutive buckets, as with an identity hash, and
/// IDs that differ only in high bits (such as `i << 16` or `i << 32`, which an
/// identity hash sends to one bucket) are spread. The 7-bit control tag that
/// hashbrown takes from the top bits repeats the folded value's low 7 bits, so
/// consecutive IDs in one probe group carry distinct tags. Like FxHash, this is
/// not keyed: it is not resistant to IDs chosen to collide.
#[derive(Default, Clone, Copy)]
struct IdHasher(u64);

impl Hasher for IdHasher {
    #[inline]
    fn finish(&self) -> u64 {
        let x = self.0;
        let folded = x ^ (x >> 16) ^ (x >> 32) ^ (x >> 48);
        folded | (folded << 57)
    }

    #[inline]
    fn write_u64(&mut self, n: u64) {
        self.0 = n;
    }

    /// Only `NodeId` (`u64`, hashed through `write_u64`) is hashed with this
    /// hasher; other input is folded in byte by byte.
    fn write(&mut self, bytes: &[u8]) {
        for &byte in bytes {
            self.0 = self.0.rotate_left(8) ^ u64::from(byte);
        }
    }
}

/// The [`Graph`] ID map.
type IdMap<V> = std::collections::HashMap<NodeId, V, BuildHasherDefault<IdHasher>>;
use std::{collections::hash_map::Entry, error::Error, fmt};

mod workspace;
pub use workspace::BfsWorkspace;

mod cluster_forest;
mod configuration;
mod dynamic;
mod forest;
mod hdt;
mod hdt_forest;
mod hdt_profile;
mod index;
pub use hdt::{HdtGraph, HdtStats};
pub use hdt_profile::{HdtLevelStorage, HdtStorageStats};
mod reference;
pub use configuration::{ConnectivityGraph, EngineConfig, GraphLimits};
pub use dynamic::{ForestGraph, ForestStats};
pub use reference::ReferenceGraph;
mod topology;
pub use topology::{
    EdgeSpec, EdgeState, LifecycleError, LifecycleGraph, LifecycleStorage, NodeSpec,
};

/// A vertex identifier.
pub type NodeId = u64;

/// An invalid graph operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum GraphError {
    /// A mutation would exceed the registered vertex ceiling.
    NodeLimitExceeded {
        /// Configured maximum vertex count.
        limit: usize,
    },
    /// A mutation would exceed the live edge ceiling.
    EdgeLimitExceeded {
        /// Configured maximum edge count.
        limit: usize,
    },
    /// A self-loop was requested.
    SelfLoop {
        /// The repeated endpoint.
        node: NodeId,
    },
    /// A query referenced an absent vertex.
    UnknownNode {
        /// The absent vertex.
        node: NodeId,
    },
}

impl fmt::Display for GraphError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NodeLimitExceeded { limit } => write!(formatter, "node limit exceeded: {limit}"),
            Self::EdgeLimitExceeded { limit } => write!(formatter, "edge limit exceeded: {limit}"),
            Self::SelfLoop { node } => write!(formatter, "self-loops are not supported: {node}"),
            Self::UnknownNode { node } => write!(formatter, "unknown node: {node}"),
        }
    }
}

impl GraphError {
    #[inline]
    pub(crate) fn check_distinct(source: NodeId, target: NodeId) -> Result<(), Self> {
        if source == target {
            Err(Self::SelfLoop { node: source })
        } else {
            Ok(())
        }
    }
}

impl Error for GraphError {}

/// Why an incidence listing could not start.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IncidenceError {
    /// The node whose incident edges were requested is not registered.
    UnknownNode,
    /// The pagination cursor names a node that is not registered.
    UnknownCursor,
    /// Neighbor listing was not enabled with [`Graph::enable_neighbor_listing`].
    NotEnabled,
}

impl fmt::Display for IncidenceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::UnknownNode => "unknown node",
            Self::UnknownCursor => "unknown incidence cursor",
            Self::NotEnabled => "neighbor listing is not enabled",
        })
    }
}

impl Error for IncidenceError {}

/// An undirected simple graph with compact adjacency and exact BFS queries.
///
/// External IDs map to stable, append-only indices. Neighbor listing
/// ([`neighbors_after`](Self::neighbors_after)) is opt-in: after
/// [`enable_neighbor_listing`](Self::enable_neighbor_listing) the graph also keeps
/// the ID of every index (8 bytes per vertex); otherwise it keeps nothing extra.
/// 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 adjacency capacities: each is at least the vertex's
/// historical maximum degree (capacity is retained) and, for a graph built in
/// bulk by the lifecycle facade, starts at the vertex's enabled registered
/// degree. No query answers are cached.
#[derive(Debug, Default)]
pub struct Graph {
    ids: IdMap<usize>,
    /// Inverse of `ids` (the ID registered at each index), kept only after
    /// [`Graph::enable_neighbor_listing`]. Indices are never reused or removed,
    /// so it only grows, in step with `adjacency`.
    nodes: Option<Vec<NodeId>>,
    adjacency: Vec<Vec<usize>>,
    edges: usize,
}

/// Minimum entries examined per round before [`Graph::connected`] chooses a
/// side again. It amortizes the choice on graphs with tiny frontiers and costs
/// at most this many extra entries when the sides would have met sooner.
const MIN_ROUND: usize = 1024;

/// The round floor of the first round of a search. It doubles every round up
/// to [`MIN_ROUND`], so a side about to run out (a small component) is not
/// out-waited by a full round of the other side.
const FIRST_ROUND: usize = 4;

/// Most queue entries one side's scratch keeps between queries (64 KiB).
const RETAIN_QUEUE: usize = 1 << 13;
/// Most mark words the scratch keeps between queries (128 KiB: two bits per
/// vertex, so graphs of up to 524,288 vertices reuse their marks).
const RETAIN_MARK_WORDS: usize = 1 << 14;

/// Mark bit of the source side; the target side's is the next bit.
const SOURCE: u64 = 0b01;
/// Mark bit of the target side.
const TARGET: u64 = 0b10;

/// Two mark bits per vertex, shared by both sides (32 vertices per word), so
/// one load tells whether a neighbor is unmarked, marked by this side or
/// marked by the other. A vertex never carries both bits: the search stops
/// at the first vertex the other side has marked.
#[inline]
fn mark_shift(vertex: usize) -> u32 {
    // At most 62: (vertex % 32) * 2.
    ((vertex & 31) * 2) as u32
}

/// Per-thread scratch of [`Graph::connected`], so queries allocate and zero
/// nothing in the steady state. Between queries every mark is clear and the
/// queues are empty. `dirty` is set while a search runs: if one unwinds, the
/// next query starts from fresh scratch.
#[derive(Default)]
struct Scratch {
    marks: Vec<u64>,
    source: Vec<usize>,
    target: Vec<usize>,
    dirty: bool,
}

impl Scratch {
    /// Clears what the last query marked and drops capacity above the caps.
    /// Clearing costs O(visited), or one pass over the marks when cheaper.
    fn reset(&mut self) {
        if self.source.len() + self.target.len() > self.marks.len() {
            self.marks.fill(0);
        } else {
            for &vertex in self.source.iter().chain(&self.target) {
                self.marks[vertex >> 5] &= !(0b11 << mark_shift(vertex));
            }
        }
        for queue in [&mut self.source, &mut self.target] {
            queue.clear();
            if queue.capacity() > RETAIN_QUEUE {
                *queue = Vec::new();
            }
        }
        if self.marks.len() > RETAIN_MARK_WORDS {
            self.marks = Vec::new();
        }
    }
}

thread_local! {
    static SCRATCH: std::cell::RefCell<Scratch> = std::cell::RefCell::new(Scratch::default());
}

/// One side of the bidirectional search of [`Graph::connected`]: the vertices
/// it marked, in order, how many of them it has expanded, its mark bit and the
/// cached degree sum of the rest. A vertex is marked on enqueue, so every
/// marked vertex is reachable from the side's endpoint and queued once.
struct SearchSide<'s> {
    queue: &'s mut Vec<usize>,
    own: u64,
    cursor: usize,
    pending: Option<usize>,
}

impl<'s> SearchSide<'s> {
    /// Starts a side at `endpoint` on an empty queue and clean marks.
    fn new(queue: &'s mut Vec<usize>, marks: &mut [u64], endpoint: usize, own: u64) -> Self {
        marks[endpoint >> 5] |= own << mark_shift(endpoint);
        queue.push(endpoint);
        Self {
            queue,
            own,
            cursor: 0,
            pending: None,
        }
    }

    /// Sum of the degrees of the marked, unexpanded vertices. It is computed
    /// once per round of this side, over vertices that round produced, so its
    /// cost is bounded by the entries already examined.
    fn pending_degree(&mut self, adjacency: &[Vec<usize>]) -> usize {
        *self.pending.get_or_insert_with(|| {
            self.queue[self.cursor..]
                .iter()
                .map(|&vertex| adjacency[vertex].len())
                .sum()
        })
    }

    /// Expands queued vertices in order for one round of at least
    /// `max(pending, floor)` entries; the first vertex always expands.
    /// Returns `Some(true)` on reaching a vertex marked by the other side,
    /// `Some(false)` when the queue is exhausted, and `None` when the round
    /// ends undecided.
    fn expand(
        &mut self,
        adjacency: &[Vec<usize>],
        marks: &mut [u64],
        pending: usize,
        floor: usize,
    ) -> Option<bool> {
        self.pending = None;
        expand_round(
            adjacency,
            marks,
            self.own,
            self.queue,
            &mut self.cursor,
            pending.max(floor),
        )
    }
}

/// The loop of [`SearchSide::expand`], with the side's state passed as
/// separate arguments and the cursor kept in a local.
fn expand_round(
    adjacency: &[Vec<usize>],
    marks: &mut [u64],
    own: u64,
    queue: &mut Vec<usize>,
    cursor_out: &mut usize,
    budget: usize,
) -> Option<bool> {
    let mut cursor = *cursor_out;
    let mut examined = 0;
    let outcome = loop {
        let Some(&vertex) = queue.get(cursor) else {
            break Some(false);
        };
        let neighbors = &adjacency[vertex];
        if examined > 0 && examined + neighbors.len() > budget {
            break None;
        }
        cursor += 1;
        examined += neighbors.len();
        let mut met = false;
        for &neighbor in neighbors {
            let word = &mut marks[neighbor >> 5];
            let shift = mark_shift(neighbor);
            let bits = (*word >> shift) & 0b11;
            if bits == 0 {
                *word |= own << shift;
                queue.push(neighbor);
            } else if bits != own {
                met = true;
                break;
            }
        }
        if met {
            break Some(true);
        }
    };
    *cursor_out = cursor;
    outcome
}

impl Graph {
    /// Reports whether `node` is registered; expected O(1) ID-map lookup.
    pub(crate) fn contains_node(&self, node: NodeId) -> bool {
        self.ids.contains_key(&node)
    }

    pub(crate) fn contains_edge(&self, source: NodeId, target: NodeId) -> bool {
        let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
            return false;
        };
        self.adjacency[a].binary_search(&b).is_ok()
    }

    /// Creates an empty graph in O(1) time.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Returns the stable internal index for `node`, registering it if absent.
    ///
    /// Preserves append-only indexing and O(1) amortized time.
    #[inline]
    fn get_or_insert_index(&mut self, node: NodeId) -> usize {
        match self.ids.entry(node) {
            Entry::Occupied(entry) => *entry.get(),
            Entry::Vacant(entry) => {
                let index = self.adjacency.len();
                self.adjacency.push(Vec::new());
                if let Some(nodes) = &mut self.nodes {
                    nodes.push(node);
                }
                entry.insert(index);
                index
            }
        }
    }

    /// Adds an isolated vertex, returning true only if it was absent.
    ///
    /// Existing edges are unchanged. O(1) amortized time; growing the outer
    /// vector can take O(V) in a single insertion. Indices never change.
    pub fn add_node(&mut self, node: NodeId) -> bool {
        if let Entry::Vacant(entry) = self.ids.entry(node) {
            let index = self.adjacency.len();
            self.adjacency.push(Vec::new());
            if let Some(nodes) = &mut self.nodes {
                nodes.push(node);
            }
            entry.insert(index);
            true
        } else {
            false
        }
    }

    /// Inserts an undirected edge, creating absent endpoints.
    ///
    /// Reversed endpoints identify the same edge; duplicates return false.
    /// O(1 + deg(source) + deg(target)) amortized time, including sorted
    /// vector shifts. A new vertex can trigger an O(V) capacity growth.
    ///
    /// # Errors
    /// Returns [`GraphError::SelfLoop`] without creating vertices for equal IDs.
    pub fn link(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        GraphError::check_distinct(source, target)?;
        let a = self.get_or_insert_index(source);
        let b = self.get_or_insert_index(target);
        let Err(position) = self.adjacency[a].binary_search(&b) else {
            return Ok(false);
        };
        let reverse = self.adjacency[b]
            .binary_search(&a)
            .expect_err("symmetric absence");
        self.adjacency[a].insert(position, b);
        self.adjacency[b].insert(reverse, a);
        self.edges += 1;
        Ok(true)
    }

    /// Removes an edge, preserving vertices; absent edges return false.
    ///
    /// Worst-case time: O(1 + deg(source) + deg(target)), due to vector shifts.
    ///
    /// # Errors
    /// Returns [`GraphError::SelfLoop`] for equal IDs without changing the graph.
    pub fn cut(&mut self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        GraphError::check_distinct(source, target)?;
        let (Some(&a), Some(&b)) = (self.ids.get(&source), self.ids.get(&target)) else {
            return Ok(false);
        };
        let Ok(position) = self.adjacency[a].binary_search(&b) else {
            return Ok(false);
        };
        let reverse = self.adjacency[b].binary_search(&a).expect("symmetric edge");
        self.adjacency[a].remove(position);
        self.adjacency[b].remove(reverse);
        self.edges -= 1;
        Ok(true)
    }

    /// Reports whether a path exists between two existing vertices.
    ///
    /// Existing vertices connect to themselves. Worst-case time O(V + E), with
    /// O(1) endpoint lookup. Scratch is per thread and reused: a query costs
    /// no allocation or O(V) initialization once the thread's scratch has
    /// grown, and shared queries need no internal lock. Each thread keeps at
    /// most 256 KiB of scratch between queries.
    ///
    /// The search grows from both endpoints and stops when they meet or when
    /// either side exhausts its component, so queries between nearby vertices,
    /// through hubs, or against a small component finish early. On path-like
    /// graphs it examines the same entries as a one-sided search from `source`.
    ///
    /// ```
    /// let mut graph = knotrel_core::Graph::new();
    /// graph.link(1, 2)?;
    /// graph.link(2, 3)?;
    /// graph.add_node(9);
    /// assert_eq!(graph.connected(1, 3), Ok(true));
    /// assert_eq!(graph.connected(1, 9), Ok(false));
    /// # Ok::<(), knotrel_core::GraphError>(())
    /// ```
    ///
    /// # Errors
    /// Returns [`GraphError::UnknownNode`] for absent endpoints, source first.
    pub fn connected(&self, source: NodeId, target: NodeId) -> Result<bool, GraphError> {
        let a = *self
            .ids
            .get(&source)
            .ok_or(GraphError::UnknownNode { node: source })?;
        let b = *self
            .ids
            .get(&target)
            .ok_or(GraphError::UnknownNode { node: target })?;
        if a == b {
            return Ok(true);
        }
        Ok(SCRATCH.with(|cell| match cell.try_borrow_mut() {
            Ok(mut scratch) => self.search(&mut scratch, a, b),
            // Re-entrant use on this thread (not expected): private scratch.
            Err(_) => self.search(&mut Scratch::default(), a, b),
        }))
    }

    /// The bidirectional search of [`Self::connected`] between distinct
    /// internal indices, on `scratch`, which it leaves clean.
    fn search(&self, scratch: &mut Scratch, a: usize, b: usize) -> bool {
        if scratch.dirty {
            *scratch = Scratch::default();
        }
        scratch.dirty = true;
        let words = self.adjacency.len().div_ceil(32);
        if scratch.marks.len() < words {
            scratch.marks.resize(words, 0);
        }
        let found = {
            let Scratch {
                marks,
                source,
                target,
                ..
            } = &mut *scratch;
            let mut source_side = SearchSide::new(source, marks, a, SOURCE);
            let mut target_side = SearchSide::new(target, marks, b, TARGET);
            // Each round expands the side with fewer pending incidences (the
            // source on a tie, so path-like graphs do a one-sided search), for
            // at least `floor` entries, without overshooting into a vertex
            // whose list would exceed the round. The floor starts at
            // FIRST_ROUND and doubles up to MIN_ROUND. Any edge between the
            // two marked sets proves a path; an exhausted queue proves its
            // endpoint's component holds no vertex of the other side. Each
            // vertex is expanded at most once: O(V + E).
            let mut floor = FIRST_ROUND;
            loop {
                let source_pending = source_side.pending_degree(&self.adjacency);
                let target_pending = target_side.pending_degree(&self.adjacency);
                let outcome = if target_pending < source_pending {
                    target_side.expand(&self.adjacency, marks, target_pending, floor)
                } else {
                    source_side.expand(&self.adjacency, marks, source_pending, floor)
                };
                if let Some(found) = outcome {
                    break found;
                }
                floor = (floor * 2).min(MIN_ROUND);
            }
        };
        scratch.reset();
        scratch.dirty = false;
        found
    }

    /// Returns the number of vertices, including isolated ones, in O(1) time.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.adjacency.len()
    }

    /// Returns the number of undirected edges in O(1) time.
    #[must_use]
    pub fn edge_count(&self) -> usize {
        self.edges
    }

    /// Builds a graph in one pass from validated adjacency (bulk construction
    /// for the lifecycle facade).
    ///
    /// `ids[i]` receives internal index `i`; `adjacency[i]` lists the indices
    /// of its neighbors. The caller guarantees the [`Graph`] invariants:
    /// distinct IDs, equal lengths, every list strictly sorted, symmetric
    /// (`j` in `adjacency[i]` iff `i` in `adjacency[j]`) and free of
    /// self-loops; debug builds verify them. Vectors are taken as they are,
    /// so their capacities are kept.
    ///
    /// `O(V + E)` time plus the ID-map insertions (expected `O(1)` each);
    /// no adjacency vector is reallocated.
    pub(crate) fn from_sorted_adjacency(ids: Vec<NodeId>, adjacency: Vec<Vec<usize>>) -> Self {
        assert_eq!(ids.len(), adjacency.len(), "one adjacency list per ID");
        let mut map: IdMap<usize> = IdMap::with_capacity_and_hasher(ids.len(), Default::default());
        for (index, &node) in ids.iter().enumerate() {
            let previous = map.insert(node, index);
            debug_assert!(previous.is_none(), "distinct IDs");
        }
        let incidences: usize = adjacency.iter().map(Vec::len).sum();
        debug_assert!(incidences.is_multiple_of(2), "symmetric adjacency");
        #[cfg(debug_assertions)]
        for (index, list) in adjacency.iter().enumerate() {
            for pair in list.windows(2) {
                debug_assert!(pair[0] < pair[1], "strictly sorted adjacency");
            }
            for &neighbor in list {
                debug_assert_ne!(neighbor, index, "no self-loops");
                debug_assert!(
                    adjacency[neighbor].binary_search(&index).is_ok(),
                    "symmetric adjacency"
                );
            }
        }
        Self {
            ids: map,
            nodes: None,
            adjacency,
            edges: incidences / 2,
        }
    }

    /// Returns the number of edges incident to `node`, or `None` if it is not
    /// registered. Expected O(1).
    ///
    /// ```rust
    /// let mut graph = knotrel_core::Graph::new();
    /// graph.link(1, 2)?;
    /// assert_eq!(graph.degree(1), Some(1));
    /// assert_eq!(graph.degree(9), None);
    /// # Ok::<(), knotrel_core::GraphError>(())
    /// ```
    #[must_use]
    pub fn degree(&self, node: NodeId) -> Option<usize> {
        self.ids
            .get(&node)
            .map(|&index| self.adjacency[index].len())
    }

    /// Starts keeping the ID of every internal index, which
    /// [`neighbors_after`](Self::neighbors_after) needs. Costs 8 bytes per vertex
    /// and one vector push per new vertex from now on; building the vector for
    /// the existing vertices is O(V). Calling it again does nothing.
    ///
    /// ```rust
    /// let mut graph = knotrel_core::Graph::new();
    /// graph.link(1, 2)?;
    /// assert!(graph.neighbors_after(1, None).is_err());
    /// graph.enable_neighbor_listing();
    /// assert_eq!(graph.neighbors_after(1, None)?.collect::<Vec<_>>(), [2]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn enable_neighbor_listing(&mut self) {
        if self.nodes.is_none() {
            let mut nodes = vec![0; self.adjacency.len()];
            for (&node, &index) in &self.ids {
                nodes[index] = node;
            }
            self.nodes = Some(nodes);
        }
    }

    /// Iterates the neighbors of `node` in the graph's stable incidence order,
    /// starting strictly after the neighbor `after` (or from the start).
    ///
    /// The order is the neighbors' registration order. It is stable across
    /// mutations: indices are never reused, so a neighbor present before and
    /// after a sequence of calls keeps its relative position. That makes
    /// `after` usable as a pagination cursor: every neighbor that stays linked
    /// while a caller pages through the list is visited exactly once, and
    /// neighbors linked or cut meanwhile may or may not be visited. `after`
    /// need not still be linked to `node`.
    ///
    /// Positioning costs O(log deg(node)) expected; each step is O(1).
    ///
    /// # Errors
    ///
    /// [`IncidenceError::NotEnabled`] before
    /// [`enable_neighbor_listing`](Self::enable_neighbor_listing),
    /// [`IncidenceError::UnknownNode`] if `node` is not registered, and
    /// [`IncidenceError::UnknownCursor`] if `after` is not a registered node.
    /// Vertices are never removed from a [`Graph`], so a cursor obtained from
    /// this graph never becomes unknown.
    ///
    /// ```rust
    /// let mut graph = knotrel_core::Graph::new();
    /// graph.enable_neighbor_listing();
    /// graph.link(5, 9)?;
    /// graph.link(5, 1)?;
    /// graph.link(5, 7)?;
    /// let all: Vec<_> = graph.neighbors_after(5, None)?.collect();
    /// assert_eq!(all, [9, 1, 7]); // registration order, not ID order
    /// let rest: Vec<_> = graph.neighbors_after(5, Some(9))?.collect();
    /// assert_eq!(rest, [1, 7]);
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn neighbors_after(
        &self,
        node: NodeId,
        after: Option<NodeId>,
    ) -> Result<impl Iterator<Item = NodeId> + '_, IncidenceError> {
        let &index = self.ids.get(&node).ok_or(IncidenceError::UnknownNode)?;
        let list = &self.adjacency[index];
        let start = match after {
            None => 0,
            Some(cursor) => {
                let &cursor = self.ids.get(&cursor).ok_or(IncidenceError::UnknownCursor)?;
                list.partition_point(|&neighbor| neighbor <= cursor)
            }
        };
        let nodes = self.nodes.as_deref().ok_or(IncidenceError::NotEnabled)?;
        Ok(list[start..].iter().map(move |&neighbor| nodes[neighbor]))
    }

    /// Releases the adjacency allocation of an isolated vertex.
    ///
    /// A no-op for an absent node or one that still has edges. The vertex and
    /// its index stay registered. `O(1)` expected.
    pub(crate) fn release_isolated_storage(&mut self, node: NodeId) {
        if let Some(&index) = self.ids.get(&node) {
            let list = &mut self.adjacency[index];
            if list.is_empty() {
                *list = Vec::new();
            }
        }
    }

    /// Returns the adjacency capacity (elements) held by `node`, if present.
    #[cfg(test)]
    pub(crate) fn adjacency_capacity(&self, node: NodeId) -> Option<usize> {
        self.ids
            .get(&node)
            .map(|&index| self.adjacency[index].capacity())
    }
}

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

    /// Resetting scratch clears every mark (per vertex, or in one pass when
    /// cheaper) and drops buffers above the retention caps.
    #[test]
    fn scratch_reset_clears_marks_and_enforces_caps() {
        let mut scratch = Scratch::default();
        scratch.marks.resize(1_000, 0);
        scratch.marks[0] |= SOURCE << mark_shift(3);
        scratch.marks[1] |= TARGET << mark_shift(40);
        scratch.source.push(3);
        scratch.target.push(40);
        scratch.reset();
        assert_eq!(scratch.marks.len(), 1_000);
        assert!(scratch.marks.iter().all(|&word| word == 0));
        assert!(scratch.source.is_empty() && scratch.target.is_empty());

        scratch.marks.resize(RETAIN_MARK_WORDS + 1, 0);
        scratch.source.reserve(RETAIN_QUEUE + 1);
        scratch.target.reserve(RETAIN_QUEUE + 1);
        for vertex in 0..RETAIN_QUEUE {
            scratch.marks[vertex >> 5] |= SOURCE << mark_shift(vertex);
            scratch.source.push(vertex);
        }
        scratch.reset();
        assert_eq!(
            (
                scratch.marks.len(),
                scratch.source.capacity(),
                scratch.target.capacity()
            ),
            (0, 0, 0)
        );
    }

    /// Two mark bits per vertex: every vertex of a word gets its own pair.
    #[test]
    fn mark_shift_gives_each_vertex_of_a_word_its_own_pair() {
        let shifts: Vec<u32> = (0..32).map(mark_shift).collect();
        assert_eq!(shifts, (0..32).map(|i| i * 2).collect::<Vec<_>>());
        assert_eq!(mark_shift(32), 0);
        assert_eq!(mark_shift(63), 62);
    }

    /// The ID hasher keeps sequential IDs in order, spreads IDs that differ
    /// only in high bits, and repeats the low 7 bits in the control tag.
    #[test]
    fn id_hasher_folds_high_bits_and_tags_low_bits() {
        let hash = |id: u64| {
            let mut hasher = IdHasher::default();
            hasher.write_u64(id);
            hasher.finish()
        };
        let low = |h: u64| h & ((1 << 57) - 1);
        assert_eq!(
            (0..100).map(|i| low(hash(i))).collect::<Vec<_>>(),
            (0..100).collect::<Vec<_>>()
        );
        for shift in [16, 32, 48] {
            let buckets: std::collections::HashSet<u64> =
                (0..1_000).map(|i| low(hash(i << shift)) & 0xFFFF).collect();
            assert_eq!(buckets.len(), 1_000, "shift {shift}");
        }
        assert_eq!(hash(5) >> 57, 5);
        assert_eq!(hash(130) >> 57, 2);
        let mut bytes = IdHasher::default();
        bytes.write(&[1, 2]);
        assert_eq!(bytes.0, 0x0102);
    }

    /// A search that unwound leaves its scratch dirty; the next query starts
    /// from fresh scratch, so stale marks cannot change its answer.
    #[test]
    fn dirty_scratch_is_replaced_before_the_next_query() {
        let mut graph = Graph::new();
        graph.link(0, 1).unwrap();
        graph.link(2, 3).unwrap();
        SCRATCH.with(|cell| {
            let mut scratch = cell.borrow_mut();
            scratch.dirty = true;
            scratch.marks = vec![u64::MAX];
            scratch.source.push(1);
        });
        assert!(!graph.connected(0, 3).unwrap());
        assert!(graph.connected(2, 3).unwrap());
        SCRATCH.with(|cell| {
            let scratch = cell.borrow();
            assert!(!scratch.dirty);
            assert!(scratch.marks.iter().all(|&word| word == 0));
            assert!(scratch.source.is_empty() && scratch.target.is_empty());
        });
    }

    /// A query issued while this thread's scratch is borrowed uses private
    /// scratch and still answers correctly.
    #[test]
    fn query_with_borrowed_thread_scratch_uses_private_scratch() {
        let mut graph = Graph::new();
        graph.link(0, 1).unwrap();
        graph.link(1, 2).unwrap();
        graph.link(5, 6).unwrap();
        SCRATCH.with(|cell| {
            let _held = cell.borrow_mut();
            assert!(graph.connected(0, 2).unwrap());
            assert!(!graph.connected(0, 6).unwrap());
        });
    }

    /// Paging through a hub's neighbors with `neighbors_after` visits every
    /// neighbor that stays linked exactly once, even when other edges are cut
    /// and added between pages; cursors stay valid after their edge is cut.
    #[test]
    fn neighbor_pages_visit_stable_neighbors_exactly_once() {
        let mut graph = Graph::new();
        graph.link(0, 3).unwrap();
        assert_eq!(
            graph.neighbors_after(0, None).err(),
            Some(IncidenceError::NotEnabled)
        );
        // Enabling after vertices exist rebuilds the index-to-ID vector.
        graph.enable_neighbor_listing();
        graph.enable_neighbor_listing();
        graph.cut(0, 3).unwrap();
        for neighbor in 1..=100u64 {
            graph.link(0, neighbor * 7).unwrap();
        }
        let stable: Vec<u64> = (1..=100u64).filter(|n| n % 3 != 0).map(|n| n * 7).collect();
        let mut seen = Vec::new();
        let mut cursor = None;
        let mut round = 0u64;
        loop {
            let page: Vec<u64> = graph.neighbors_after(0, cursor).unwrap().take(9).collect();
            let Some(&last) = page.last() else { break };
            seen.extend(page);
            cursor = Some(last);
            // Between pages: cut neighbors that are not "stable" (including the
            // cursor itself) and link new ones.
            for n in (1..=100u64).filter(|n| n % 3 == 0) {
                let _ = graph.cut(0, n * 7);
            }
            // New neighbors are appended after the cursor; stop adding them after
            // a few rounds so the traversal terminates.
            if round < 5 {
                round += 1;
                graph.link(0, 10_000 + round).unwrap();
            }
        }
        for node in &stable {
            assert_eq!(seen.iter().filter(|&&s| s == *node).count(), 1, "{node}");
        }
        assert_eq!(graph.degree(0), Some(stable.len() + round as usize));
        assert_eq!(graph.degree(424_242), None);
        assert_eq!(
            graph.neighbors_after(424_242, None).err(),
            Some(IncidenceError::UnknownNode)
        );
        assert_eq!(
            graph.neighbors_after(0, Some(424_242)).err(),
            Some(IncidenceError::UnknownCursor)
        );
        assert_eq!(
            IncidenceError::UnknownCursor.to_string(),
            "unknown incidence cursor"
        );
        assert_eq!(IncidenceError::UnknownNode.to_string(), "unknown node");
        assert_eq!(
            IncidenceError::NotEnabled.to_string(),
            "neighbor listing is not enabled"
        );
    }

    /// A bulk-built graph maps indices back to the same IDs as an incremental one.
    #[test]
    fn bulk_built_graph_lists_neighbors_by_id() {
        let ids = vec![u64::MAX, 3, 9_007_199_254_740_993];
        let adjacency = vec![vec![1, 2], vec![0], vec![0]];
        let mut graph = Graph::from_sorted_adjacency(ids, adjacency);
        graph.enable_neighbor_listing();
        let neighbors: Vec<u64> = graph.neighbors_after(u64::MAX, None).unwrap().collect();
        assert_eq!(neighbors, [3, 9_007_199_254_740_993]);
        assert_eq!(graph.degree(3), Some(1));
    }

    /// A bulk-built graph keeps every `Graph` invariant and then behaves like
    /// an incrementally built one under further `add_node`, `link`, `cut` and
    /// `connected` calls.
    #[test]
    fn bulk_built_graph_matches_incremental_graph_under_mutation() {
        let mut seed = 0x2545_f491_u64;
        let mut next = move |bound: u64| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed % bound
        };
        for _case in 0..200 {
            let n = 1 + next(30) as usize;
            let ids: Vec<NodeId> = (0..n as u64).map(|i| i * 7 + 3).collect();
            let mut incremental = Graph::new();
            for &id in &ids {
                incremental.add_node(id);
            }
            let mut adjacency = vec![Vec::new(); n];
            for _ in 0..next(3 * n as u64 + 1) {
                let (a, b) = (next(n as u64) as usize, next(n as u64) as usize);
                if a != b && incremental.link(ids[a], ids[b]) == Ok(true) {
                    adjacency[a].push(b);
                    adjacency[b].push(a);
                }
            }
            for list in &mut adjacency {
                list.sort_unstable();
            }
            let mut bulk = Graph::from_sorted_adjacency(ids.clone(), adjacency);
            assert_eq!(bulk.node_count(), incremental.node_count());
            assert_eq!(bulk.edge_count(), incremental.edge_count());
            for _ in 0..100 {
                let a = next(n as u64 + 5) * 7 + 3;
                let b = next(n as u64 + 5) * 7 + 3;
                match next(4) {
                    0 => assert_eq!(bulk.add_node(a), incremental.add_node(a)),
                    1 => assert_eq!(bulk.link(a, b), incremental.link(a, b)),
                    2 => assert_eq!(bulk.cut(a, b), incremental.cut(a, b)),
                    _ => assert_eq!(bulk.connected(a, b), incremental.connected(a, b)),
                }
                assert_eq!(bulk.edge_count(), incremental.edge_count());
                assert_eq!(bulk.node_count(), incremental.node_count());
            }
            for list in &bulk.adjacency {
                assert!(list.windows(2).all(|pair| pair[0] < pair[1]));
            }
            bulk.release_isolated_storage(ids[0]);
            assert_eq!(bulk.connected(ids[0], ids[0]), Ok(true));
        }
    }

    #[test]
    fn link_preserves_internal_source_before_target_index_order() {
        let mut graph = Graph::new();
        // Link two fresh nodes: source 42, target 99.
        assert_eq!(graph.link(42, 99), Ok(true));
        // Directly verify the internal index mapping:
        // source (42) must receive internal index 0; target (99) must receive internal index 1.
        assert_eq!(graph.ids.get(&42), Some(&0));
        assert_eq!(graph.ids.get(&99), Some(&1));
        assert_eq!(graph.adjacency[0], vec![1]);
        assert_eq!(graph.adjacency[1], vec![0]);

        // Link with one existing endpoint: source 42 (existing index 0), target 1000 (fresh).
        assert_eq!(graph.link(42, 1000), Ok(true));
        assert_eq!(graph.ids.get(&1000), Some(&2));
        assert_eq!(graph.adjacency[0], vec![1, 2]);
        assert_eq!(graph.adjacency[2], vec![0]);

        // Link with one existing endpoint: source 2000 (fresh), target 99 (existing index 1).
        assert_eq!(graph.link(2000, 99), Ok(true));
        assert_eq!(graph.ids.get(&2000), Some(&3));
        assert_eq!(graph.adjacency[1], vec![0, 3]);
        assert_eq!(graph.adjacency[3], vec![1]);

        // Link with two existing endpoints: 1000 (index 2) and 2000 (index 3).
        assert_eq!(graph.link(1000, 2000), Ok(true));
        assert_eq!(graph.ids.get(&1000), Some(&2));
        assert_eq!(graph.ids.get(&2000), Some(&3));
        assert_eq!(graph.adjacency[2], vec![0, 3]);
        assert_eq!(graph.adjacency[3], vec![1, 2]);
    }
}