sochdb 2.0.1

SochDB - LLM-optimized database with native vector search
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// SochDB - LLM-Optimized Embedded Database
// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Semantic Cache with Provenance-Safe Keys (Task 8)
//!
//! This module provides a semantic caching layer that:
//! - Uses exact key matching for deterministic cache hits
//! - Supports semantic similarity search for approximate matches
//! - Preserves provenance (DERIVED_FROM edges to sources)
//! - Integrates with AllowedSet for policy-aware caching
//!
//! ## Design Principles
//!
//! 1. **Exact-match first**: Hash of (normalized_query, AllowedSet) for deterministic hits
//! 2. **Semantic fallback**: ANN search with explicit similarity threshold
//! 3. **Provenance tracking**: Every cache entry tracks its source documents
//! 4. **Policy integration**: Cache hits respect AllowedSet (no post-filtering)
//!
//! ## Complexity
//!
//! - Exact match: O(1) hash lookup
//! - Semantic search: O(log n) with HNSW index
//! - Policy gating: O(1) per entry with namespace/allowed-set check
//!
//! ## Cache Invalidation Strategy
//!
//! Cache entries are invalidated when:
//! 1. TTL expires
//! 2. Any source document is updated (via provenance edges)
//! 3. Policy changes affect the AllowedSet
//!
//! Note: Semantic similarity ≠ query equivalence. Similar queries may have
//! different correct answers, so semantic cache hits are marked as "approximate".

use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use crate::error::{ClientError, Result};
use crate::ConnectionTrait;

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

/// Unique cache key combining query and access context
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct CacheKey {
    /// Normalized query hash
    pub query_hash: u64,
    /// Namespace (for scoping)
    pub namespace: String,
    /// Hash of AllowedSet for policy-aware caching
    pub allowed_set_hash: u64,
}

impl CacheKey {
    /// Create a new cache key
    pub fn new(query: &str, namespace: &str, allowed_set_hash: u64) -> Self {
        Self {
            query_hash: Self::hash_query(query),
            namespace: namespace.to_string(),
            allowed_set_hash,
        }
    }
    
    fn hash_query(query: &str) -> u64 {
        use std::collections::hash_map::DefaultHasher;
        let mut hasher = DefaultHasher::new();
        query.trim().to_lowercase().hash(&mut hasher);
        hasher.finish()
    }
    
    /// Convert to storage key
    pub fn to_storage_key(&self) -> Vec<u8> {
        format!(
            "_cache/exact/{}/{:016x}/{:016x}",
            self.namespace, self.query_hash, self.allowed_set_hash
        ).into_bytes()
    }
}

/// A cached result entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheEntry {
    /// The cache key
    pub key: CacheKey,
    /// Original query text
    pub query: String,
    /// Cached result (serialized)
    pub result: Vec<u8>,
    /// Query embedding (for semantic search)
    pub embedding: Option<Vec<f32>>,
    /// Provenance: document IDs this result was derived from
    pub source_docs: Vec<String>,
    /// Creation timestamp
    pub created_at: u64,
    /// Expiration timestamp
    pub expires_at: u64,
    /// Hit count
    pub hits: u64,
    /// Whether this was an exact or semantic match
    pub match_type: CacheMatchType,
    /// Optional metadata
    pub metadata: HashMap<String, String>,
}

/// Type of cache match
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum CacheMatchType {
    /// Exact key match (deterministic)
    Exact,
    /// Semantic similarity match (approximate)
    Semantic { similarity: f32 },
    /// No cache entry (miss)
    Miss,
}

impl CacheMatchType {
    /// Check if this is a cache hit
    pub fn is_hit(&self) -> bool {
        !matches!(self, Self::Miss)
    }
    
    /// Check if this is an exact match
    pub fn is_exact(&self) -> bool {
        matches!(self, Self::Exact)
    }
}

