kitedb 0.2.3

High-performance embedded graph database
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
//! Traversal Cache
//!
//! Caches neighbor iteration results to avoid repeated graph traversals.
//! Uses targeted invalidation via reverse index for O(1) node/edge invalidation.
//!
//! Ported from src/cache/traversal-cache.ts

use super::lru::LruCache;
use crate::types::{ETypeId, Edge, NodeId, TraversalCacheConfig};
use std::collections::{HashMap, HashSet};

// ============================================================================
// Cache Key Types
// ============================================================================

/// Traversal direction
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TraversalDirection {
  Out,
  In,
}

/// Traversal cache key - packed as u64 for fast comparison and hashing
/// Pack: nodeId (53 bits) | etype (10 bits) | direction (1 bit)
/// With etype=0x3FF meaning "all edge types"
type TraversalKey = u64;

/// Sentinel value for "all edge types"
const ALL_ETYPES: u64 = 0x3FF; // 1023

// ============================================================================
// Cached Neighbors Result
// ============================================================================

/// Cached neighbors result
#[derive(Debug, Clone)]
pub struct CachedNeighbors {
  /// The cached neighbor edges
  pub neighbors: Vec<Edge>,
  /// True if the neighbors were truncated due to max_neighbors_per_entry
  pub truncated: bool,
}

// ============================================================================
// Traversal Cache Statistics
// ============================================================================

/// Traversal cache statistics
#[derive(Debug, Clone, Default)]
pub struct TraversalCacheStats {
  pub hits: u64,
  pub misses: u64,
  pub cache_size: usize,
  pub max_cache_size: usize,
}

impl TraversalCacheStats {
  /// Calculate hit rate
  pub fn hit_rate(&self) -> f64 {
    let total = self.hits + self.misses;
    if total > 0 {
      self.hits as f64 / total as f64
    } else {
      0.0
    }
  }
}

// ============================================================================
// Traversal Cache
// ============================================================================

/// Traversal cache for neighbor lookups
///
/// Uses targeted invalidation via reverse index mapping:
/// - `node_key_index`: Maps NodeId -> Set<TraversalKey> for O(1) node invalidation
///
/// When a node changes, we invalidate:
/// - All outgoing traversals from that node
/// - All incoming traversals to that node
/// - All traversals that include this node in their results (as a destination)
///
/// When an edge changes (src -> dst), we invalidate:
/// - Outgoing traversals from src (affected by edge addition/removal)
/// - Incoming traversals to dst (affected by edge addition/removal)
///
/// # Example
/// ```
/// use kitedb::cache::traversal::{TraversalCache, TraversalDirection};
/// use kitedb::types::{TraversalCacheConfig, Edge};
///
/// let config = TraversalCacheConfig {
///     max_entries: 100,
///     max_neighbors_per_entry: 50,
/// };
/// let mut cache = TraversalCache::new(config);
///
/// // Cache neighbors for a traversal
/// let neighbors = vec![
///     Edge { src: 1, etype: 1, dst: 2 },
///     Edge { src: 1, etype: 1, dst: 3 },
/// ];
/// cache.set(1, Some(1), TraversalDirection::Out, neighbors.clone());
///
/// // Retrieve from cache
/// let result = cache.get(1, Some(1), TraversalDirection::Out);
/// assert!(result.is_some());
/// ```
pub struct TraversalCache {
  /// The LRU cache for traversal results
  cache: LruCache<TraversalKey, CachedNeighbors>,

  /// Maximum neighbors to store per entry
  max_neighbors_per_entry: usize,

  /// Reverse index: NodeId -> Set of traversal keys that reference this node
  /// (as source OR destination)
  node_key_index: HashMap<NodeId, HashSet<TraversalKey>>,

  /// Cache statistics
  hits: u64,
  misses: u64,
}

impl TraversalCache {
  /// Create a new traversal cache with the given configuration
  pub fn new(config: TraversalCacheConfig) -> Self {
    Self {
      cache: LruCache::new(config.max_entries),
      max_neighbors_per_entry: config.max_neighbors_per_entry,
      node_key_index: HashMap::new(),
      hits: 0,
      misses: 0,
    }
  }

