ruvllm 2.2.0

LLM serving runtime with Ruvector integration - Paged attention, KV cache, and SONA learning
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
//! Semantic Tool Cache - Caches tool results with similarity-based retrieval
//!
//! Provides intelligent caching of tool execution results using HNSW-indexed
//! embeddings for semantic similarity matching.

use chrono::{DateTime, Duration, Utc};
use parking_lot::RwLock;
use ruvector_core::index::hnsw::HnswIndex;
use ruvector_core::index::VectorIndex;
use ruvector_core::types::{DistanceMetric, HnswConfig};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;

use crate::error::{Result, RuvLLMError};

/// Configuration for semantic tool cache
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SemanticCacheConfig {
    /// Embedding dimension
    pub embedding_dim: usize,
    /// Maximum cached entries
    pub max_entries: usize,
    /// Similarity threshold for cache hits (0.0 - 1.0)
    pub similarity_threshold: f32,
    /// Default TTL in seconds
    pub default_ttl_seconds: i64,
    /// HNSW M parameter
    pub hnsw_m: usize,
    /// HNSW ef_construction parameter
    pub hnsw_ef_construction: usize,
    /// HNSW ef_search parameter
    pub hnsw_ef_search: usize,
    /// Enable LRU eviction
    pub enable_lru: bool,
}

impl Default for SemanticCacheConfig {
    fn default() -> Self {
        Self {
            embedding_dim: 768,
            max_entries: 1_000,
            similarity_threshold: 0.85,
            default_ttl_seconds: 3600, // 1 hour
            hnsw_m: 16,
            hnsw_ef_construction: 100,
            hnsw_ef_search: 50,
            enable_lru: true,
        }
    }
}

/// A cached tool result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CachedToolResult {
    /// Cache entry ID
    pub id: String,
    /// Tool name
    pub tool_name: String,
    /// Input hash for exact matching
    pub input_hash: String,
    /// Input embedding for similarity matching
    pub embedding: Vec<f32>,
    /// Tool result
    pub result: String,
    /// Success status
    pub success: bool,
    /// Similarity score (1.0 for exact match)
    pub similarity: f32,
    /// Access count
    pub access_count: u64,
    /// Cached timestamp
    pub cached_at: DateTime<Utc>,
    /// Last accessed timestamp
    pub last_accessed: DateTime<Utc>,
    /// Time-to-live
    pub ttl: Duration,
    /// Metadata
    pub metadata: HashMap<String, String>,
}

/// Cache statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheStats {
    /// Total entries
    pub total_entries: usize,
    /// Total lookups
    pub total_lookups: u64,
    /// Cache hits
    pub hits: u64,
    /// Cache misses
    pub misses: u64,
    /// Hit rate (0.0 - 1.0)
    pub hit_rate: f32,
    /// Exact matches (hash-based)
    pub exact_matches: u64,
    /// Semantic matches (embedding-based)
    pub semantic_matches: u64,
    /// Evictions
    pub evictions: u64,
    /// Expirations
    pub expirations: u64,
}

/// Internal statistics tracking
#[derive(Debug, Default)]
struct StatsInternal {
    lookups: AtomicU64,
    hits: AtomicU64,
    misses: AtomicU64,
    exact_matches: AtomicU64,
    semantic_matches: AtomicU64,
    evictions: AtomicU64,
    expirations: AtomicU64,
}

/// Semantic tool cache with HNSW indexing
pub struct SemanticToolCache {
    /// Configuration
    config: SemanticCacheConfig,
    /// HNSW index for similarity search
    index: Arc<RwLock<HnswIndex>>,
    /// Cache storage
    cache: Arc<RwLock<HashMap<String, CachedToolResult>>>,
    /// Hash to ID mapping for exact matches
    hash_index: Arc<RwLock<HashMap<String, String>>>,
    /// Statistics
    stats: StatsInternal,
}

impl SemanticToolCache {
    /// Create new semantic cache with configuration
    pub fn new(config: SemanticCacheConfig) -> Result<Self> {
        let hnsw_config = HnswConfig {
            m: config.hnsw_m,
            ef_construction: config.hnsw_ef_construction,
            ef_search: config.hnsw_ef_search,
            max_elements: config.max_entries,
        };

        let index = HnswIndex::new(config.embedding_dim, DistanceMetric::Cosine, hnsw_config)
            .map_err(|e| RuvLLMError::Ruvector(e.to_string()))?;

        Ok(Self {
            config,
            index: Arc::new(RwLock::new(index)),
            cache: Arc::new(RwLock::new(HashMap::new())),
            hash_index: Arc::new(RwLock::new(HashMap::new())),
            stats: StatsInternal::default(),
        })
    }