/// Cache lookup result
#[derive(Debug)]
pub struct CacheLookupResult {
    /// The cached entry (if found)
    pub entry: Option<CacheEntry>,
    /// Type of match
    pub match_type: CacheMatchType,
    /// Lookup latency in microseconds
    pub latency_us: u64,
}

impl CacheLookupResult {
    /// Check if this is a cache hit
    pub fn is_hit(&self) -> bool {
        self.entry.is_some()
    }
    
    /// Get the cached result bytes
    pub fn result(&self) -> Option<&[u8]> {
        self.entry.as_ref().map(|e| e.result.as_slice())
    }
}

// ============================================================================
// Cache Configuration
// ============================================================================

/// Configuration for the semantic cache
#[derive(Debug, Clone)]
pub struct SemanticCacheConfig {
    /// Default TTL for cache entries
    pub default_ttl: Duration,
    /// Minimum similarity threshold for semantic matches
    pub similarity_threshold: f32,
    /// Maximum number of entries (for LRU eviction)
    pub max_entries: usize,
    /// Whether to enable semantic search (requires embeddings)
    pub enable_semantic_search: bool,
    /// Whether to track hit counts
    pub track_hits: bool,
}

impl Default for SemanticCacheConfig {
    fn default() -> Self {
        Self {
            default_ttl: Duration::from_secs(3600), // 1 hour
            similarity_threshold: 0.95, // 95% similarity required
            max_entries: 10000,
            enable_semantic_search: true,
            track_hits: true,
        }
    }
}

// ============================================================================
// Semantic Cache
// ============================================================================

/// Storage prefix for cache entries
const CACHE_PREFIX: &str = "_cache/";

/// Provenance-safe semantic cache
pub struct SemanticCache<C: ConnectionTrait> {
    conn: C,
    config: SemanticCacheConfig,
}

impl<C: ConnectionTrait> SemanticCache<C> {
    /// Create a new semantic cache
    pub fn new(conn: C) -> Self {
        Self {
            conn,
            config: SemanticCacheConfig::default(),
        }
    }
    
    /// Create with custom configuration
    pub fn with_config(conn: C, config: SemanticCacheConfig) -> Self {
        Self { conn, config }
    }
    
