Skip to main content

grafeo_core/index/
adjacency.rs

1//! Chunked adjacency lists - the core data structure for graph traversal.
2//!
3//! Every graph database needs fast neighbor lookups. This implementation uses
4//! chunked storage with delta buffers, giving you:
5//!
6//! - **O(1) amortized inserts** - new edges go into a delta buffer
7//! - **Cache-friendly scans** - chunks are sized for L1/L2 cache
8//! - **Soft deletes** - deletions don't require recompaction
9//! - **Concurrent reads** - RwLock allows many simultaneous traversals
10//! - **Compression** - cold chunks can be compressed using DeltaBitPacked
11
12use crate::storage::{BitPackedInts, DeltaBitPacked};
13use grafeo_common::types::{EdgeId, NodeId};
14use grafeo_common::utils::hash::{FxHashMap, FxHashSet};
15use parking_lot::RwLock;
16use smallvec::SmallVec;
17use std::sync::atomic::{AtomicUsize, Ordering};
18
19/// Default chunk capacity (number of edges per chunk).
20const DEFAULT_CHUNK_CAPACITY: usize = 64;
21
22/// Threshold for delta buffer compaction.
23///
24/// Lower values reduce memory overhead and iteration cost for delta buffers,
25/// but increase compaction frequency. 64 provides a good balance for typical workloads.
26const DELTA_COMPACTION_THRESHOLD: usize = 64;
27
28/// Threshold for cold chunk compression.
29///
30/// When the number of hot chunks exceeds this threshold, the oldest hot chunks
31/// are compressed and moved to cold storage. This balances memory usage with
32/// the cost of compression/decompression.
33const COLD_COMPRESSION_THRESHOLD: usize = 4;
34
35/// A chunk of adjacency entries.
36#[derive(Debug, Clone)]
37struct AdjacencyChunk {
38    /// Destination node IDs.
39    destinations: Vec<NodeId>,
40    /// Edge IDs (parallel to destinations).
41    edge_ids: Vec<EdgeId>,
42    /// Capacity of this chunk.
43    capacity: usize,
44}
45
46impl AdjacencyChunk {
47    fn new(capacity: usize) -> Self {
48        Self {
49            destinations: Vec::with_capacity(capacity),
50            edge_ids: Vec::with_capacity(capacity),
51            capacity,
52        }
53    }
54
55    fn len(&self) -> usize {
56        self.destinations.len()
57    }
58
59    fn is_full(&self) -> bool {
60        self.destinations.len() >= self.capacity
61    }
62
63    fn push(&mut self, dst: NodeId, edge_id: EdgeId) -> bool {
64        if self.is_full() {
65            return false;
66        }
67        self.destinations.push(dst);
68        self.edge_ids.push(edge_id);
69        true
70    }
71
72    fn iter(&self) -> impl Iterator<Item = (NodeId, EdgeId)> + '_ {
73        self.destinations
74            .iter()
75            .copied()
76            .zip(self.edge_ids.iter().copied())
77    }
78
79    /// Compresses this chunk into a `CompressedAdjacencyChunk`.
80    ///
81    /// The entries are sorted by destination node ID for better delta compression.
82    /// Use this for cold chunks that won't be modified.
83    fn compress(&self) -> CompressedAdjacencyChunk {
84        // Sort entries by destination for better delta compression
85        let mut entries: Vec<_> = self
86            .destinations
87            .iter()
88            .copied()
89            .zip(self.edge_ids.iter().copied())
90            .collect();
91        entries.sort_by_key(|(dst, _)| dst.as_u64());
92
93        // Extract sorted destinations and corresponding edge IDs
94        let sorted_dsts: Vec<u64> = entries.iter().map(|(d, _)| d.as_u64()).collect();
95        let sorted_edges: Vec<u64> = entries.iter().map(|(_, e)| e.as_u64()).collect();
96
97        let max_destination = sorted_dsts.last().copied().unwrap_or(0);
98
99        CompressedAdjacencyChunk {
100            destinations: DeltaBitPacked::encode(&sorted_dsts),
101            edge_ids: BitPackedInts::pack(&sorted_edges),
102            count: entries.len(),
103            max_destination,
104        }
105    }
106}
107
108/// A compressed chunk of adjacency entries.
109///
110/// Uses DeltaBitPacked for destination node IDs (sorted for good compression)
111/// and BitPackedInts for edge IDs. Typical compression ratio is 5-10x for
112/// dense adjacency lists.
113#[derive(Debug, Clone)]
114struct CompressedAdjacencyChunk {
115    /// Delta + bit-packed destination node IDs (sorted).
116    destinations: DeltaBitPacked,
117    /// Bit-packed edge IDs.
118    edge_ids: BitPackedInts,
119    /// Number of entries.
120    count: usize,
121    /// Maximum destination node ID (last element in sorted order).
122    max_destination: u64,
123}
124
125impl CompressedAdjacencyChunk {
126    /// Returns the number of entries in this chunk.
127    fn len(&self) -> usize {
128        self.count
129    }
130
131    /// Returns true if this chunk is empty.
132    #[cfg(test)]
133    fn is_empty(&self) -> bool {
134        self.count == 0
135    }
136
137    /// Decompresses and iterates over all entries.
138    fn iter(&self) -> impl Iterator<Item = (NodeId, EdgeId)> + '_ {
139        let dsts = self.destinations.decode();
140        let edges = self.edge_ids.unpack();
141
142        dsts.into_iter()
143            .zip(edges)
144            .map(|(d, e)| (NodeId::new(d), EdgeId::new(e)))
145    }
146
147    /// Returns the approximate memory size in bytes.
148    fn memory_size(&self) -> usize {
149        // DeltaBitPacked: 8 bytes base + packed deltas
150        // BitPackedInts: packed data
151        let dest_size = 8 + self.destinations.to_bytes().len();
152        let edge_size = self.edge_ids.data().len() * 8;
153        dest_size + edge_size
154    }
155
156    /// Returns the minimum destination ID in this chunk.
157    #[must_use]
158    fn min_destination(&self) -> u64 {
159        self.destinations.base()
160    }
161
162    /// Returns `(destination, edge_id)` pairs where destination is in `[min, max]`.
163    ///
164    /// Uses zone-map pruning to skip chunks entirely when the range doesn't
165    /// overlap, then `partition_point` for efficient sub-range extraction.
166    fn destinations_in_range(&self, min: u64, max: u64) -> Vec<(NodeId, EdgeId)> {
167        if min > self.max_destination || max < self.destinations.base() {
168            return Vec::new();
169        }
170        let destinations = self.destinations.decode();
171        let edges = self.edge_ids.unpack();
172        let start = destinations.partition_point(|&d| d < min);
173        let end = destinations.partition_point(|&d| d <= max);
174        destinations[start..end]
175            .iter()
176            .zip(&edges[start..end])
177            .map(|(&d, &e)| (NodeId::new(d), EdgeId::new(e)))
178            .collect()
179    }
180
181    /// Returns the compression ratio compared to uncompressed storage.
182    #[cfg(test)]
183    fn compression_ratio(&self) -> f64 {
184        if self.count == 0 {
185            return 1.0;
186        }
187        let uncompressed = self.count * 16; // 8 bytes each for NodeId and EdgeId
188        let compressed = self.memory_size();
189        if compressed == 0 {
190            return f64::INFINITY;
191        }
192        uncompressed as f64 / compressed as f64
193    }
194}
195
196/// Zone map entry for a single compressed cold chunk.
197///
198/// The skip index stores one entry per cold chunk, sorted by `min_destination`.
199/// Binary search on this index identifies which chunks might contain a target
200/// destination without decompressing any data.
201#[derive(Debug, Clone, Copy)]
202struct SkipIndexEntry {
203    /// Minimum destination ID in the chunk (from `DeltaBitPacked::base()`).
204    min_destination: u64,
205    /// Maximum destination ID in the chunk.
206    max_destination: u64,
207    /// Index into `AdjacencyList::cold_chunks`.
208    chunk_index: usize,
209}
210
211/// Adjacency list for a single node.
212///
213/// Uses a tiered storage model:
214/// - **Hot chunks**: Recent data, uncompressed for fast modification
215/// - **Cold chunks**: Older data, compressed for memory efficiency
216/// - **Delta buffer**: Very recent insertions, not yet compacted
217/// - **Skip index**: Zone map over cold chunks for O(log n) point lookups
218#[derive(Debug)]
219struct AdjacencyList {
220    /// Hot chunks (mutable, uncompressed) - for recent data.
221    hot_chunks: Vec<AdjacencyChunk>,
222    /// Cold chunks (immutable, compressed) - for older data.
223    cold_chunks: Vec<CompressedAdjacencyChunk>,
224    /// Delta buffer for recent insertions.
225    /// Uses SmallVec with 16 inline entries for cache-friendly access.
226    /// Most nodes have <16 recent insertions before compaction, so this
227    /// avoids heap allocation in the common case.
228    delta_inserts: SmallVec<[(NodeId, EdgeId); 16]>,
229    /// Set of deleted edge IDs.
230    deleted: FxHashSet<EdgeId>,
231    /// Zone map skip index over cold chunks, sorted by `min_destination`.
232    /// Enables O(log n) point lookups and range queries without decompressing
233    /// all cold chunks.
234    skip_index: Vec<SkipIndexEntry>,
235}
236
237impl AdjacencyList {
238    fn new() -> Self {
239        Self {
240            hot_chunks: Vec::new(),
241            cold_chunks: Vec::new(),
242            delta_inserts: SmallVec::new(),
243            deleted: FxHashSet::default(),
244            skip_index: Vec::new(),
245        }
246    }
247
248    fn add_edge(&mut self, dst: NodeId, edge_id: EdgeId) {
249        // Try to add to the last hot chunk
250        if let Some(last) = self.hot_chunks.last_mut()
251            && last.push(dst, edge_id)
252        {
253            return;
254        }
255
256        // Add to delta buffer
257        self.delta_inserts.push((dst, edge_id));
258    }
259
260    fn mark_deleted(&mut self, edge_id: EdgeId) {
261        self.deleted.insert(edge_id);
262    }
263
264    fn compact(&mut self, chunk_capacity: usize) {
265        if self.delta_inserts.is_empty() {
266            return;
267        }
268
269        // Create new chunks from delta buffer
270        // Check if last hot chunk has room, and if so, pop it to continue filling
271        let last_has_room = self.hot_chunks.last().is_some_and(|c| !c.is_full());
272        let mut current_chunk = if last_has_room {
273            // Invariant: is_some_and() returned true, so hot_chunks is non-empty
274            self.hot_chunks
275                .pop()
276                .expect("hot_chunks is non-empty: is_some_and() succeeded on previous line")
277        } else {
278            AdjacencyChunk::new(chunk_capacity)
279        };
280
281        for (dst, edge_id) in self.delta_inserts.drain(..) {
282            if !current_chunk.push(dst, edge_id) {
283                self.hot_chunks.push(current_chunk);
284                current_chunk = AdjacencyChunk::new(chunk_capacity);
285                current_chunk.push(dst, edge_id);
286            }
287        }
288
289        if current_chunk.len() > 0 {
290            self.hot_chunks.push(current_chunk);
291        }
292
293        // Check if we should compress some hot chunks to cold
294        self.maybe_compress_to_cold();
295    }
296
297    /// Compresses oldest hot chunks to cold storage if threshold exceeded.
298    ///
299    /// Builds skip index entries for each new cold chunk, enabling O(log n)
300    /// point lookups via zone-map pruning.
301    fn maybe_compress_to_cold(&mut self) {
302        // Keep at least COLD_COMPRESSION_THRESHOLD hot chunks for write performance
303        while self.hot_chunks.len() > COLD_COMPRESSION_THRESHOLD {
304            // Remove the oldest (first) hot chunk
305            let oldest = self.hot_chunks.remove(0);
306
307            // Skip empty chunks
308            if oldest.len() == 0 {
309                continue;
310            }
311
312            // Compress and add to cold storage
313            let compressed = oldest.compress();
314            let chunk_index = self.cold_chunks.len();
315            self.skip_index.push(SkipIndexEntry {
316                min_destination: compressed.min_destination(),
317                max_destination: compressed.max_destination,
318                chunk_index,
319            });
320            self.cold_chunks.push(compressed);
321        }
322        // Maintain sort order for binary search
323        self.skip_index.sort_unstable_by_key(|e| e.min_destination);
324    }
325
326    /// Forces all hot chunks to be compressed to cold storage.
327    ///
328    /// Useful when memory pressure is high or the node is rarely accessed.
329    /// Rebuilds the skip index to include all newly compressed chunks.
330    fn freeze_all(&mut self) {
331        for chunk in self.hot_chunks.drain(..) {
332            if chunk.len() > 0 {
333                let compressed = chunk.compress();
334                let chunk_index = self.cold_chunks.len();
335                self.skip_index.push(SkipIndexEntry {
336                    min_destination: compressed.min_destination(),
337                    max_destination: compressed.max_destination,
338                    chunk_index,
339                });
340                self.cold_chunks.push(compressed);
341            }
342        }
343        self.skip_index.sort_unstable_by_key(|e| e.min_destination);
344    }
345
346    fn iter(&self) -> impl Iterator<Item = (NodeId, EdgeId)> + '_ {
347        let deleted = &self.deleted;
348
349        // Iterate cold chunks first (oldest data)
350        let cold_iter = self.cold_chunks.iter().flat_map(|c| c.iter());
351
352        // Then hot chunks
353        let hot_iter = self.hot_chunks.iter().flat_map(|c| c.iter());
354
355        // Finally delta buffer (newest data)
356        let delta_iter = self.delta_inserts.iter().copied();
357
358        cold_iter
359            .chain(hot_iter)
360            .chain(delta_iter)
361            .filter(move |(_, edge_id)| !deleted.contains(edge_id))
362    }
363
364    /// Checks whether a specific destination node exists in this list.
365    ///
366    /// Uses the skip index for O(log n) lookup over cold chunks (only
367    /// decompresses chunks whose zone maps overlap the target). Then scans
368    /// hot chunks and the delta buffer linearly. Respects soft-deleted edges.
369    fn contains(&self, destination: NodeId) -> bool {
370        let dst_raw = destination.as_u64();
371        let deleted = &self.deleted;
372
373        // Cold chunks: use skip index to find candidate chunks
374        for entry in &self.skip_index {
375            if dst_raw < entry.min_destination || dst_raw > entry.max_destination {
376                continue;
377            }
378            let chunk = &self.cold_chunks[entry.chunk_index];
379            let decoded_dsts = chunk.destinations.decode();
380            let decoded_edges = chunk.edge_ids.unpack();
381            if let Ok(pos) = decoded_dsts.binary_search(&dst_raw) {
382                // Check this position and adjacent duplicates
383                let mut i = pos;
384                while i > 0 && decoded_dsts[i - 1] == dst_raw {
385                    i -= 1;
386                }
387                for j in i..decoded_dsts.len() {
388                    if decoded_dsts[j] != dst_raw {
389                        break;
390                    }
391                    if !deleted.contains(&EdgeId::new(decoded_edges[j])) {
392                        return true;
393                    }
394                }
395            }
396        }
397
398        // Hot chunks: linear scan (small, unsorted)
399        for chunk in &self.hot_chunks {
400            for (dst, edge_id) in chunk.iter() {
401                if dst == destination && !deleted.contains(&edge_id) {
402                    return true;
403                }
404            }
405        }
406
407        // Delta buffer: linear scan
408        for &(dst, edge_id) in &self.delta_inserts {
409            if dst == destination && !deleted.contains(&edge_id) {
410                return true;
411            }
412        }
413
414        false
415    }
416
417    /// Returns edges whose destination falls in `[min, max]` (inclusive).
418    ///
419    /// Uses skip index zone-map pruning over cold chunks, then linear scan
420    /// of hot chunks and delta buffer. Respects soft-deleted edges.
421    fn destinations_in_range(&self, min: NodeId, max: NodeId) -> Vec<(NodeId, EdgeId)> {
422        let min_raw = min.as_u64();
423        let max_raw = max.as_u64();
424        let deleted = &self.deleted;
425        let mut results = Vec::new();
426
427        // Cold chunks: skip index prunes non-overlapping chunks
428        for entry in &self.skip_index {
429            if entry.max_destination < min_raw || entry.min_destination > max_raw {
430                continue;
431            }
432            let chunk = &self.cold_chunks[entry.chunk_index];
433            results.extend(
434                chunk
435                    .destinations_in_range(min_raw, max_raw)
436                    .into_iter()
437                    .filter(|(_, eid)| !deleted.contains(eid)),
438            );
439        }
440
441        // Hot chunks: linear scan
442        for chunk in &self.hot_chunks {
443            for (dst, edge_id) in chunk.iter() {
444                if dst.as_u64() >= min_raw && dst.as_u64() <= max_raw && !deleted.contains(&edge_id)
445                {
446                    results.push((dst, edge_id));
447                }
448            }
449        }
450
451        // Delta buffer: linear scan
452        for &(dst, edge_id) in &self.delta_inserts {
453            if dst.as_u64() >= min_raw && dst.as_u64() <= max_raw && !deleted.contains(&edge_id) {
454                results.push((dst, edge_id));
455            }
456        }
457
458        results
459    }
460
461    fn neighbors(&self) -> impl Iterator<Item = NodeId> + '_ {
462        self.iter().map(|(dst, _)| dst)
463    }
464
465    fn degree(&self) -> usize {
466        self.iter().count()
467    }
468
469    /// Returns the number of entries in hot storage.
470    fn hot_count(&self) -> usize {
471        self.hot_chunks.iter().map(|c| c.len()).sum::<usize>() + self.delta_inserts.len()
472    }
473
474    /// Returns the number of entries in cold storage.
475    fn cold_count(&self) -> usize {
476        self.cold_chunks.iter().map(|c| c.len()).sum()
477    }
478
479    /// Returns the approximate memory size in bytes.
480    #[cfg(test)]
481    fn memory_size(&self) -> usize {
482        // Hot chunks: full uncompressed size
483        let hot_size = self.hot_chunks.iter().map(|c| c.len() * 16).sum::<usize>();
484
485        // Cold chunks: compressed size
486        let cold_size = self
487            .cold_chunks
488            .iter()
489            .map(|c| c.memory_size())
490            .sum::<usize>();
491
492        // Delta buffer
493        let delta_size = self.delta_inserts.len() * 16;
494
495        // Deleted set (rough estimate)
496        let deleted_size = self.deleted.len() * 16;
497
498        hot_size + cold_size + delta_size + deleted_size
499    }
500}
501
502/// The main structure for traversing graph edges.
503///
504/// Given a node, this tells you all its neighbors and the edges connecting them.
505/// Internally uses chunked storage (64 edges per chunk) with a delta buffer for
506/// recent inserts. Deletions are soft (tombstones) until compaction.
507///
508/// # Example
509///
510/// ```
511/// use grafeo_core::index::ChunkedAdjacency;
512/// use grafeo_common::types::{NodeId, EdgeId};
513///
514/// let adj = ChunkedAdjacency::new();
515///
516/// // Build a star graph: node 0 connects to nodes 1, 2, 3
517/// adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(100));
518/// adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(101));
519/// adj.add_edge(NodeId::new(0), NodeId::new(3), EdgeId::new(102));
520///
521/// // Fast neighbor lookup
522/// let neighbors = adj.neighbors(NodeId::new(0));
523/// assert_eq!(neighbors.len(), 3);
524/// ```
525pub struct ChunkedAdjacency {
526    /// Adjacency lists indexed by source node.
527    /// Lock order: 10 (nested, acquired via LpgStore::forward_adj/backward_adj)
528    lists: RwLock<FxHashMap<NodeId, AdjacencyList>>,
529    /// Chunk capacity for new chunks.
530    chunk_capacity: usize,
531    /// Total number of edges (including deleted).
532    edge_count: AtomicUsize,
533    /// Number of deleted edges.
534    deleted_count: AtomicUsize,
535}
536
537impl ChunkedAdjacency {
538    /// Creates a new chunked adjacency structure.
539    #[must_use]
540    pub fn new() -> Self {
541        Self::with_chunk_capacity(DEFAULT_CHUNK_CAPACITY)
542    }
543
544    /// Creates a new chunked adjacency with custom chunk capacity.
545    #[must_use]
546    pub fn with_chunk_capacity(capacity: usize) -> Self {
547        Self {
548            lists: RwLock::new(FxHashMap::default()),
549            chunk_capacity: capacity,
550            edge_count: AtomicUsize::new(0),
551            deleted_count: AtomicUsize::new(0),
552        }
553    }
554
555    /// Adds an edge from src to dst.
556    pub fn add_edge(&self, src: NodeId, dst: NodeId, edge_id: EdgeId) {
557        let mut lists = self.lists.write();
558        lists
559            .entry(src)
560            .or_insert_with(AdjacencyList::new)
561            .add_edge(dst, edge_id);
562        self.edge_count.fetch_add(1, Ordering::Relaxed);
563    }
564
565    /// Adds multiple edges in a single lock acquisition.
566    ///
567    /// Each tuple is `(src, dst, edge_id)`. Takes the write lock once and
568    /// inserts all edges, then compacts any lists that exceed the delta
569    /// threshold. Significantly faster than calling `add_edge()` in a loop
570    /// for bulk imports.
571    pub fn batch_add_edges(&self, edges: &[(NodeId, NodeId, EdgeId)]) {
572        if edges.is_empty() {
573            return;
574        }
575        let mut lists = self.lists.write();
576        for &(src, dst, edge_id) in edges {
577            lists
578                .entry(src)
579                .or_insert_with(AdjacencyList::new)
580                .add_edge(dst, edge_id);
581        }
582        self.edge_count.fetch_add(edges.len(), Ordering::Relaxed);
583
584        // Compact any lists that overflowed their delta buffer
585        for list in lists.values_mut() {
586            if list.delta_inserts.len() >= DELTA_COMPACTION_THRESHOLD {
587                list.compact(self.chunk_capacity);
588            }
589        }
590    }
591
592    /// Marks an edge as deleted.
593    pub fn mark_deleted(&self, src: NodeId, edge_id: EdgeId) {
594        let mut lists = self.lists.write();
595        if let Some(list) = lists.get_mut(&src) {
596            list.mark_deleted(edge_id);
597            self.deleted_count.fetch_add(1, Ordering::Relaxed);
598        }
599    }
600
601    /// Returns all neighbors of a node.
602    ///
603    /// Note: This allocates a Vec to collect neighbors while the internal lock
604    /// is held, then returns the Vec. For traversal performance, consider using
605    /// `edges_from` if you also need edge IDs, to avoid multiple lookups.
606    #[must_use]
607    pub fn neighbors(&self, src: NodeId) -> Vec<NodeId> {
608        let lists = self.lists.read();
609        lists
610            .get(&src)
611            .map(|list| list.neighbors().collect())
612            .unwrap_or_default()
613    }
614
615    /// Returns all (neighbor, edge_id) pairs for outgoing edges from a node.
616    ///
617    /// Note: This allocates a Vec to collect edges while the internal lock
618    /// is held, then returns the Vec. This is intentional to avoid holding
619    /// the lock across iteration.
620    #[must_use]
621    pub fn edges_from(&self, src: NodeId) -> Vec<(NodeId, EdgeId)> {
622        let lists = self.lists.read();
623        lists
624            .get(&src)
625            .map(|list| list.iter().collect())
626            .unwrap_or_default()
627    }
628
629    /// Returns the out-degree of a node (number of outgoing edges).
630    ///
631    /// For forward adjacency, this counts edges where `src` is the source.
632    pub fn out_degree(&self, src: NodeId) -> usize {
633        let lists = self.lists.read();
634        lists.get(&src).map_or(0, |list| list.degree())
635    }
636
637    /// Returns the in-degree of a node (number of incoming edges).
638    ///
639    /// This is semantically equivalent to `out_degree` but named differently
640    /// for use with backward adjacency where edges are stored in reverse.
641    /// When called on `backward_adj`, this returns the count of edges
642    /// where `node` is the destination.
643    pub fn in_degree(&self, node: NodeId) -> usize {
644        let lists = self.lists.read();
645        lists.get(&node).map_or(0, |list| list.degree())
646    }
647
648    /// Compacts all adjacency lists.
649    pub fn compact(&self) {
650        let mut lists = self.lists.write();
651        for list in lists.values_mut() {
652            list.compact(self.chunk_capacity);
653        }
654    }
655
656    /// Compacts delta buffers that exceed the threshold.
657    pub fn compact_if_needed(&self) {
658        let mut lists = self.lists.write();
659        for list in lists.values_mut() {
660            if list.delta_inserts.len() >= DELTA_COMPACTION_THRESHOLD {
661                list.compact(self.chunk_capacity);
662            }
663        }
664    }
665
666    /// Returns the total number of edges (including deleted).
667    pub fn total_edge_count(&self) -> usize {
668        self.edge_count.load(Ordering::Relaxed)
669    }
670
671    /// Returns the number of active (non-deleted) edges.
672    pub fn active_edge_count(&self) -> usize {
673        self.edge_count.load(Ordering::Relaxed) - self.deleted_count.load(Ordering::Relaxed)
674    }
675
676    /// Returns the number of nodes with adjacency lists.
677    pub fn node_count(&self) -> usize {
678        self.lists.read().len()
679    }
680
681    /// Checks if an edge from `src` to `dst` exists (not deleted).
682    ///
683    /// Uses zone-map skip index over cold chunks for O(log n) lookup
684    /// when most data is in cold storage. Hot chunks and the delta buffer
685    /// are scanned linearly.
686    #[must_use]
687    pub fn contains_edge(&self, src: NodeId, dst: NodeId) -> bool {
688        let lists = self.lists.read();
689        lists.get(&src).is_some_and(|list| list.contains(dst))
690    }
691
692    /// Returns edges from `src` whose destination is in `[min_dst, max_dst]`.
693    ///
694    /// Only decompresses cold chunks whose zone maps overlap the requested range.
695    #[must_use]
696    pub fn edges_in_range(
697        &self,
698        src: NodeId,
699        min_dst: NodeId,
700        max_dst: NodeId,
701    ) -> Vec<(NodeId, EdgeId)> {
702        let lists = self.lists.read();
703        lists
704            .get(&src)
705            .map(|list| list.destinations_in_range(min_dst, max_dst))
706            .unwrap_or_default()
707    }
708
709    /// Clears all adjacency lists.
710    pub fn clear(&self) {
711        let mut lists = self.lists.write();
712        lists.clear();
713        self.edge_count.store(0, Ordering::Relaxed);
714        self.deleted_count.store(0, Ordering::Relaxed);
715    }
716
717    /// Returns memory statistics for this adjacency structure.
718    #[must_use]
719    pub fn memory_stats(&self) -> AdjacencyMemoryStats {
720        let lists = self.lists.read();
721
722        let mut hot_entries = 0usize;
723        let mut cold_entries = 0usize;
724        let mut hot_bytes = 0usize;
725        let mut cold_bytes = 0usize;
726
727        for list in lists.values() {
728            hot_entries += list.hot_count();
729            cold_entries += list.cold_count();
730
731            // Hot: uncompressed (16 bytes per entry)
732            hot_bytes += list.hot_count() * 16;
733
734            // Cold: compressed size from memory_size()
735            for cold_chunk in &list.cold_chunks {
736                cold_bytes += cold_chunk.memory_size();
737            }
738        }
739
740        AdjacencyMemoryStats {
741            hot_entries,
742            cold_entries,
743            hot_bytes,
744            cold_bytes,
745            node_count: lists.len(),
746        }
747    }
748
749    /// Forces all hot chunks to be compressed for all adjacency lists.
750    ///
751    /// This is useful when memory pressure is high or during shutdown.
752    pub fn freeze_all(&self) {
753        let mut lists = self.lists.write();
754        for list in lists.values_mut() {
755            list.freeze_all();
756        }
757    }
758}
759
760/// Memory statistics for the adjacency structure.
761#[derive(Debug, Clone)]
762pub struct AdjacencyMemoryStats {
763    /// Number of entries in hot (uncompressed) storage.
764    pub hot_entries: usize,
765    /// Number of entries in cold (compressed) storage.
766    pub cold_entries: usize,
767    /// Bytes used by hot storage.
768    pub hot_bytes: usize,
769    /// Bytes used by cold storage.
770    pub cold_bytes: usize,
771    /// Number of nodes with adjacency lists.
772    pub node_count: usize,
773}
774
775impl AdjacencyMemoryStats {
776    /// Returns the total number of entries.
777    #[must_use]
778    pub fn total_entries(&self) -> usize {
779        self.hot_entries + self.cold_entries
780    }
781
782    /// Returns the total memory used in bytes.
783    #[must_use]
784    pub fn total_bytes(&self) -> usize {
785        self.hot_bytes + self.cold_bytes
786    }
787
788    /// Returns the compression ratio for cold storage.
789    ///
790    /// Values > 1.0 indicate actual compression.
791    #[must_use]
792    pub fn cold_compression_ratio(&self) -> f64 {
793        if self.cold_entries == 0 || self.cold_bytes == 0 {
794            return 1.0;
795        }
796        let uncompressed = self.cold_entries * 16;
797        uncompressed as f64 / self.cold_bytes as f64
798    }
799
800    /// Returns the overall compression ratio.
801    #[must_use]
802    pub fn overall_compression_ratio(&self) -> f64 {
803        let total_entries = self.total_entries();
804        if total_entries == 0 || self.total_bytes() == 0 {
805            return 1.0;
806        }
807        let uncompressed = total_entries * 16;
808        uncompressed as f64 / self.total_bytes() as f64
809    }
810}
811
812impl Default for ChunkedAdjacency {
813    fn default() -> Self {
814        Self::new()
815    }
816}
817
818#[cfg(test)]
819mod tests {
820    use super::*;
821
822    #[test]
823    fn test_basic_adjacency() {
824        let adj = ChunkedAdjacency::new();
825
826        adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(0));
827        adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(1));
828        adj.add_edge(NodeId::new(0), NodeId::new(3), EdgeId::new(2));
829
830        let neighbors = adj.neighbors(NodeId::new(0));
831        assert_eq!(neighbors.len(), 3);
832        assert!(neighbors.contains(&NodeId::new(1)));
833        assert!(neighbors.contains(&NodeId::new(2)));
834        assert!(neighbors.contains(&NodeId::new(3)));
835    }
836
837    #[test]
838    fn test_out_degree() {
839        let adj = ChunkedAdjacency::new();
840
841        adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(0));
842        adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(1));
843
844        assert_eq!(adj.out_degree(NodeId::new(0)), 2);
845        assert_eq!(adj.out_degree(NodeId::new(1)), 0);
846    }
847
848    #[test]
849    fn test_mark_deleted() {
850        let adj = ChunkedAdjacency::new();
851
852        adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(0));
853        adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(1));
854
855        adj.mark_deleted(NodeId::new(0), EdgeId::new(0));
856
857        let neighbors = adj.neighbors(NodeId::new(0));
858        assert_eq!(neighbors.len(), 1);
859        assert!(neighbors.contains(&NodeId::new(2)));
860    }
861
862    #[test]
863    fn test_edges_from() {
864        let adj = ChunkedAdjacency::new();
865
866        adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(10));
867        adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(20));
868
869        let edges = adj.edges_from(NodeId::new(0));
870        assert_eq!(edges.len(), 2);
871        assert!(edges.contains(&(NodeId::new(1), EdgeId::new(10))));
872        assert!(edges.contains(&(NodeId::new(2), EdgeId::new(20))));
873    }
874
875    #[test]
876    fn test_compaction() {
877        let adj = ChunkedAdjacency::with_chunk_capacity(4);
878
879        // Add more edges than chunk capacity
880        for i in 0..10 {
881            adj.add_edge(NodeId::new(0), NodeId::new(i + 1), EdgeId::new(i));
882        }
883
884        adj.compact();
885
886        // All edges should still be accessible
887        let neighbors = adj.neighbors(NodeId::new(0));
888        assert_eq!(neighbors.len(), 10);
889    }
890
891    #[test]
892    fn test_edge_counts() {
893        let adj = ChunkedAdjacency::new();
894
895        adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(0));
896        adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(1));
897        adj.add_edge(NodeId::new(1), NodeId::new(2), EdgeId::new(2));
898
899        assert_eq!(adj.total_edge_count(), 3);
900        assert_eq!(adj.active_edge_count(), 3);
901
902        adj.mark_deleted(NodeId::new(0), EdgeId::new(0));
903
904        assert_eq!(adj.total_edge_count(), 3);
905        assert_eq!(adj.active_edge_count(), 2);
906    }
907
908    #[test]
909    fn test_clear() {
910        let adj = ChunkedAdjacency::new();
911
912        adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(0));
913        adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(1));
914
915        adj.clear();
916
917        assert_eq!(adj.total_edge_count(), 0);
918        assert_eq!(adj.node_count(), 0);
919    }
920
921    #[test]
922    fn test_chunk_compression() {
923        // Create a chunk with some edges
924        let mut chunk = AdjacencyChunk::new(64);
925
926        // Add edges with various destination IDs
927        for i in 0..20 {
928            chunk.push(NodeId::new(100 + i * 5), EdgeId::new(1000 + i));
929        }
930
931        // Compress the chunk
932        let compressed = chunk.compress();
933
934        // Verify all data is preserved
935        assert_eq!(compressed.len(), 20);
936
937        // Decompress and verify
938        let entries: Vec<_> = compressed.iter().collect();
939        assert_eq!(entries.len(), 20);
940
941        // After compression, entries are sorted by destination
942        // Verify destinations are sorted
943        for window in entries.windows(2) {
944            assert!(window[0].0.as_u64() <= window[1].0.as_u64());
945        }
946
947        // Verify all original destinations are present
948        let original_dsts: std::collections::HashSet<_> =
949            (0..20).map(|i| NodeId::new(100 + i * 5)).collect();
950        let compressed_dsts: std::collections::HashSet<_> =
951            entries.iter().map(|(d, _)| *d).collect();
952        assert_eq!(original_dsts, compressed_dsts);
953
954        // Check compression ratio (should be > 1.0 for sorted data)
955        let ratio = compressed.compression_ratio();
956        assert!(
957            ratio > 1.0,
958            "Expected compression ratio > 1.0, got {}",
959            ratio
960        );
961    }
962
963    #[test]
964    fn test_empty_chunk_compression() {
965        let chunk = AdjacencyChunk::new(64);
966        let compressed = chunk.compress();
967
968        assert_eq!(compressed.len(), 0);
969        assert!(compressed.is_empty());
970        assert_eq!(compressed.iter().count(), 0);
971    }
972
973    #[test]
974    fn test_hot_to_cold_migration() {
975        // Use small chunk capacity to trigger cold compression faster
976        let adj = ChunkedAdjacency::with_chunk_capacity(8);
977
978        // Add many edges to force multiple chunks and cold compression
979        // With chunk_capacity=8 and COLD_COMPRESSION_THRESHOLD=4,
980        // we need more than 4 * 8 = 32 edges to trigger cold compression
981        for i in 0..100 {
982            adj.add_edge(NodeId::new(0), NodeId::new(i + 1), EdgeId::new(i));
983        }
984
985        // Force compaction to trigger hot→cold migration
986        adj.compact();
987
988        // All edges should still be accessible
989        let neighbors = adj.neighbors(NodeId::new(0));
990        assert_eq!(neighbors.len(), 100);
991
992        // Check memory stats
993        let stats = adj.memory_stats();
994        assert_eq!(stats.total_entries(), 100);
995
996        // With 100 edges and threshold of 4 hot chunks (32 edges),
997        // we should have some cold entries
998        assert!(
999            stats.cold_entries > 0,
1000            "Expected some cold entries, got {}",
1001            stats.cold_entries
1002        );
1003    }
1004
1005    #[test]
1006    fn test_memory_stats() {
1007        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1008
1009        // Add edges
1010        for i in 0..20 {
1011            adj.add_edge(NodeId::new(0), NodeId::new(i + 1), EdgeId::new(i));
1012        }
1013
1014        adj.compact();
1015
1016        let stats = adj.memory_stats();
1017        assert_eq!(stats.total_entries(), 20);
1018        assert_eq!(stats.node_count, 1);
1019        assert!(stats.total_bytes() > 0);
1020    }
1021
1022    #[test]
1023    fn test_freeze_all() {
1024        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1025
1026        // Add some edges
1027        for i in 0..30 {
1028            adj.add_edge(NodeId::new(0), NodeId::new(i + 1), EdgeId::new(i));
1029        }
1030
1031        adj.compact();
1032
1033        // Get initial stats
1034        let before = adj.memory_stats();
1035
1036        // Freeze all hot chunks
1037        adj.freeze_all();
1038
1039        // Get stats after freeze
1040        let after = adj.memory_stats();
1041
1042        // All data should now be in cold storage
1043        assert_eq!(after.hot_entries, 0);
1044        assert_eq!(after.cold_entries, before.total_entries());
1045
1046        // All edges should still be accessible
1047        let neighbors = adj.neighbors(NodeId::new(0));
1048        assert_eq!(neighbors.len(), 30);
1049    }
1050
1051    #[test]
1052    fn test_cold_compression_ratio() {
1053        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1054
1055        // Add many edges with sequential IDs (compresses well)
1056        for i in 0..200 {
1057            adj.add_edge(NodeId::new(0), NodeId::new(100 + i), EdgeId::new(i));
1058        }
1059
1060        adj.compact();
1061        adj.freeze_all();
1062
1063        let stats = adj.memory_stats();
1064
1065        // Sequential data should compress well
1066        let ratio = stats.cold_compression_ratio();
1067        assert!(
1068            ratio > 1.5,
1069            "Expected cold compression ratio > 1.5, got {}",
1070            ratio
1071        );
1072    }
1073
1074    #[test]
1075    fn test_deleted_edges_with_cold_storage() {
1076        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1077
1078        // Add edges
1079        for i in 0..50 {
1080            adj.add_edge(NodeId::new(0), NodeId::new(i + 1), EdgeId::new(i));
1081        }
1082
1083        adj.compact();
1084
1085        // Delete some edges (some will be in cold storage after compaction)
1086        for i in (0..50).step_by(2) {
1087            adj.mark_deleted(NodeId::new(0), EdgeId::new(i));
1088        }
1089
1090        // Should have half the edges
1091        let neighbors = adj.neighbors(NodeId::new(0));
1092        assert_eq!(neighbors.len(), 25);
1093
1094        // Verify only odd-numbered destinations remain
1095        for neighbor in neighbors {
1096            assert!(neighbor.as_u64() % 2 == 0); // Original IDs were i+1, so even means odd i
1097        }
1098    }
1099
1100    #[test]
1101    fn test_adjacency_list_memory_size() {
1102        let mut list = AdjacencyList::new();
1103
1104        // Add edges
1105        for i in 0..50 {
1106            list.add_edge(NodeId::new(i + 1), EdgeId::new(i));
1107        }
1108
1109        // Compact with small chunk capacity to get multiple chunks
1110        list.compact(8);
1111
1112        let size = list.memory_size();
1113        assert!(size > 0);
1114
1115        // Size should be roughly proportional to entry count
1116        // Each entry is 16 bytes uncompressed
1117        assert!(size <= 50 * 16 + 200); // Allow some overhead
1118    }
1119
1120    #[test]
1121    fn test_cold_iteration_order() {
1122        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1123
1124        // Add edges in order
1125        for i in 0..50 {
1126            adj.add_edge(NodeId::new(0), NodeId::new(i + 1), EdgeId::new(i));
1127        }
1128
1129        adj.compact();
1130
1131        // Collect all edges
1132        let edges = adj.edges_from(NodeId::new(0));
1133
1134        // All edges should be present
1135        assert_eq!(edges.len(), 50);
1136
1137        // Verify edge IDs are present (may be reordered due to compression sorting)
1138        let edge_ids: std::collections::HashSet<_> = edges.iter().map(|(_, e)| *e).collect();
1139        for i in 0..50 {
1140            assert!(edge_ids.contains(&EdgeId::new(i)));
1141        }
1142    }
1143
1144    #[test]
1145    fn test_in_degree() {
1146        let adj = ChunkedAdjacency::new();
1147
1148        // Simulate backward adjacency: edges stored as (dst, src)
1149        // Edge 1->2: backward stores (2, 1)
1150        // Edge 3->2: backward stores (2, 3)
1151        adj.add_edge(NodeId::new(2), NodeId::new(1), EdgeId::new(0)); // 1->2 in backward
1152        adj.add_edge(NodeId::new(2), NodeId::new(3), EdgeId::new(1)); // 3->2 in backward
1153
1154        // In-degree of node 2 is 2 (two edges point to it)
1155        assert_eq!(adj.in_degree(NodeId::new(2)), 2);
1156
1157        // Node 1 has no incoming edges
1158        assert_eq!(adj.in_degree(NodeId::new(1)), 0);
1159    }
1160
1161    #[test]
1162    fn test_bidirectional_edges() {
1163        let forward = ChunkedAdjacency::new();
1164        let backward = ChunkedAdjacency::new();
1165
1166        // Add edge: 1 -> 2
1167        let edge_id = EdgeId::new(100);
1168        forward.add_edge(NodeId::new(1), NodeId::new(2), edge_id);
1169        backward.add_edge(NodeId::new(2), NodeId::new(1), edge_id); // Reverse for backward!
1170
1171        // Forward: edges from node 1 → returns (dst=2, edge_id)
1172        let forward_edges = forward.edges_from(NodeId::new(1));
1173        assert_eq!(forward_edges.len(), 1);
1174        assert_eq!(forward_edges[0], (NodeId::new(2), edge_id));
1175
1176        // Forward: node 2 has no outgoing edges
1177        assert_eq!(forward.edges_from(NodeId::new(2)).len(), 0);
1178
1179        // Backward: edges to node 2 → stored as edges_from(2) → returns (src=1, edge_id)
1180        let backward_edges = backward.edges_from(NodeId::new(2));
1181        assert_eq!(backward_edges.len(), 1);
1182        assert_eq!(backward_edges[0], (NodeId::new(1), edge_id));
1183
1184        // Backward: node 1 has no incoming edges
1185        assert_eq!(backward.edges_from(NodeId::new(1)).len(), 0);
1186    }
1187
1188    #[test]
1189    fn test_bidirectional_chain() {
1190        // Test chain: A -> B -> C
1191        let forward = ChunkedAdjacency::new();
1192        let backward = ChunkedAdjacency::new();
1193
1194        let a = NodeId::new(1);
1195        let b = NodeId::new(2);
1196        let c = NodeId::new(3);
1197
1198        // Edge A -> B
1199        let edge_ab = EdgeId::new(10);
1200        forward.add_edge(a, b, edge_ab);
1201        backward.add_edge(b, a, edge_ab);
1202
1203        // Edge B -> C
1204        let edge_bc = EdgeId::new(20);
1205        forward.add_edge(b, c, edge_bc);
1206        backward.add_edge(c, b, edge_bc);
1207
1208        // Forward traversal from A: should reach B
1209        let from_a = forward.edges_from(a);
1210        assert_eq!(from_a.len(), 1);
1211        assert_eq!(from_a[0].0, b);
1212
1213        // Forward traversal from B: should reach C
1214        let from_b = forward.edges_from(b);
1215        assert_eq!(from_b.len(), 1);
1216        assert_eq!(from_b[0].0, c);
1217
1218        // Backward traversal to C: should find B
1219        let to_c = backward.edges_from(c);
1220        assert_eq!(to_c.len(), 1);
1221        assert_eq!(to_c[0].0, b);
1222
1223        // Backward traversal to B: should find A
1224        let to_b = backward.edges_from(b);
1225        assert_eq!(to_b.len(), 1);
1226        assert_eq!(to_b[0].0, a);
1227
1228        // Node A has no incoming edges
1229        assert_eq!(backward.edges_from(a).len(), 0);
1230
1231        // Node C has no outgoing edges
1232        assert_eq!(forward.edges_from(c).len(), 0);
1233    }
1234
1235    // === Skip Index Tests ===
1236
1237    #[test]
1238    fn test_contains_edge_basic() {
1239        let adj = ChunkedAdjacency::new();
1240
1241        adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(0));
1242        adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(1));
1243        adj.add_edge(NodeId::new(0), NodeId::new(3), EdgeId::new(2));
1244
1245        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(1)));
1246        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(2)));
1247        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(3)));
1248        assert!(!adj.contains_edge(NodeId::new(0), NodeId::new(4)));
1249        assert!(!adj.contains_edge(NodeId::new(1), NodeId::new(0)));
1250    }
1251
1252    #[test]
1253    fn test_contains_edge_after_delete() {
1254        let adj = ChunkedAdjacency::new();
1255
1256        adj.add_edge(NodeId::new(0), NodeId::new(1), EdgeId::new(10));
1257        adj.add_edge(NodeId::new(0), NodeId::new(2), EdgeId::new(20));
1258
1259        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(1)));
1260
1261        adj.mark_deleted(NodeId::new(0), EdgeId::new(10));
1262
1263        assert!(!adj.contains_edge(NodeId::new(0), NodeId::new(1)));
1264        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(2)));
1265    }
1266
1267    #[test]
1268    fn test_contains_edge_in_cold_storage() {
1269        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1270
1271        // Add enough edges to trigger hot→cold compression
1272        for i in 0..100 {
1273            adj.add_edge(NodeId::new(0), NodeId::new(100 + i), EdgeId::new(i));
1274        }
1275
1276        adj.compact();
1277        adj.freeze_all();
1278
1279        // All edges should be findable via skip index
1280        for i in 0..100 {
1281            assert!(
1282                adj.contains_edge(NodeId::new(0), NodeId::new(100 + i)),
1283                "Should find destination {} in cold storage",
1284                100 + i
1285            );
1286        }
1287
1288        // Non-existent destinations should not be found
1289        assert!(!adj.contains_edge(NodeId::new(0), NodeId::new(0)));
1290        assert!(!adj.contains_edge(NodeId::new(0), NodeId::new(99)));
1291        assert!(!adj.contains_edge(NodeId::new(0), NodeId::new(200)));
1292    }
1293
1294    #[test]
1295    fn test_contains_edge_in_delta_only() {
1296        let adj = ChunkedAdjacency::new();
1297
1298        // Add just a few edges (stays in delta buffer)
1299        adj.add_edge(NodeId::new(0), NodeId::new(5), EdgeId::new(0));
1300        adj.add_edge(NodeId::new(0), NodeId::new(10), EdgeId::new(1));
1301
1302        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(5)));
1303        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(10)));
1304        assert!(!adj.contains_edge(NodeId::new(0), NodeId::new(7)));
1305    }
1306
1307    #[test]
1308    fn test_edges_in_range() {
1309        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1310
1311        // Add edges with destinations 100..200
1312        for i in 0..100 {
1313            adj.add_edge(NodeId::new(0), NodeId::new(100 + i), EdgeId::new(i));
1314        }
1315
1316        adj.compact();
1317
1318        // Range [130, 140] should return 11 edges (130..=140)
1319        let results = adj.edges_in_range(NodeId::new(0), NodeId::new(130), NodeId::new(140));
1320        assert_eq!(
1321            results.len(),
1322            11,
1323            "Expected 11 edges in range [130, 140], got {}",
1324            results.len()
1325        );
1326
1327        // Verify all results are in range
1328        for (dst, _) in &results {
1329            assert!(dst.as_u64() >= 130 && dst.as_u64() <= 140);
1330        }
1331
1332        // Out-of-range query should return empty
1333        let empty = adj.edges_in_range(NodeId::new(0), NodeId::new(200), NodeId::new(300));
1334        assert!(empty.is_empty());
1335    }
1336
1337    #[test]
1338    fn test_skip_index_prunes_chunks() {
1339        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1340
1341        // Add edges in distinct ranges to create separate cold chunks
1342        // Range A: destinations 100-107, Range B: 200-207, Range C: 300-307
1343        for i in 0..8 {
1344            adj.add_edge(NodeId::new(0), NodeId::new(100 + i), EdgeId::new(i));
1345        }
1346        adj.compact();
1347
1348        for i in 0..8 {
1349            adj.add_edge(NodeId::new(0), NodeId::new(200 + i), EdgeId::new(100 + i));
1350        }
1351        adj.compact();
1352
1353        for i in 0..8 {
1354            adj.add_edge(NodeId::new(0), NodeId::new(300 + i), EdgeId::new(200 + i));
1355        }
1356        adj.compact();
1357        adj.freeze_all();
1358
1359        // contains_edge for each range
1360        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(103)));
1361        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(205)));
1362        assert!(adj.contains_edge(NodeId::new(0), NodeId::new(307)));
1363
1364        // Values between ranges should not exist
1365        assert!(!adj.contains_edge(NodeId::new(0), NodeId::new(150)));
1366        assert!(!adj.contains_edge(NodeId::new(0), NodeId::new(250)));
1367
1368        // Range query spanning only one chunk range
1369        let range_b = adj.edges_in_range(NodeId::new(0), NodeId::new(200), NodeId::new(207));
1370        assert_eq!(range_b.len(), 8);
1371    }
1372
1373    #[test]
1374    fn test_contains_after_freeze_all() {
1375        let adj = ChunkedAdjacency::with_chunk_capacity(8);
1376
1377        for i in 0..50 {
1378            adj.add_edge(NodeId::new(0), NodeId::new(i + 1), EdgeId::new(i));
1379        }
1380
1381        adj.compact();
1382        adj.freeze_all();
1383
1384        // Verify all edges are in cold storage
1385        let stats = adj.memory_stats();
1386        assert_eq!(stats.hot_entries, 0);
1387        assert_eq!(stats.cold_entries, 50);
1388
1389        // All edges should still be findable
1390        for i in 0..50 {
1391            assert!(
1392                adj.contains_edge(NodeId::new(0), NodeId::new(i + 1)),
1393                "Should find destination {} after freeze_all",
1394                i + 1
1395            );
1396        }
1397    }
1398}