    /// Store a tool result in cache
    pub fn store(
        &self,
        tool_name: &str,
        input: &str,
        result: &str,
        embedding: Vec<f32>,
    ) -> Result<()> {
        self.store_with_options(
            tool_name,
            input,
            result,
            embedding,
            true,
            Duration::seconds(self.config.default_ttl_seconds),
            HashMap::new(),
        )
    }

    /// Store with custom options
    pub fn store_with_options(
        &self,
        tool_name: &str,
        input: &str,
        result: &str,
        embedding: Vec<f32>,
        success: bool,
        ttl: Duration,
        metadata: HashMap<String, String>,
    ) -> Result<()> {
        let input_hash = format!("{:x}", md5::compute(input));
        let id = format!("{}:{}", tool_name, uuid::Uuid::new_v4());
        let now = Utc::now();

        let entry = CachedToolResult {
            id: id.clone(),
            tool_name: tool_name.to_string(),
            input_hash: input_hash.clone(),
            embedding: embedding.clone(),
            result: result.to_string(),
            success,
            similarity: 1.0, // Exact match for stored entry
            access_count: 0,
            cached_at: now,
            last_accessed: now,
            ttl,
            metadata,
        };

        // Add to HNSW index
        {
            let mut index = self.index.write();
            index.add(id.clone(), embedding)?;
        }

        // Store entry
        {
            let mut cache = self.cache.write();
            cache.insert(id.clone(), entry);
        }

        // Update hash index
        {
            let mut hash_idx = self.hash_index.write();
            hash_idx.insert(input_hash, id);
        }

        // Enforce limit
        self.enforce_limit()?;

        Ok(())
    }

    /// Get cached result by embedding similarity
    pub fn get(&self, query_embedding: &[f32]) -> Result<Option<CachedToolResult>> {
        self.stats.lookups.fetch_add(1, Ordering::SeqCst);

        // Search for similar entries
        let results = {
            let index = self.index.read();
            index.search(query_embedding, 1)?
        };

        if results.is_empty() {
            self.stats.misses.fetch_add(1, Ordering::SeqCst);
            return Ok(None);
        }

        let best = &results[0];
        let similarity = 1.0 - best.score; // Convert distance to similarity

        if similarity < self.config.similarity_threshold {
            self.stats.misses.fetch_add(1, Ordering::SeqCst);
            return Ok(None);
        }

        // Get the entry
        let mut cache = self.cache.write();
        if let Some(entry) = cache.get_mut(&best.id) {
            // Check TTL
            if Utc::now() - entry.cached_at > entry.ttl {
                // Expired
                self.stats.expirations.fetch_add(1, Ordering::SeqCst);
                self.stats.misses.fetch_add(1, Ordering::SeqCst);

                // Remove expired entry
                let id = entry.id.clone();
                drop(cache);
                self.remove(&id)?;
                return Ok(None);
            }

            // Update access stats
            entry.access_count += 1;
            entry.last_accessed = Utc::now();
            entry.similarity = similarity;

            self.stats.hits.fetch_add(1, Ordering::SeqCst);
            self.stats.semantic_matches.fetch_add(1, Ordering::SeqCst);

            return Ok(Some(entry.clone()));
        }

        self.stats.misses.fetch_add(1, Ordering::SeqCst);
        Ok(None)
    }

    /// Get by exact input hash
    pub fn get_exact(&self, tool_name: &str, input: &str) -> Result<Option<CachedToolResult>> {
        self.stats.lookups.fetch_add(1, Ordering::SeqCst);

        let input_hash = format!("{:x}", md5::compute(input));

        // Look up by hash
        let id = {
            let hash_idx = self.hash_index.read();
            hash_idx.get(&input_hash).cloned()
        };

        if let Some(id) = id {
            let mut cache = self.cache.write();
            if let Some(entry) = cache.get_mut(&id) {
                // Verify tool name
                if entry.tool_name != tool_name {
                    self.stats.misses.fetch_add(1, Ordering::SeqCst);
                    return Ok(None);
                }

                // Check TTL
                if Utc::now() - entry.cached_at > entry.ttl {
                    self.stats.expirations.fetch_add(1, Ordering::SeqCst);
                    self.stats.misses.fetch_add(1, Ordering::SeqCst);

                    let id = entry.id.clone();
                    drop(cache);
                    self.remove(&id)?;
                    return Ok(None);
                }

                // Update access stats
                entry.access_count += 1;
                entry.last_accessed = Utc::now();
                entry.similarity = 1.0; // Exact match

                self.stats.hits.fetch_add(1, Ordering::SeqCst);
                self.stats.exact_matches.fetch_add(1, Ordering::SeqCst);

                return Ok(Some(entry.clone()));
            }
        }

        self.stats.misses.fetch_add(1, Ordering::SeqCst);
        Ok(None)
    }