  /// Get cached neighbors for a node
  ///
  /// # Arguments
  /// - `node_id` - Source node ID
  /// - `etype` - Edge type ID, or None for all types
  /// - `direction` - Traversal direction (Out or In)
  ///
  /// # Returns
  /// Cached neighbors or None if not cached
  pub fn get(
    &mut self,
    node_id: NodeId,
    etype: Option<ETypeId>,
    direction: TraversalDirection,
  ) -> Option<&CachedNeighbors> {
    let key = Self::make_key(node_id, etype, direction);
    let result = self.cache.get(&key);

    if result.is_some() {
      self.hits += 1;
    } else {
      self.misses += 1;
    }

    result
  }

  /// Peek at cached neighbors without affecting LRU order
  pub fn peek(
    &self,
    node_id: NodeId,
    etype: Option<ETypeId>,
    direction: TraversalDirection,
  ) -> Option<&CachedNeighbors> {
    let key = Self::make_key(node_id, etype, direction);
    self.cache.peek(&key)
  }

  /// Set cached neighbors for a node
  ///
  /// # Arguments
  /// - `node_id` - Source node ID
  /// - `etype` - Edge type ID, or None for all types
  /// - `direction` - Traversal direction (Out or In)
  /// - `neighbors` - Array of neighbor edges
  pub fn set(
    &mut self,
    node_id: NodeId,
    etype: Option<ETypeId>,
    direction: TraversalDirection,
    neighbors: Vec<Edge>,
  ) {
    let key = Self::make_key(node_id, etype, direction);

    // Truncate if exceeds max neighbors per entry
    let (cached_neighbors, truncated) = if neighbors.len() > self.max_neighbors_per_entry {
      (
        neighbors
          .into_iter()
          .take(self.max_neighbors_per_entry)
          .collect(),
        true,
      )
    } else {
      (neighbors, false)
    };

    // Track source node for invalidation
    self.add_to_node_index(node_id, key);

    // Track destination nodes for invalidation
    // This ensures that when a destination node changes, this cache entry is invalidated
    for edge in &cached_neighbors {
      let dest_id = match direction {
        TraversalDirection::Out => edge.dst,
        TraversalDirection::In => edge.src,
      };
      self.add_to_node_index(dest_id, key);
    }

    self.cache.set(
      key,
      CachedNeighbors {
        neighbors: cached_neighbors,
        truncated,
      },
    );
  }

  /// Invalidate all cached traversals for a node
  ///
  /// Complexity: O(k) where k = number of traversals referencing this node
  pub fn invalidate_node(&mut self, node_id: NodeId) {
    if let Some(keys) = self.node_key_index.remove(&node_id) {
      for key in keys {
        self.cache.delete(&key);
      }
    }
  }

  /// Invalidate traversals involving a specific edge
  ///
  /// When an edge (src, etype, dst) is added/removed:
  /// - Outgoing traversals from src are affected
  /// - Incoming traversals to dst are affected
  pub fn invalidate_edge(&mut self, src: NodeId, etype: ETypeId, dst: NodeId) {
    // Invalidate outgoing traversals from src
    self.invalidate_node_traversals(src, TraversalDirection::Out, etype);

    // Invalidate incoming traversals to dst
    self.invalidate_node_traversals(dst, TraversalDirection::In, etype);
  }

  /// Clear all cached traversals
  pub fn clear(&mut self) {
    self.cache.clear();
    self.node_key_index.clear();
    self.hits = 0;
    self.misses = 0;
  }

  /// Get cache statistics
  pub fn stats(&self) -> TraversalCacheStats {
    TraversalCacheStats {
      hits: self.hits,
      misses: self.misses,
      cache_size: self.cache.len(),
      max_cache_size: self.cache.max_size(),
    }
  }

  /// Get current cache size
  pub fn len(&self) -> usize {
    self.cache.len()
  }

  /// Check if cache is empty
  pub fn is_empty(&self) -> bool {
    self.cache.is_empty()
  }

  /// Reset statistics counters
  pub fn reset_stats(&mut self) {
    self.hits = 0;
    self.misses = 0;
  }

  // ========================================================================
  // Internal Methods
  // ========================================================================

