maproom 0.1.0

Semantic code search powered by embeddings and SQLite
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
//! Cache statistics tracking and reporting.

use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

/// Cache performance statistics.
///
/// Tracks cache operations using atomic counters for lock-free updates.
/// These statistics provide insight into cache effectiveness.
#[derive(Debug, Default)]
pub struct CacheStats {
    /// Number of cache hits
    pub hits: AtomicU64,
    /// Number of cache misses
    pub misses: AtomicU64,
    /// Number of cache evictions (LRU)
    pub evictions: AtomicU64,
    /// Number of expired entries removed
    pub expirations: AtomicU64,
    /// Total cache size in bytes (approximate)
    pub total_size: AtomicUsize,
    /// Number of insertions
    pub insertions: AtomicU64,
}

impl CacheStats {
    /// Create new cache statistics.
    pub fn new() -> Self {
        Self::default()
    }

    /// Calculate cache hit rate (0.0 to 1.0).
    ///
    /// Returns 0.0 if no operations have occurred.
    pub fn hit_rate(&self) -> f64 {
        let hits = self.hits.load(Ordering::Relaxed) as f64;
        let total = hits + self.misses.load(Ordering::Relaxed) as f64;
        if total > 0.0 {
            hits / total
        } else {
            0.0
        }
    }

    /// Get total number of cache operations.
    pub fn total_operations(&self) -> u64 {
        self.hits.load(Ordering::Relaxed) + self.misses.load(Ordering::Relaxed)
    }

    /// Get total cache size in bytes.
    pub fn size_bytes(&self) -> usize {
        self.total_size.load(Ordering::Relaxed)
    }

    /// Get total cache size in megabytes.
    pub fn size_mb(&self) -> f64 {
        self.size_bytes() as f64 / 1_048_576.0
    }

    /// Record a cache hit.
    pub fn record_hit(&self) {
        self.hits.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a cache miss.
    pub fn record_miss(&self) {
        self.misses.fetch_add(1, Ordering::Relaxed);
    }

    /// Record a cache eviction.
    pub fn record_eviction(&self) {
        self.evictions.fetch_add(1, Ordering::Relaxed);
    }

    /// Record an expiration.
    pub fn record_expiration(&self) {
        self.expirations.fetch_add(1, Ordering::Relaxed);
    }

    /// Record an insertion.
    pub fn record_insertion(&self) {
        self.insertions.fetch_add(1, Ordering::Relaxed);
    }

    /// Update cache size.
    pub fn update_size(&self, delta: isize) {
        if delta >= 0 {
            self.total_size.fetch_add(delta as usize, Ordering::Relaxed);
        } else {
            self.total_size
                .fetch_sub((-delta) as usize, Ordering::Relaxed);
        }
    }

    /// Reset all statistics to zero.
    pub fn reset(&self) {
        self.hits.store(0, Ordering::Relaxed);
        self.misses.store(0, Ordering::Relaxed);
        self.evictions.store(0, Ordering::Relaxed);
        self.expirations.store(0, Ordering::Relaxed);
        self.insertions.store(0, Ordering::Relaxed);
        self.total_size.store(0, Ordering::Relaxed);
    }

    /// Get a snapshot of current statistics.
    pub fn snapshot(&self) -> CacheStatsSnapshot {
        CacheStatsSnapshot {
            hits: self.hits.load(Ordering::Relaxed),
            misses: self.misses.load(Ordering::Relaxed),
            evictions: self.evictions.load(Ordering::Relaxed),
            expirations: self.expirations.load(Ordering::Relaxed),
            insertions: self.insertions.load(Ordering::Relaxed),
            total_size_bytes: self.total_size.load(Ordering::Relaxed),
        }
    }
}

/// Snapshot of cache statistics at a point in time.
///
/// This is a serializable copy of the atomic statistics,
/// useful for logging, metrics export, and testing.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CacheStatsSnapshot {
    /// Number of cache hits
    pub hits: u64,
    /// Number of cache misses
    pub misses: u64,
    /// Number of cache evictions
    pub evictions: u64,
    /// Number of expirations
    pub expirations: u64,
    /// Number of insertions
    pub insertions: u64,
    /// Total cache size in bytes
    pub total_size_bytes: usize,
}

