leankg 0.19.10

Lightweight Knowledge Graph for AI-Assisted Development
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
use crate::db::schema::CozoDb;
use serde::{de::DeserializeOwned, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;

/// Maximum number of entries in the persistent cache to prevent unbounded growth
const MAX_CACHE_ENTRIES: usize = 10_000;
/// Evict when approaching max entries
const EVICTION_THRESHOLD: f64 = 0.9;

#[derive(Clone)]
struct CacheEntry {
    value_json: String,
    created_at: i64,
    ttl_seconds: i64,
}

impl CacheEntry {
    fn is_expired(&self) -> bool {
        if self.ttl_seconds == 0 {
            return true;
        }
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);
        (now - self.created_at) > self.ttl_seconds
    }
}

#[derive(Clone)]
pub struct PersistentCache {
    db: Arc<CozoDb>,
    memory: Arc<RwLock<HashMap<String, CacheEntry>>>,
    default_ttl: u64,
    /// If true, only use memory storage (no DB persistence)
    /// Useful for reducing memory footprint when persistence isn't needed
    memory_only: bool,
    /// Track entry count for size-based eviction
    entry_count: Arc<std::sync::atomic::AtomicUsize>,
}

impl PersistentCache {
    pub fn new(db: Arc<CozoDb>, default_ttl: u64) -> Self {
        Self {
            db,
            memory: Arc::new(RwLock::new(HashMap::new())),
            default_ttl,
            memory_only: false,
            entry_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        }
    }

    /// Create a memory-only cache that doesn't duplicate storage in SQLite
    /// Reduces memory footprint by ~50% for transient caches
    pub fn memory_only(db: Arc<CozoDb>, default_ttl: u64) -> Self {
        Self {
            db,
            memory: Arc::new(RwLock::new(HashMap::new())),
            default_ttl,
            memory_only: true,
            entry_count: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
        }
    }

    pub fn with_ttl(db: Arc<CozoDb>, ttl_secs: u64) -> Self {
        Self::new(db, ttl_secs)
    }

    pub async fn get<V: DeserializeOwned>(&self, key: &str) -> Option<V> {
        if let Some(entry) = self.memory.read().await.get(key) {
            if !entry.is_expired() {
                return serde_json::from_str(&entry.value_json).ok();
            }
        }

        if let Some(value_json) = self.load_from_db(key).await {
            if let Ok(v) = serde_json::from_str::<V>(&value_json) {
                let now = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .map(|d| d.as_secs() as i64)
                    .unwrap_or(0);
                self.memory.write().await.insert(
                    key.to_string(),
                    CacheEntry {
                        value_json: value_json.clone(),
                        created_at: now,
                        ttl_seconds: self.default_ttl as i64,
                    },
                );
                return Some(v);
            }
        }
        None
    }

    #[allow(clippy::extra_unused_type_parameters)]
    pub async fn insert<K: Serialize, V: Serialize>(&self, key: String, value: V) {
        // Evict old entries if we're approaching the max
        self.evict_if_needed().await;

        let value_json = serde_json::to_string(&value).unwrap_or_default();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);

        let was_new = {
            let mut memory = self.memory.write().await;
            let existed = memory.contains_key(&key);
            memory.insert(
                key.clone(),
                CacheEntry {
                    value_json: value_json.clone(),
                    created_at: now,
                    ttl_seconds: self.default_ttl as i64,
                },
            );
            !existed
        };

        // Update entry count (only on new entries)
        if was_new {
            self.entry_count
                .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        }