  /// Generate cache key for traversal using u64 packing for faster comparison
  ///
  /// Pack: nodeId (53 bits) | etype (10 bits) | direction (1 bit)
  /// With etype=0x3FF meaning "all types"
  fn make_key(
    node_id: NodeId,
    etype: Option<ETypeId>,
    direction: TraversalDirection,
  ) -> TraversalKey {
    let etype_val = etype.map(|e| e as u64).unwrap_or(ALL_ETYPES);
    let dir_val = match direction {
      TraversalDirection::Out => 0u64,
      TraversalDirection::In => 1u64,
    };

    // nodeId << 11 | etype << 1 | direction
    (node_id << 11) | (etype_val << 1) | dir_val
  }

  /// Add a key to the node index
  fn add_to_node_index(&mut self, node_id: NodeId, key: TraversalKey) {
    self.node_key_index.entry(node_id).or_default().insert(key);
  }

  /// Invalidate specific traversals for a node
  fn invalidate_node_traversals(
    &mut self,
    node_id: NodeId,
    direction: TraversalDirection,
    etype: ETypeId,
  ) {
    let Some(keys) = self.node_key_index.get_mut(&node_id) else {
      return;
    };

    // Find keys that match this direction and etype (or "all")
    let specific_key = Self::make_key(node_id, Some(etype), direction);
    let all_key = Self::make_key(node_id, None, direction);

    let mut keys_to_delete = Vec::new();

    if keys.contains(&specific_key) {
      keys_to_delete.push(specific_key);
    }
    if keys.contains(&all_key) {
      keys_to_delete.push(all_key);
    }

    // Delete matched keys
    for key in keys_to_delete {
      self.cache.delete(&key);
      keys.remove(&key);
    }

    // Clean up empty index entries
    if keys.is_empty() {
      self.node_key_index.remove(&node_id);
    }
  }
}