impl CacheStatsSnapshot {
    /// Calculate cache hit rate (0.0 to 1.0).
    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
        }
    }

    /// Get total operations.
    pub fn total_operations(&self) -> u64 {
        self.hits + self.misses
    }

    /// Get cache size in megabytes.
    pub fn size_mb(&self) -> f64 {
        self.total_size_bytes as f64 / 1_048_576.0
    }

    /// Check if cache is performing well (hit rate > 60%).
    pub fn is_effective(&self) -> bool {
        self.hit_rate() > 0.6
    }

    /// Get eviction rate (evictions per operation).
    pub fn eviction_rate(&self) -> f64 {
        let total = self.total_operations();
        if total > 0 {
            self.evictions as f64 / total as f64
        } else {
            0.0
        }
    }
}

/// Multi-layer cache statistics aggregator.
///
/// Combines statistics from multiple cache layers (L1, L2, L3, ParseTree)
/// to provide overall system performance metrics.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct MultiLayerStats {
    /// L1 query cache statistics
    pub l1_query: CacheStatsSnapshot,
    /// L2 embedding cache statistics
    pub l2_embedding: CacheStatsSnapshot,
    /// L3 context cache statistics
    pub l3_context: CacheStatsSnapshot,
    /// Parse tree cache statistics
    pub parse_tree: CacheStatsSnapshot,
}

impl MultiLayerStats {
    /// Calculate overall hit rate across all cache layers.
    pub fn overall_hit_rate(&self) -> f64 {
        let total_hits = self.l1_query.hits
            + self.l2_embedding.hits
            + self.l3_context.hits
            + self.parse_tree.hits;
        let total_ops = self.l1_query.total_operations()
            + self.l2_embedding.total_operations()
            + self.l3_context.total_operations()
            + self.parse_tree.total_operations();

        if total_ops > 0 {
            total_hits as f64 / total_ops as f64
        } else {
            0.0
        }
    }

    /// Calculate total memory usage across all caches.
    pub fn total_size_bytes(&self) -> usize {
        self.l1_query.total_size_bytes
            + self.l2_embedding.total_size_bytes
            + self.l3_context.total_size_bytes
            + self.parse_tree.total_size_bytes
    }

    /// Calculate total memory usage in megabytes.
    pub fn total_size_mb(&self) -> f64 {
        self.total_size_bytes() as f64 / 1_048_576.0
    }

    /// Check if overall cache system is effective (>60% hit rate).
    pub fn is_effective(&self) -> bool {
        self.overall_hit_rate() > 0.6
    }

    /// Check if memory usage is within target (<500MB).
    pub fn is_within_memory_target(&self) -> bool {
        self.total_size_mb() < 500.0
    }

    /// Get total operations across all caches.
    pub fn total_operations(&self) -> u64 {
        self.l1_query.total_operations()
            + self.l2_embedding.total_operations()
            + self.l3_context.total_operations()
            + self.parse_tree.total_operations()
    }

