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
//! LRU cache for frequently accessed graph query results
//!
//! Provides LRU caching for file nodes and symbol lookups
//! to reduce database round-trips for hot data.
//!
//! # Thread Safety
//!
//! **This cache is NOT thread-safe.**
//!
//! `LruCache<K, V>` and `FileNodeCache` are designed for single-threaded use:
//! - All methods require `&mut self` (exclusive mutable access)
//! - `HashMap` and `VecDeque` have no synchronization primitives
//! - No `Send` or `Sync` impls
//!
//! # Usage Pattern
//!
//! `FileNodeCache` is accessed exclusively through `CodeGraph`, which
//! enforces single-threaded access. Do not share the cache directly
//! across threads.
//!
//! For concurrent caching, wrap in `Mutex<LruCache<...>>` or use
//! a thread-safe cache library (e.g., `moka`).
use std::collections::{HashMap, VecDeque};
use std::hash::Hash;
/// Cache statistics for monitoring effectiveness
#[derive(Debug, Clone, Default)]
pub struct CacheStats {
pub hits: usize,
pub misses: usize,
pub size: usize,
}
impl CacheStats {
/// Calculate cache hit rate as a percentage (0.0 to 1.0)
pub fn hit_rate(&self) -> f64 {
let total = self.hits + self.misses;
if total == 0 {
0.0
} else {
self.hits as f64 / total as f64
}
}
}
/// Simple LRU cache implementation
///
/// Uses HashMap for O(1) lookups and VecDeque for tracking access order.
/// When capacity is reached, the least recently used item is evicted.
pub struct LruCache<K, V> {
capacity: usize,
map: HashMap<K, V>,
order: VecDeque<K>,
hits: usize,
misses: usize,
}
impl<K: Hash + Eq + Clone, V> LruCache<K, V> {
/// Create a new LRU cache with the specified capacity
pub fn new(capacity: usize) -> Self {
Self {
capacity,
map: HashMap::new(),
order: VecDeque::with_capacity(capacity),
hits: 0,
misses: 0,
}
}
/// Get a value from the cache by key
///
/// Returns a reference to the value if present, None otherwise.
/// On cache hit, the item is moved to the front of the LRU order.
pub fn get(&mut self, key: &K) -> Option<&V> {
if self.map.contains_key(key) {
self.hits += 1;
// Move to front of order
if let Some(pos) = self.order.iter().position(|k| k == key) {
self.order.remove(pos);
self.order.push_front(key.clone());
}
self.map.get(key)
} else {
self.misses += 1;
None
}
}
/// Insert a key-value pair into the cache
///
/// If the key already exists, the value is updated and the key is moved to front.
/// If the cache is at capacity, the least recently used item is evicted.
pub fn put(&mut self, key: K, value: V) {
if self.map.contains_key(&key) {
// Update existing: remove from current position
if let Some(pos) = self.order.iter().position(|k| k == &key) {
self.order.remove(pos);
}
} else if self.order.len() >= self.capacity {
// Evict oldest (least recently used)
if let Some(old) = self.order.pop_back() {
self.map.remove(&old);
}
}
// Clone key for both order tracking and map insertion
let key_clone = key.clone();
self.order.push_front(key_clone);
self.map.insert(key, value);
}
/// Invalidate a specific cache entry
///
/// Removes the key and its value from the cache if present.
pub fn invalidate(&mut self, key: &K) {
self.map.remove(key);
if let Some(pos) = self.order.iter().position(|k| k == key) {
self.order.remove(pos);
}
}
/// Clear all entries from the cache
pub fn clear(&mut self) {
self.map.clear();
self.order.clear();
self.hits = 0;
self.misses = 0;
}
/// Get current cache size
pub fn _len(&self) -> usize {
self.map.len()
}
/// Check if cache is empty
pub fn _is_empty(&self) -> bool {
self.map.is_empty()
}
/// Get cache statistics
pub fn stats(&self) -> CacheStats {
CacheStats {
hits: self.hits,
misses: self.misses,
size: self.map.len(),
}
}
/// Get hit rate as a percentage (0.0 to 1.0)
pub fn _hit_rate(&self) -> f64 {
self.stats().hit_rate()
}
}
/// Specialized cache for file nodes
///
/// Caches FileNode lookups by file path to avoid repeated database queries.
pub type FileNodeCache = LruCache<String, crate::graph::schema::FileNode>;
/// Specialized cache for symbol vectors
///
/// Caches symbol vectors by file path for faster symbol lookups.
/// Currently unused internally but provided for API completeness and future use.
#[expect(dead_code)] // Future use: symbol vector caching
pub type SymbolCache = LruCache<String, Vec<crate::ingest::SymbolFact>>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_lru_cache_basic_operations() {
let mut cache: LruCache<String, i32> = LruCache::new(3);
// Empty cache
assert_eq!(cache.get(&"a".to_string()), None);
assert_eq!(cache._len(), 0);
assert!(cache._is_empty());
// Insert and get
cache.put("a".to_string(), 1);
cache.put("b".to_string(), 2);
assert_eq!(cache.get(&"a".to_string()), Some(&1));
assert_eq!(cache.get(&"b".to_string()), Some(&2));
assert_eq!(cache._len(), 2);
assert!(!cache._is_empty());
}
#[test]
fn test_lru_cache_eviction() {
let mut cache: LruCache<String, i32> = LruCache::new(2);
cache.put("a".to_string(), 1);
cache.put("b".to_string(), 2);
// Access 'a' to make it more recently used than 'b'
cache.get(&"a".to_string());
// Insert 'c' - should evict 'b' (least recently used)
cache.put("c".to_string(), 3);
assert_eq!(cache.get(&"a".to_string()), Some(&1));
assert_eq!(cache.get(&"b".to_string()), None); // Evicted
assert_eq!(cache.get(&"c".to_string()), Some(&3));
assert_eq!(cache._len(), 2);
}
#[test]
fn test_lru_cache_update_existing() {
let mut cache: LruCache<String, i32> = LruCache::new(3);
cache.put("a".to_string(), 1);
cache.put("b".to_string(), 2);
cache.put("c".to_string(), 3);
// Update 'a' and verify it moves to front
cache.put("a".to_string(), 10);
// Add 'd' - should evict 'b' (now LRU since 'a' was updated)
cache.put("d".to_string(), 4);
assert_eq!(cache.get(&"a".to_string()), Some(&10));
assert_eq!(cache.get(&"b".to_string()), None); // Evicted
assert_eq!(cache.get(&"c".to_string()), Some(&3));
assert_eq!(cache.get(&"d".to_string()), Some(&4));
assert_eq!(cache._len(), 3);
}
#[test]
fn test_lru_cache_invalidate() {
let mut cache: LruCache<String, i32> = LruCache::new(3);
cache.put("a".to_string(), 1);
cache.put("b".to_string(), 2);
cache.put("c".to_string(), 3);
// Invalidate 'b'
cache.invalidate(&"b".to_string());
assert_eq!(cache.get(&"a".to_string()), Some(&1));
assert_eq!(cache.get(&"b".to_string()), None);
assert_eq!(cache.get(&"c".to_string()), Some(&3));
assert_eq!(cache._len(), 2);
}
#[test]
fn test_lru_cache_clear() {
let mut cache: LruCache<String, i32> = LruCache::new(3);
cache.put("a".to_string(), 1);
cache.put("b".to_string(), 2);
cache.clear();
assert_eq!(cache._len(), 0);
assert!(cache._is_empty());
assert_eq!(cache.get(&"a".to_string()), None);
}
#[test]
fn test_cache_stats() {
let mut cache: LruCache<String, i32> = LruCache::new(3);
cache.put("a".to_string(), 1);
cache.put("b".to_string(), 2);
// Generate some hits and misses
cache.get(&"a".to_string()); // hit
cache.get(&"b".to_string()); // hit
cache.get(&"c".to_string()); // miss
let stats = cache.stats();
assert_eq!(stats.hits, 2);
assert_eq!(stats.misses, 1);
assert_eq!(stats.size, 2);
let hit_rate = cache._hit_rate();
assert!((hit_rate - 2.0 / 3.0).abs() < f64::EPSILON);
}
#[test]
fn test_cache_hit_rate_empty() {
let cache: LruCache<String, i32> = LruCache::new(3);
assert_eq!(cache._hit_rate(), 0.0);
}
#[test]
fn test_cache_hit_rate_all_hits() {
let mut cache: LruCache<String, i32> = LruCache::new(3);
cache.put("a".to_string(), 1);
cache.get(&"a".to_string());
cache.get(&"a".to_string());
assert_eq!(cache._hit_rate(), 1.0);
}
#[test]
fn test_cache_hit_rate_all_misses() {
let mut cache: LruCache<String, i32> = LruCache::new(3);
cache.get(&"a".to_string());
cache.get(&"b".to_string());
assert_eq!(cache._hit_rate(), 0.0);
}
}