    /// Get or execute - returns cached result or executes function
    pub fn get_or_execute<F, E>(
        &self,
        tool_name: &str,
        input: &str,
        embedding: Vec<f32>,
        execute: F,
    ) -> std::result::Result<String, E>
    where
        F: FnOnce() -> std::result::Result<String, E>,
        E: std::fmt::Debug,
    {
        // Try exact match first
        if let Ok(Some(cached)) = self.get_exact(tool_name, input) {
            return Ok(cached.result);
        }

        // Try semantic match
        if let Ok(Some(cached)) = self.get(&embedding) {
            if cached.tool_name == tool_name {
                return Ok(cached.result);
            }
        }

        // Execute and cache
        let result = execute()?;

        // Store result (ignore errors)
        let _ = self.store(tool_name, input, &result, embedding);

        Ok(result)
    }

    /// Remove entry by ID
    pub fn remove(&self, id: &str) -> Result<bool> {
        let entry = {
            let mut cache = self.cache.write();
            cache.remove(id)
        };

        if let Some(entry) = entry {
            // Remove from hash index
            {
                let mut hash_idx = self.hash_index.write();
                hash_idx.remove(&entry.input_hash);
            }

            // Remove from HNSW index
            {
                let mut index = self.index.write();
                let _ = index.remove(&id.to_string());
            }

            return Ok(true);
        }

        Ok(false)
    }

    /// Invalidate entries by tool name
    pub fn invalidate_tool(&self, tool_name: &str) -> Result<usize> {
        let to_remove: Vec<String> = {
            let cache = self.cache.read();
            cache
                .iter()
                .filter(|(_, e)| e.tool_name == tool_name)
                .map(|(id, _)| id.clone())
                .collect()
        };

        let count = to_remove.len();
        for id in to_remove {
            self.remove(&id)?;
        }

        Ok(count)
    }

    /// Clean expired entries
    pub fn clean_expired(&self) -> Result<usize> {
        let now = Utc::now();
        let expired: Vec<String> = {
            let cache = self.cache.read();
            cache
                .iter()
                .filter(|(_, e)| now - e.cached_at > e.ttl)
                .map(|(id, _)| id.clone())
                .collect()
        };

        let count = expired.len();
        for id in expired {
            self.remove(&id)?;
            self.stats.expirations.fetch_add(1, Ordering::SeqCst);
        }

        Ok(count)
    }

    /// Enforce storage limit
    fn enforce_limit(&self) -> Result<()> {
        let cache = self.cache.read();

        if cache.len() <= self.config.max_entries {
            return Ok(());
        }

        drop(cache);

        if self.config.enable_lru {
            // Remove least recently accessed
            let to_remove: Option<String> = {
                let cache = self.cache.read();
                cache
                    .iter()
                    .min_by_key(|(_, e)| e.last_accessed)
                    .map(|(id, _)| id.clone())
            };

            if let Some(id) = to_remove {
                self.remove(&id)?;
                self.stats.evictions.fetch_add(1, Ordering::SeqCst);
            }
        } else {
            // Remove oldest
            let to_remove: Option<String> = {
                let cache = self.cache.read();
                cache
                    .iter()
                    .min_by_key(|(_, e)| e.cached_at)
                    .map(|(id, _)| id.clone())
            };

            if let Some(id) = to_remove {
                self.remove(&id)?;
                self.stats.evictions.fetch_add(1, Ordering::SeqCst);
            }
        }

        Ok(())
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        let total = self.cache.read().len();
        let lookups = self.stats.lookups.load(Ordering::SeqCst);
        let hits = self.stats.hits.load(Ordering::SeqCst);
        let misses = self.stats.misses.load(Ordering::SeqCst);

        CacheStats {
            total_entries: total,
            total_lookups: lookups,
            hits,
            misses,
            hit_rate: if lookups > 0 {
                hits as f32 / lookups as f32
            } else {
                0.0
            },
            exact_matches: self.stats.exact_matches.load(Ordering::SeqCst),
            semantic_matches: self.stats.semantic_matches.load(Ordering::SeqCst),
            evictions: self.stats.evictions.load(Ordering::SeqCst),
            expirations: self.stats.expirations.load(Ordering::SeqCst),
        }
    }