    /// Get total evictions across all caches.
    pub fn total_evictions(&self) -> u64 {
        self.l1_query.evictions
            + self.l2_embedding.evictions
            + self.l3_context.evictions
            + self.parse_tree.evictions
    }
}

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

    #[test]
    fn test_cache_stats_hit_rate() {
        let stats = CacheStats::new();

        // No operations yet
        assert_eq!(stats.hit_rate(), 0.0);

        // 60% hit rate
        for _ in 0..60 {
            stats.record_hit();
        }
        for _ in 0..40 {
            stats.record_miss();
        }

        assert!((stats.hit_rate() - 0.6).abs() < 0.01);
    }

    #[test]
    fn test_cache_stats_operations() {
        let stats = CacheStats::new();

        stats.record_hit();
        stats.record_hit();
        stats.record_miss();

        assert_eq!(stats.total_operations(), 3);
        assert_eq!(stats.hits.load(Ordering::Relaxed), 2);
        assert_eq!(stats.misses.load(Ordering::Relaxed), 1);
    }

    #[test]
    fn test_cache_stats_size() {
        let stats = CacheStats::new();

        stats.update_size(1024);
        assert_eq!(stats.size_bytes(), 1024);

        stats.update_size(1024);
        assert_eq!(stats.size_bytes(), 2048);

        stats.update_size(-1024);
        assert_eq!(stats.size_bytes(), 1024);
    }

    #[test]
    fn test_cache_stats_reset() {
        let stats = CacheStats::new();

        stats.record_hit();
        stats.record_miss();
        stats.record_eviction();
        stats.update_size(1024);

        stats.reset();

        assert_eq!(stats.hits.load(Ordering::Relaxed), 0);
        assert_eq!(stats.misses.load(Ordering::Relaxed), 0);
        assert_eq!(stats.evictions.load(Ordering::Relaxed), 0);
        assert_eq!(stats.size_bytes(), 0);
    }

    #[test]
    fn test_cache_stats_snapshot() {
        let stats = CacheStats::new();

        stats.record_hit();
        stats.record_hit();
        stats.record_miss();
        stats.update_size(1024);

        let snapshot = stats.snapshot();

        assert_eq!(snapshot.hits, 2);
        assert_eq!(snapshot.misses, 1);
        assert_eq!(snapshot.total_size_bytes, 1024);
        assert_eq!(snapshot.hit_rate(), 2.0 / 3.0);
    }

    #[test]
    fn test_snapshot_is_effective() {
        let mut snapshot = CacheStatsSnapshot {
            hits: 70,
            misses: 30,
            evictions: 0,
            expirations: 0,
            insertions: 100,
            total_size_bytes: 0,
        };

        assert!(snapshot.is_effective()); // 70% hit rate

        snapshot.hits = 50;
        snapshot.misses = 50;
        assert!(!snapshot.is_effective()); // 50% hit rate
    }

    #[test]
    fn test_multi_layer_stats() {
        let stats = MultiLayerStats {
            l1_query: CacheStatsSnapshot {
                hits: 60,
                misses: 40,
                evictions: 5,
                expirations: 2,
                insertions: 100,
                total_size_bytes: 10_000_000, // 10 MB
            },
            l2_embedding: CacheStatsSnapshot {
                hits: 80,
                misses: 20,
                evictions: 3,
                expirations: 1,
                insertions: 100,
                total_size_bytes: 50_000_000, // 50 MB
            },
            l3_context: CacheStatsSnapshot {
                hits: 70,
                misses: 30,
                evictions: 4,
                expirations: 3,
                insertions: 100,
                total_size_bytes: 30_000_000, // 30 MB
            },
            parse_tree: CacheStatsSnapshot {
                hits: 90,
                misses: 10,
                evictions: 2,
                expirations: 0,
                insertions: 100,
                total_size_bytes: 20_000_000, // 20 MB
            },
        };

        // Overall hit rate: (60+80+70+90) / (60+40+80+20+70+30+90+10) = 300/400 = 0.75
        assert!((stats.overall_hit_rate() - 0.75).abs() < 0.01);

        // Total size: ~104.9 MiB (110 million bytes / 1,048,576 bytes per MiB)
        let actual_mb = stats.total_size_mb();
        assert!(
            (actual_mb - 104.9).abs() < 0.2,
            "Expected ~104.9 MiB, got {} MiB (total bytes: {})",
            actual_mb,
            stats.total_size_bytes()
        );

        // Is effective (>60% hit rate)
        assert!(stats.is_effective());

        // Within memory target (<500MB)
        assert!(stats.is_within_memory_target());

        // Total operations
        assert_eq!(stats.total_operations(), 400);

        // Total evictions
        assert_eq!(stats.total_evictions(), 14);
    }
}