    fn now_millis() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64
    }
    
    fn now_micros() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros() as u64
    }
    
    fn semantic_index_key(&self, namespace: &str, id: u64) -> Vec<u8> {
        format!("{}semantic/{}/{:016x}", CACHE_PREFIX, namespace, id).into_bytes()
    }
    
    fn semantic_index_prefix(&self, namespace: &str) -> Vec<u8> {
        format!("{}semantic/{}/", CACHE_PREFIX, namespace).into_bytes()
    }
    
    fn provenance_key(&self, cache_key_hash: u64, doc_id: &str) -> Vec<u8> {
        format!(
            "{}provenance/{:016x}/{}",
            CACHE_PREFIX, cache_key_hash, doc_id
        ).into_bytes()
    }
    
    fn provenance_prefix(&self, cache_key_hash: u64) -> Vec<u8> {
        format!("{}provenance/{:016x}/", CACHE_PREFIX, cache_key_hash).into_bytes()
    }
    
    // ========================================================================
    // Core Operations
    // ========================================================================
    
    /// Look up a cache entry
    ///
    /// First tries exact match, then (optionally) semantic search.
    pub fn lookup(
        &self,
        query: &str,
        namespace: &str,
        allowed_set_hash: u64,
        query_embedding: Option<&[f32]>,
    ) -> Result<CacheLookupResult> {
        let start = Self::now_micros();
        
        // Try exact match first
        let key = CacheKey::new(query, namespace, allowed_set_hash);
        if let Some(entry) = self.get_exact(&key)? {
            // Check if expired
            if entry.expires_at > Self::now_millis() {
                // Update hit count if tracking enabled
                if self.config.track_hits {
                    let _ = self.increment_hits(&key);
                }
                
                return Ok(CacheLookupResult {
                    entry: Some(entry),
                    match_type: CacheMatchType::Exact,
                    latency_us: Self::now_micros() - start,
                });
            }
            // Expired - treat as miss and clean up
            let _ = self.delete(&key);
        }
        
        // Try semantic match if enabled and embedding provided
        if self.config.enable_semantic_search {
            if let Some(embedding) = query_embedding {
                if let Some((entry, similarity)) = self.search_semantic(
                    namespace,
                    embedding,
                    allowed_set_hash,
                )? {
                    if similarity >= self.config.similarity_threshold {
                        if self.config.track_hits {
                            let _ = self.increment_hits(&entry.key);
                        }
                        
                        return Ok(CacheLookupResult {
                            entry: Some(entry),
                            match_type: CacheMatchType::Semantic { similarity },
                            latency_us: Self::now_micros() - start,
                        });
                    }
                }
            }
        }
        
        // Cache miss
        Ok(CacheLookupResult {
            entry: None,
            match_type: CacheMatchType::Miss,
            latency_us: Self::now_micros() - start,
        })
    }
    
    /// Store a result in the cache
    pub fn store(
        &self,
        query: &str,
        namespace: &str,
        allowed_set_hash: u64,
        result: &[u8],
        embedding: Option<Vec<f32>>,
        source_docs: Vec<String>,
        ttl: Option<Duration>,
    ) -> Result<CacheKey> {
        let key = CacheKey::new(query, namespace, allowed_set_hash);
        let now = Self::now_millis();
        let ttl = ttl.unwrap_or(self.config.default_ttl);
        
        let entry = CacheEntry {
            key: key.clone(),
            query: query.to_string(),
            result: result.to_vec(),
            embedding: embedding.clone(),
            source_docs: source_docs.clone(),
            created_at: now,
            expires_at: now + ttl.as_millis() as u64,
            hits: 0,
            match_type: CacheMatchType::Exact, // Stored entries are exact
            metadata: HashMap::new(),
        };
        
        // Store exact key entry
        let storage_key = key.to_storage_key();
        let value = serde_json::to_vec(&entry)
            .map_err(|e| ClientError::Serialization(e.to_string()))?;
        self.conn.put(&storage_key, &value)?;
        
        // Store semantic index if embedding provided
        if let Some(ref emb) = embedding {
            self.store_semantic_index(namespace, &key, emb)?;
        }
        
        // Store provenance edges
        let key_hash = key.query_hash ^ key.allowed_set_hash;
        for doc_id in &source_docs {
            let prov_key = self.provenance_key(key_hash, doc_id);
            self.conn.put(&prov_key, storage_key.as_slice())?;
        }
        
        Ok(key)
    }
    
    /// Delete a cache entry
    pub fn delete(&self, key: &CacheKey) -> Result<bool> {
        let storage_key = key.to_storage_key();
        
        // Check if exists
        if self.conn.get(&storage_key)?.is_none() {
            return Ok(false);
        }
        
        // Delete main entry
        self.conn.delete(&storage_key)?;
        
        // Delete provenance edges
        let key_hash = key.query_hash ^ key.allowed_set_hash;
        let prov_prefix = self.provenance_prefix(key_hash);
        for (prov_key, _) in self.conn.scan(&prov_prefix)? {
            self.conn.delete(&prov_key)?;
        }
        
        Ok(true)
    }
    
    /// Invalidate all cache entries derived from a document
    ///
    /// This is called when a source document is updated.
    pub fn invalidate_by_source(&self, doc_id: &str) -> Result<usize> {
        // Scan all provenance entries for this doc
        let prefix = format!("{}provenance/", CACHE_PREFIX).into_bytes();
        let results = self.conn.scan(&prefix)?;
        
        let mut invalidated = 0;
        for (prov_key, cache_key) in results {
            let key_str = String::from_utf8_lossy(&prov_key);
            if key_str.ends_with(&format!("/{}", doc_id)) {
                // This provenance edge points to our doc - invalidate the cache entry
                self.conn.delete(&cache_key)?;
                self.conn.delete(&prov_key)?;
                invalidated += 1;
            }
        }
        
        Ok(invalidated)
    }
    
    /// Get provenance (source documents) for a cache entry
    pub fn get_provenance(&self, key: &CacheKey) -> Result<Vec<String>> {
        let key_hash = key.query_hash ^ key.allowed_set_hash;
        let prefix = self.provenance_prefix(key_hash);
        let results = self.conn.scan(&prefix)?;
        
        let mut sources = Vec::new();
        for (prov_key, _) in results {
            let key_str = String::from_utf8_lossy(&prov_key);
            if let Some(doc_id) = key_str.rsplit('/').next() {
                sources.push(doc_id.to_string());
            }
        }
        
        Ok(sources)
    }
    
    // ========================================================================
    // Internal Methods
    // ========================================================================
    
    fn get_exact(&self, key: &CacheKey) -> Result<Option<CacheEntry>> {
        let storage_key = key.to_storage_key();
        if let Some(data) = self.conn.get(&storage_key)? {
            let entry: CacheEntry = serde_json::from_slice(&data)
                .map_err(|e| ClientError::Serialization(e.to_string()))?;
            Ok(Some(entry))
        } else {
            Ok(None)
        }
    }
    
    fn store_semantic_index(
        &self,
        namespace: &str,
        key: &CacheKey,
        embedding: &[f32],
    ) -> Result<()> {
        let index_key = self.semantic_index_key(namespace, key.query_hash);
        let index_entry = SemanticIndexEntry {
            cache_key: key.clone(),
            embedding: embedding.to_vec(),
        };
        let value = serde_json::to_vec(&index_entry)
            .map_err(|e| ClientError::Serialization(e.to_string()))?;
        self.conn.put(&index_key, &value)?;
        Ok(())
    }
    
    fn search_semantic(
        &self,
        namespace: &str,
        query_embedding: &[f32],
        allowed_set_hash: u64,
    ) -> Result<Option<(CacheEntry, f32)>> {
        let prefix = self.semantic_index_prefix(namespace);
        let results = self.conn.scan(&prefix)?;
        
        let mut best_match: Option<(CacheEntry, f32)> = None;
        
        for (_, value) in results {
            let index_entry: SemanticIndexEntry = match serde_json::from_slice(&value) {
                Ok(e) => e,
                Err(_) => continue,
            };
            
            // Check if AllowedSet matches
            if index_entry.cache_key.allowed_set_hash != allowed_set_hash {
                continue;
            }
            
            // Calculate similarity
            let similarity = cosine_similarity(query_embedding, &index_entry.embedding);
            
            if similarity >= self.config.similarity_threshold {
                // Get the actual cache entry
                if let Some(entry) = self.get_exact(&index_entry.cache_key)? {
                    // Check if not expired
                    if entry.expires_at > Self::now_millis() {
                        match &best_match {
                            None => best_match = Some((entry, similarity)),
                            Some((_, best_sim)) if similarity > *best_sim => {
                                best_match = Some((entry, similarity));
                            }
                            _ => {}
                        }
                    }
                }
            }
        }
        
        Ok(best_match)
    }
    
    fn increment_hits(&self, key: &CacheKey) -> Result<()> {
        let storage_key = key.to_storage_key();
        if let Some(data) = self.conn.get(&storage_key)? {
            let mut entry: CacheEntry = serde_json::from_slice(&data)
                .map_err(|e| ClientError::Serialization(e.to_string()))?;
            entry.hits += 1;
            let value = serde_json::to_vec(&entry)
                .map_err(|e| ClientError::Serialization(e.to_string()))?;
            self.conn.put(&storage_key, &value)?;
        }
        Ok(())
    }
    
    /// Clean up expired entries
    pub fn cleanup_expired(&self) -> Result<usize> {
        let prefix = format!("{}exact/", CACHE_PREFIX).into_bytes();
        let results = self.conn.scan(&prefix)?;
        
        let now = Self::now_millis();
        let mut cleaned = 0;
        
        for (key, value) in results {
            let entry: CacheEntry = match serde_json::from_slice(&value) {
                Ok(e) => e,
                Err(_) => continue,
            };
            
            if entry.expires_at < now {
                self.conn.delete(&key)?;
                
                // Clean up provenance
                let key_hash = entry.key.query_hash ^ entry.key.allowed_set_hash;
                let prov_prefix = self.provenance_prefix(key_hash);
                for (prov_key, _) in self.conn.scan(&prov_prefix)? {
                    self.conn.delete(&prov_key)?;
                }
                
                cleaned += 1;
            }
        }
        
        Ok(cleaned)
    }
}