        // Skip DB persistence if memory_only mode is enabled
        if !self.memory_only {
            self.save_to_db(&key, &value_json, now).await.ok();
        }
    }

    /// Evict oldest expired entries when approaching max capacity
    async fn evict_if_needed(&self) {
        let current = self.entry_count.load(std::sync::atomic::Ordering::Relaxed);
        let threshold = (MAX_CACHE_ENTRIES as f64 * EVICTION_THRESHOLD) as usize;

        if current >= threshold {
            self.evict_oldest_expired(current - threshold + 100).await;
        }
    }

    /// Evict the oldest entries (both expired in memory and from DB)
    async fn evict_oldest_expired(&self, count: usize) {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs() as i64)
            .unwrap_or(0);

        // First, evict expired entries from memory
        {
            let mut memory = self.memory.write().await;
            memory.retain(|_, entry| {
                entry.ttl_seconds > 0 && (now - entry.created_at) <= entry.ttl_seconds
            });
        }

        // Evict oldest entries from DB using a batch delete
        if !self.memory_only {
            self.evict_from_db(count).await.ok();
        }

        // Recount and update
        let memory_count = self.memory.read().await.len();
        self.entry_count
            .store(memory_count, std::sync::atomic::Ordering::Relaxed);
    }

    async fn evict_from_db(
        &self,
        count: usize,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        // Get oldest entries from DB and delete them
        let query = r#"
            :delete query_cache
            where cache_key in (
                select cache_key from query_cache
                order by created_at asc
                limit $count
            )
        "#;
        let mut params = std::collections::BTreeMap::new();
        params.insert("count".to_string(), serde_json::Value::Number(count.into()));
        crate::db::schema::run_script(&self.db, query, params)?;
        Ok(())
    }

    pub async fn invalidate(&self, key: &str) {
        let existed = self.memory.write().await.remove(key).is_some();
        if existed {
            self.entry_count
                .fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
        }
        self.delete_from_db(key).await.ok();
    }

    pub async fn invalidate_prefix(&self, prefix: &str) {
        let prefix_owned = prefix.to_string();
        let keys: Vec<String> = self
            .memory
            .read()
            .await
            .keys()
            .filter(|k| k.starts_with(&prefix_owned))
            .cloned()
            .collect();
        let count = keys.len();

        for key in keys {
            self.invalidate(&key).await;
        }
        if count > 0 {
            self.entry_count
                .fetch_sub(count, std::sync::atomic::Ordering::Relaxed);
        }
    }

    async fn load_from_db(&self, key: &str) -> Option<String> {
        let query = r#"
            ?[value_json, created_at, ttl_seconds] := 
                *query_cache[cache_key = $key, value_json, created_at, ttl_seconds]
        "#;
        let mut params = std::collections::BTreeMap::new();
        params.insert(
            "key".to_string(),
            serde_json::Value::String(key.to_string()),
        );

        let result = crate::db::schema::run_script(&self.db, query, params).ok()?;

        let row = result.rows.first()?;
        let created_at = row.get(1)?.get_int()?;
        let ttl_seconds = row.get(2)?.get_int()?;

        if ttl_seconds > 0 {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map(|d| d.as_secs() as i64)
                .unwrap_or(0);
            if (now - created_at) > ttl_seconds {
                self.delete_from_db(key).await.ok();
                return None;
            }
        }

        row.first()?.get_str().map(String::from)
    }

    async fn save_to_db(
        &self,
        key: &str,
        value_json: &str,
        created_at: i64,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let query = r#"
            ?[cache_key, value_json, created_at, ttl_seconds, tool_name, project_path, metadata] 
            <- [[ $key, $value_json, $created_at, $ttl_seconds, "unknown", "default", "{}" ]]
            :put query_cache { cache_key, value_json, created_at, ttl_seconds, tool_name, project_path, metadata }
        "#;
        let mut params = std::collections::BTreeMap::new();
        params.insert(
            "key".to_string(),
            serde_json::Value::String(key.to_string()),
        );
        params.insert(
            "value_json".to_string(),
            serde_json::Value::String(value_json.to_string()),
        );
        params.insert(
            "created_at".to_string(),
            serde_json::Value::Number(created_at.into()),
        );
        params.insert(
            "ttl_seconds".to_string(),
            serde_json::Value::Number((self.default_ttl as i64).into()),
        );

        crate::db::schema::run_script(&self.db, query, params)?;
        Ok(())
    }

    async fn delete_from_db(
        &self,
        key: &str,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let query = r#":delete query_cache where cache_key = $key"#;
        let mut params = std::collections::BTreeMap::new();
        params.insert(
            "key".to_string(),
            serde_json::Value::String(key.to_string()),
        );
        crate::db::schema::run_script(&self.db, query, params)?;
        Ok(())
    }

    pub async fn len(&self) -> usize {
        self.memory.read().await.len()
    }

    pub async fn is_empty(&self) -> bool {
        self.memory.read().await.is_empty()
    }

    /// Get approximate cache size (for monitoring)
    pub async fn size(&self) -> usize {
        self.entry_count.load(std::sync::atomic::Ordering::Relaxed)
    }

    /// Prune all expired entries and enforce max size limit
    pub async fn prune(&self) -> usize {
        let before = self.entry_count.load(std::sync::atomic::Ordering::Relaxed);
        self.evict_oldest_expired(MAX_CACHE_ENTRIES / 2).await;
        let after = self.entry_count.load(std::sync::atomic::Ordering::Relaxed);
        before - after
    }

    /// Get database size in bytes (approximate, for monitoring)
    pub fn database_size_approx(&self) -> Option<u64> {
        crate::db::schema::run_script(&self.db, "PRAGMA page_count", Default::default())
            .ok()
            .and_then(|result| {
                result
                    .rows
                    .first()
                    .and_then(|row| row.first()?.get_int().map(|pages| (pages as u64) * 4096))
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::Duration;

    static TEST_DB_COUNTER: AtomicU64 = AtomicU64::new(0);

    fn create_test_db() -> CozoDb {
        let counter = TEST_DB_COUNTER.fetch_add(1, Ordering::SeqCst);
        let temp_dir = std::env::temp_dir();
        let db_path = temp_dir.join(format!("leankg_test_persistent_cache_{}.db", counter));
        let db = crate::db::schema::init_db(&db_path).unwrap();
        drop(db);
        std::fs::remove_file(&db_path).ok();
        crate::db::schema::init_db(&db_path).unwrap()
    }

    #[tokio::test]
    async fn test_persistent_cache_basic() {
        let db = Arc::new(create_test_db());
        let cache = PersistentCache::new(db, 300);

        cache
            .insert::<String, Vec<String>>(
                "test_key".to_string(),
                vec!["value1".to_string(), "value2".to_string()],
            )
            .await;

        let result: Option<Vec<String>> = cache.get("test_key").await;
        assert!(result.is_some());
        let values = result.unwrap();
        assert_eq!(values.len(), 2);
        assert_eq!(values[0], "value1");
    }

    #[tokio::test]
    async fn test_persistent_cache_expired() {
        let db = Arc::new(create_test_db());
        let cache = PersistentCache::new(db, 0);

        cache
            .insert::<String, Vec<String>>("expired_key".to_string(), vec!["value".to_string()])
            .await;

        tokio::time::sleep(Duration::from_millis(10)).await;

        let result: Option<Vec<String>> = cache.get("expired_key").await;
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_persistent_cache_invalidate_prefix() {
        let db = Arc::new(create_test_db());
        let cache = PersistentCache::new(db, 300);

        cache
            .insert::<String, Vec<String>>(
                "deps:src/main.rs".to_string(),
                vec!["lib.rs".to_string()],
            )
            .await;
        cache
            .insert::<String, Vec<String>>(
                "deps:src/lib.rs".to_string(),
                vec!["mod.rs".to_string()],
            )
            .await;
        cache
            .insert::<String, String>(
                "orch:context:src/main.rs".to_string(),
                "content".to_string(),
            )
            .await;

        cache.invalidate_prefix("deps:src/").await;

        let result1: Option<Vec<String>> = cache.get("deps:src/main.rs").await;
        assert!(result1.is_none());

        let result2: Option<Vec<String>> = cache.get("deps:src/lib.rs").await;
        assert!(result2.is_none());

        let result3: Option<String> = cache.get("orch:context:src/main.rs").await;
        assert!(result3.is_some());
    }

    #[tokio::test]
    async fn test_persistent_cache_invalidate() {
        let db = Arc::new(create_test_db());
        let cache = PersistentCache::new(db, 300);

        cache
            .insert::<String, Vec<String>>("key1".to_string(), vec!["value1".to_string()])
            .await;

        cache.invalidate("key1").await;

        let result: Option<Vec<String>> = cache.get("key1").await;
        assert!(result.is_none());
    }
}