    /// Clear all entries
    pub fn clear(&self) -> Result<()> {
        self.cache.write().clear();
        self.hash_index.write().clear();

        // Recreate index
        let hnsw_config = HnswConfig {
            m: self.config.hnsw_m,
            ef_construction: self.config.hnsw_ef_construction,
            ef_search: self.config.hnsw_ef_search,
            max_elements: self.config.max_entries,
        };

        *self.index.write() = HnswIndex::new(
            self.config.embedding_dim,
            DistanceMetric::Cosine,
            hnsw_config,
        )
        .map_err(|e| RuvLLMError::Ruvector(e.to_string()))?;

        Ok(())
    }
}

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

    fn test_embedding(dim: usize) -> Vec<f32> {
        vec![0.1; dim]
    }

    #[test]
    fn test_cache_creation() {
        let config = SemanticCacheConfig {
            embedding_dim: 128,
            ..Default::default()
        };
        let cache = SemanticToolCache::new(config).unwrap();
        assert_eq!(cache.stats().total_entries, 0);
    }

    #[test]
    fn test_store_and_get_exact() {
        let config = SemanticCacheConfig {
            embedding_dim: 128,
            ..Default::default()
        };
        let cache = SemanticToolCache::new(config).unwrap();

        let embedding = test_embedding(128);
        cache
            .store("read_file", "/path/to/file.rs", "file contents", embedding)
            .unwrap();

        let result = cache.get_exact("read_file", "/path/to/file.rs").unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().result, "file contents");

        // Different input should not match
        let result = cache.get_exact("read_file", "/other/file.rs").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_store_and_get_semantic() {
        let config = SemanticCacheConfig {
            embedding_dim: 128,
            similarity_threshold: 0.8,
            ..Default::default()
        };
        let cache = SemanticToolCache::new(config).unwrap();

        let embedding = test_embedding(128);
        cache
            .store(
                "read_file",
                "/path/to/file.rs",
                "file contents",
                embedding.clone(),
            )
            .unwrap();

        // Same embedding should match
        let result = cache.get(&embedding).unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().result, "file contents");
    }

    #[test]
    fn test_get_or_execute() {
        let config = SemanticCacheConfig {
            embedding_dim: 128,
            ..Default::default()
        };
        let cache = SemanticToolCache::new(config).unwrap();

        let embedding = test_embedding(128);

        // First call should execute
        let result: std::result::Result<String, &str> =
            cache.get_or_execute("test_tool", "input", embedding.clone(), || {
                Ok("executed".to_string())
            });
        assert_eq!(result.unwrap(), "executed");

        // Second call should return cached
        let result: std::result::Result<String, &str> =
            cache.get_or_execute("test_tool", "input", embedding, || {
                Ok("should not execute".to_string())
            });
        assert_eq!(result.unwrap(), "executed");
    }

    #[test]
    fn test_invalidate_tool() {
        let config = SemanticCacheConfig {
            embedding_dim: 128,
            ..Default::default()
        };
        let cache = SemanticToolCache::new(config).unwrap();

        let embedding = test_embedding(128);
        cache
            .store("tool_a", "input1", "result1", embedding.clone())
            .unwrap();
        cache
            .store("tool_b", "input2", "result2", embedding.clone())
            .unwrap();

        assert_eq!(cache.stats().total_entries, 2);

        let removed = cache.invalidate_tool("tool_a").unwrap();
        assert_eq!(removed, 1);
        assert_eq!(cache.stats().total_entries, 1);
    }

    #[test]
    fn test_stats() {
        let config = SemanticCacheConfig {
            embedding_dim: 128,
            ..Default::default()
        };
        let cache = SemanticToolCache::new(config).unwrap();

        let embedding = test_embedding(128);
        cache
            .store("tool", "input", "result", embedding.clone())
            .unwrap();

        // Hit
        cache.get_exact("tool", "input").unwrap();

        // Miss
        cache.get_exact("tool", "other").unwrap();

        let stats = cache.stats();
        assert_eq!(stats.total_entries, 1);
        assert_eq!(stats.total_lookups, 2);
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
        assert!((stats.hit_rate - 0.5).abs() < 0.001);
    }

    #[test]
    fn test_clear() {
        let config = SemanticCacheConfig {
            embedding_dim: 128,
            ..Default::default()
        };
        let cache = SemanticToolCache::new(config).unwrap();

        let embedding = test_embedding(128);
        cache.store("tool", "input", "result", embedding).unwrap();

        assert_eq!(cache.stats().total_entries, 1);
        cache.clear().unwrap();
        assert_eq!(cache.stats().total_entries, 0);
    }
}