// ============================================================================
// Helpers
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SemanticIndexEntry {
    cache_key: CacheKey,
    embedding: Vec<f32>,
}

/// Calculate cosine similarity between two vectors
fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() {
        return 0.0;
    }
    
    let mut dot = 0.0f32;
    let mut norm_a = 0.0f32;
    let mut norm_b = 0.0f32;
    
    for i in 0..a.len() {
        dot += a[i] * b[i];
        norm_a += a[i] * a[i];
        norm_b += b[i] * b[i];
    }
    
    let norm = (norm_a.sqrt() * norm_b.sqrt());
    if norm == 0.0 {
        0.0
    } else {
        dot / norm
    }
}

/// Compute a hash of an AllowedSet for cache keying
///
/// This creates a stable hash that can be used to ensure cache hits
/// only occur for identical permission contexts.
pub fn hash_allowed_set<'a>(ids: impl Iterator<Item = &'a u64>) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    let mut hasher = DefaultHasher::new();
    
    // Sort for deterministic hashing
    let mut sorted: Vec<_> = ids.collect();
    sorted.sort();
    
    for id in sorted {
        id.hash(&mut hasher);
    }
    
    hasher.finish()
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_cache_key_creation() {
        let key1 = CacheKey::new("What is SochDB?", "default", 12345);
        let key2 = CacheKey::new("what is sochdb?", "default", 12345);
        let key3 = CacheKey::new("What is SochDB?", "default", 54321);
        
        // Same query (case-insensitive) same hash
        assert_eq!(key1.query_hash, key2.query_hash);
        
        // Different AllowedSet = different key
        assert_ne!(key1.allowed_set_hash, key3.allowed_set_hash);
    }
    
    #[test]
    fn test_cosine_similarity() {
        let a = vec![1.0, 0.0, 0.0];
        let b = vec![1.0, 0.0, 0.0];
        let c = vec![0.0, 1.0, 0.0];
        let d = vec![0.707, 0.707, 0.0];
        
        assert!((cosine_similarity(&a, &b) - 1.0).abs() < 0.001);
        assert!((cosine_similarity(&a, &c) - 0.0).abs() < 0.001);
        assert!((cosine_similarity(&a, &d) - 0.707).abs() < 0.01);
    }
    
    #[test]
    fn test_hash_allowed_set() {
        let ids1: Vec<u64> = vec![1, 2, 3, 5, 8];
        let ids2: Vec<u64> = vec![8, 5, 3, 2, 1]; // Same set, different order
        let ids3: Vec<u64> = vec![1, 2, 3, 5, 9]; // Different set
        
        let hash1 = hash_allowed_set(ids1.iter());
        let hash2 = hash_allowed_set(ids2.iter());
        let hash3 = hash_allowed_set(ids3.iter());
        
        // Same set = same hash
        assert_eq!(hash1, hash2);
        
        // Different set = different hash
        assert_ne!(hash1, hash3);
    }
}