// ============================================================================
// Tests
// ============================================================================

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

  fn make_cache() -> TraversalCache {
    TraversalCache::new(TraversalCacheConfig {
      max_entries: 100,
      max_neighbors_per_entry: 10,
    })
  }

  fn make_edge(src: NodeId, etype: ETypeId, dst: NodeId) -> Edge {
    Edge { src, etype, dst }
  }

  #[test]
  fn test_new_cache() {
    let cache = make_cache();
    assert!(cache.is_empty());
    assert_eq!(cache.stats().hits, 0);
    assert_eq!(cache.stats().misses, 0);
  }

  #[test]
  fn test_cache_miss() {
    let mut cache = make_cache();
    assert!(cache.get(1, Some(1), TraversalDirection::Out).is_none());
    assert_eq!(cache.stats().misses, 1);
  }

  #[test]
  fn test_cache_hit() {
    let mut cache = make_cache();

    let neighbors = vec![make_edge(1, 1, 2), make_edge(1, 1, 3)];
    cache.set(1, Some(1), TraversalDirection::Out, neighbors.clone());

    let result = cache.get(1, Some(1), TraversalDirection::Out);
    assert!(result.is_some());
    let cached = result.unwrap();
    assert_eq!(cached.neighbors.len(), 2);
    assert!(!cached.truncated);
    assert_eq!(cache.stats().hits, 1);
  }

  #[test]
  fn test_cache_all_etypes() {
    let mut cache = make_cache();

    let neighbors = vec![make_edge(1, 1, 2), make_edge(1, 2, 3)];
    cache.set(1, None, TraversalDirection::Out, neighbors);

    // Should hit with None etype
    assert!(cache.get(1, None, TraversalDirection::Out).is_some());

    // Should miss with specific etype
    assert!(cache.get(1, Some(1), TraversalDirection::Out).is_none());
  }

  #[test]
  fn test_different_directions() {
    let mut cache = make_cache();

    let out_neighbors = vec![make_edge(1, 1, 2)];
    let in_neighbors = vec![make_edge(3, 1, 1)];

    cache.set(1, Some(1), TraversalDirection::Out, out_neighbors);
    cache.set(1, Some(1), TraversalDirection::In, in_neighbors);

    // Check out result
    let out_result = cache.get(1, Some(1), TraversalDirection::Out);
    assert!(out_result.is_some());
    assert_eq!(out_result.unwrap().neighbors[0].dst, 2);

    // Check in result (separate borrow)
    let in_result = cache.get(1, Some(1), TraversalDirection::In);
    assert!(in_result.is_some());
    assert_eq!(in_result.unwrap().neighbors[0].src, 3);
  }

  #[test]
  fn test_truncation() {
    let mut cache = TraversalCache::new(TraversalCacheConfig {
      max_entries: 100,
      max_neighbors_per_entry: 3,
    });

    let neighbors = vec![
      make_edge(1, 1, 2),
      make_edge(1, 1, 3),
      make_edge(1, 1, 4),
      make_edge(1, 1, 5),
      make_edge(1, 1, 6),
    ];
    cache.set(1, Some(1), TraversalDirection::Out, neighbors);

    let result = cache.get(1, Some(1), TraversalDirection::Out).unwrap();
    assert_eq!(result.neighbors.len(), 3);
    assert!(result.truncated);
  }

  #[test]
  fn test_invalidate_node() {
    let mut cache = make_cache();

    // Cache traversals for multiple nodes
    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2)],
    );
    cache.set(
      2,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(2, 1, 3)],
    );

    assert_eq!(cache.len(), 2);

    // Invalidate node 1
    cache.invalidate_node(1);

    // Node 1 traversals should be gone
    assert!(cache.get(1, Some(1), TraversalDirection::Out).is_none());

    // Node 2 traversals should remain (note: hit counter increments)
    let stats_before = cache.stats().hits;
    assert!(cache.get(2, Some(1), TraversalDirection::Out).is_some());
    assert_eq!(cache.stats().hits, stats_before + 1);
  }

  #[test]
  fn test_invalidate_node_as_destination() {
    let mut cache = make_cache();

    // Cache traversal from node 1 that includes node 2 as destination
    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2), make_edge(1, 1, 3)],
    );

    // Invalidate node 2 (which is a destination)
    cache.invalidate_node(2);

    // The entire traversal should be invalidated because it included node 2
    assert!(cache.get(1, Some(1), TraversalDirection::Out).is_none());
  }

  #[test]
  fn test_invalidate_edge() {
    let mut cache = make_cache();

    // Cache outgoing from node 1
    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2)],
    );

    // Cache incoming to node 2
    cache.set(2, Some(1), TraversalDirection::In, vec![make_edge(1, 1, 2)]);

    // Cache unrelated traversal
    cache.set(
      3,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(3, 1, 4)],
    );

    // Invalidate edge (1, 1, 2)
    cache.invalidate_edge(1, 1, 2);

    // Outgoing from 1 and incoming to 2 should be invalidated
    assert!(cache.peek(1, Some(1), TraversalDirection::Out).is_none());
    assert!(cache.peek(2, Some(1), TraversalDirection::In).is_none());

    // Unrelated traversal should remain
    assert!(cache.peek(3, Some(1), TraversalDirection::Out).is_some());
  }

  #[test]
  fn test_invalidate_edge_all_etypes() {
    let mut cache = make_cache();

    // Cache with "all etypes"
    cache.set(
      1,
      None,
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2), make_edge(1, 2, 3)],
    );

    // Also cache specific etype
    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2)],
    );

    // Invalidate edge with etype=1
    cache.invalidate_edge(1, 1, 2);

    // Both should be invalidated (specific and "all")
    assert!(cache.peek(1, Some(1), TraversalDirection::Out).is_none());
    assert!(cache.peek(1, None, TraversalDirection::Out).is_none());
  }

  #[test]
  fn test_clear() {
    let mut cache = make_cache();

    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2)],
    );
    cache.get(1, Some(1), TraversalDirection::Out);
    cache.get(999, Some(1), TraversalDirection::Out);

    cache.clear();

    assert!(cache.is_empty());
    assert_eq!(cache.stats().hits, 0);
    assert_eq!(cache.stats().misses, 0);
  }

  #[test]
  fn test_peek_does_not_update_lru() {
    let mut cache = TraversalCache::new(TraversalCacheConfig {
      max_entries: 2,
      max_neighbors_per_entry: 10,
    });

    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 10)],
    );
    cache.set(
      2,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(2, 1, 20)],
    );

    // Peek at node 1 (should NOT make it most recently used)
    cache.peek(1, Some(1), TraversalDirection::Out);

    // Add node 3 - should evict node 1 (oldest)
    cache.set(
      3,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(3, 1, 30)],
    );

    assert!(cache.peek(1, Some(1), TraversalDirection::Out).is_none());
    assert!(cache.peek(2, Some(1), TraversalDirection::Out).is_some());
    assert!(cache.peek(3, Some(1), TraversalDirection::Out).is_some());
  }

  #[test]
  fn test_get_updates_lru() {
    let mut cache = TraversalCache::new(TraversalCacheConfig {
      max_entries: 2,
      max_neighbors_per_entry: 10,
    });

    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 10)],
    );
    cache.set(
      2,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(2, 1, 20)],
    );

    // Get node 1 (SHOULD make it most recently used)
    cache.get(1, Some(1), TraversalDirection::Out);

    // Add node 3 - should evict node 2 (oldest after node 1 was accessed)
    cache.set(
      3,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(3, 1, 30)],
    );

    assert!(cache.peek(1, Some(1), TraversalDirection::Out).is_some());
    assert!(cache.peek(2, Some(1), TraversalDirection::Out).is_none());
    assert!(cache.peek(3, Some(1), TraversalDirection::Out).is_some());
  }

  #[test]
  fn test_stats() {
    let mut cache = make_cache();

    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2)],
    );

    // 2 hits
    cache.get(1, Some(1), TraversalDirection::Out);
    cache.get(1, Some(1), TraversalDirection::Out);

    // 2 misses
    cache.get(999, Some(1), TraversalDirection::Out);
    cache.get(1, Some(2), TraversalDirection::Out);

    let stats = cache.stats();
    assert_eq!(stats.hits, 2);
    assert_eq!(stats.misses, 2);
    assert_eq!(stats.hit_rate(), 0.5);
  }

  #[test]
  fn test_reset_stats() {
    let mut cache = make_cache();

    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2)],
    );
    cache.get(1, Some(1), TraversalDirection::Out);
    cache.get(999, Some(1), TraversalDirection::Out);

    cache.reset_stats();

    assert_eq!(cache.stats().hits, 0);
    assert_eq!(cache.stats().misses, 0);

    // Cache should still have data
    assert_eq!(cache.len(), 1);
  }

  #[test]
  fn test_key_uniqueness() {
    let mut cache = make_cache();

    // Different node IDs
    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 100)],
    );
    cache.set(
      2,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(2, 1, 200)],
    );

    // Different etypes
    cache.set(
      1,
      Some(2),
      TraversalDirection::Out,
      vec![make_edge(1, 2, 300)],
    );

    // Different directions
    cache.set(
      1,
      Some(1),
      TraversalDirection::In,
      vec![make_edge(100, 1, 1)],
    );

    assert_eq!(cache.len(), 4);

    // Each should be retrievable independently
    assert_eq!(
      cache
        .peek(1, Some(1), TraversalDirection::Out)
        .unwrap()
        .neighbors[0]
        .dst,
      100
    );
    assert_eq!(
      cache
        .peek(2, Some(1), TraversalDirection::Out)
        .unwrap()
        .neighbors[0]
        .dst,
      200
    );
    assert_eq!(
      cache
        .peek(1, Some(2), TraversalDirection::Out)
        .unwrap()
        .neighbors[0]
        .dst,
      300
    );
    assert_eq!(
      cache
        .peek(1, Some(1), TraversalDirection::In)
        .unwrap()
        .neighbors[0]
        .src,
      100
    );
  }

  #[test]
  fn test_empty_neighbors() {
    let mut cache = make_cache();

    // Cache empty result (node has no neighbors)
    cache.set(1, Some(1), TraversalDirection::Out, vec![]);

    let result = cache.get(1, Some(1), TraversalDirection::Out);
    assert!(result.is_some());
    assert!(result.unwrap().neighbors.is_empty());
    assert!(!result.unwrap().truncated);
  }

  #[test]
  fn test_invalidate_nonexistent_node() {
    let mut cache = make_cache();
    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2)],
    );

    // Should not panic or affect other entries
    cache.invalidate_node(999);

    assert!(cache.peek(1, Some(1), TraversalDirection::Out).is_some());
  }

  #[test]
  fn test_invalidate_nonexistent_edge() {
    let mut cache = make_cache();
    cache.set(
      1,
      Some(1),
      TraversalDirection::Out,
      vec![make_edge(1, 1, 2)],
    );

    // Should not panic or affect other entries
    cache.invalidate_edge(999, 1, 888);

    assert!(cache.peek(1, Some(1), TraversalDirection::Out).is_some());
  }
}