do-memory-storage-redb 0.1.31

redb embedded storage backend for do-memory-core episodic learning system (cache layer)
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
//! Integration tests for LRU cache with TTL expiration

use chrono::Utc;
use do_memory_core::{ComplexityLevel, Episode, TaskContext, TaskType};
use do_memory_storage_redb::{CacheConfig, RedbStorage};
use std::collections::HashMap;
use tempfile::tempdir;
use tokio::time::{Duration, sleep};
use uuid::Uuid;

/// Helper function to create a test episode
fn create_test_episode(id: Uuid) -> Episode {
    Episode {
        episode_id: id,
        task_type: TaskType::Testing,
        task_description: "Test task".to_string(),
        start_time: Utc::now(),
        end_time: None,
        context: TaskContext {
            language: Some("rust".to_string()),
            framework: None,
            complexity: ComplexityLevel::Moderate,
            domain: "testing".to_string(),
            tags: vec!["test".to_string()],
        },
        outcome: None,
        steps: vec![],
        patterns: vec![],
        heuristics: vec![],
        reflection: None,
        reward: None,
        applied_patterns: vec![],
        salient_features: None,
        metadata: HashMap::new(),
        tags: vec![],
        checkpoints: vec![],
    }
}

/// Helper to create storage with custom cache config
async fn create_storage_with_config(config: CacheConfig) -> RedbStorage {
    let dir = tempdir().expect("Failed to create temp directory for test");
    let db_path = dir.path().join("test.redb");
    RedbStorage::new_with_cache_config(&db_path, config)
        .await
        .expect("Failed to create storage with config")
}

#[tokio::test]
async fn test_cache_metrics_tracking() {
    let storage = create_storage_with_config(CacheConfig::default()).await;

    let id1 = Uuid::new_v4();
    let id2 = Uuid::new_v4();
    let episode1 = create_test_episode(id1);
    let episode2 = create_test_episode(id2);

    // Store two episodes
    storage.store_episode(&episode1).await.unwrap();
    storage.store_episode(&episode2).await.unwrap();

    // Get first episode (hit)
    let result = storage.get_episode(id1).await.unwrap();
    assert!(result.is_some());

    // Get non-existent episode (miss)
    let result = storage.get_episode(Uuid::new_v4()).await.unwrap();
    assert!(result.is_none());

    // Check metrics
    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.hits, 1);
    assert_eq!(metrics.misses, 2); // 2 stores only (misses on gets don't add to cache)
    assert_eq!(metrics.item_count, 2);
    assert_eq!(metrics.hit_rate, 0.3333333333333333); // 1/3
}

#[tokio::test]
async fn test_lru_eviction_on_full_cache() {
    let config = CacheConfig {
        max_size: 3,
        default_ttl_secs: 3600,
        cleanup_interval_secs: 300,
        enable_background_cleanup: false,
    };
    let storage = create_storage_with_config(config).await;

    let id1 = Uuid::new_v4();
    let id2 = Uuid::new_v4();
    let id3 = Uuid::new_v4();
    let id4 = Uuid::new_v4();

    // Fill cache to capacity
    storage
        .store_episode(&create_test_episode(id1))
        .await
        .unwrap();
    storage
        .store_episode(&create_test_episode(id2))
        .await
        .unwrap();
    storage
        .store_episode(&create_test_episode(id3))
        .await
        .unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 3);
    assert_eq!(metrics.evictions, 0);

    // Add one more - should evict id1 (least recently used)
    storage
        .store_episode(&create_test_episode(id4))
        .await
        .unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 3);
    assert_eq!(metrics.evictions, 1);

    // All episodes should still be retrievable from redb (not affected by cache eviction)
    assert!(storage.get_episode(id1).await.unwrap().is_some());
    assert!(storage.get_episode(id2).await.unwrap().is_some());
    assert!(storage.get_episode(id3).await.unwrap().is_some());
    assert!(storage.get_episode(id4).await.unwrap().is_some());
}

#[tokio::test]
async fn test_lru_order_updates_on_access() {
    let config = CacheConfig {
        max_size: 3,
        default_ttl_secs: 3600,
        cleanup_interval_secs: 300,
        enable_background_cleanup: false,
    };
    let storage = create_storage_with_config(config).await;

    let id1 = Uuid::new_v4();
    let id2 = Uuid::new_v4();
    let id3 = Uuid::new_v4();
    let id4 = Uuid::new_v4();

    // Fill cache
    storage
        .store_episode(&create_test_episode(id1))
        .await
        .unwrap();
    storage
        .store_episode(&create_test_episode(id2))
        .await
        .unwrap();
    storage
        .store_episode(&create_test_episode(id3))
        .await
        .unwrap();

    // Access id1, making it most recently used
    storage.get_episode(id1).await.unwrap();

    // Add id4 - should evict id2 (now least recently used)
    storage
        .store_episode(&create_test_episode(id4))
        .await
        .unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.evictions, 1);

    // Verify all can still be retrieved (from redb)
    assert!(storage.get_episode(id1).await.unwrap().is_some());
    assert!(storage.get_episode(id2).await.unwrap().is_some());
    assert!(storage.get_episode(id3).await.unwrap().is_some());
    assert!(storage.get_episode(id4).await.unwrap().is_some());
}

#[tokio::test]
async fn test_ttl_expiration_lazy_check() {
    let config = CacheConfig {
        max_size: 10,
        default_ttl_secs: 1, // 1 second TTL
        cleanup_interval_secs: 300,
        enable_background_cleanup: false,
    };
    let storage = create_storage_with_config(config).await;

    let id = Uuid::new_v4();
    storage
        .store_episode(&create_test_episode(id))
        .await
        .unwrap();

    // Episode should be in cache
    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 1);

    // Wait for expiration
    sleep(Duration::from_secs(2)).await;

    // Access should detect expiration and count as miss
    let result = storage.get_episode(id).await.unwrap();
    assert!(result.is_some()); // Still in redb

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.expirations, 1);
    assert_eq!(metrics.misses, 2); // 1 from store, 1 from expired access
}

#[tokio::test]
async fn test_manual_cache_cleanup() {
    let config = CacheConfig {
        max_size: 10,
        default_ttl_secs: 1,
        cleanup_interval_secs: 300,
        enable_background_cleanup: false,
    };
    let storage = create_storage_with_config(config).await;

    let id1 = Uuid::new_v4();
    let id2 = Uuid::new_v4();

    storage
        .store_episode(&create_test_episode(id1))
        .await
        .unwrap();
    storage
        .store_episode(&create_test_episode(id2))
        .await
        .unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 2);

    // Wait for expiration
    sleep(Duration::from_secs(2)).await;

    // Manually trigger cleanup
    let expired_count = storage.cleanup_cache().await;
    assert_eq!(expired_count, 2);

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 0);
    assert_eq!(metrics.expirations, 2);
}

#[tokio::test]
async fn test_background_cleanup_task() {
    let config = CacheConfig {
        max_size: 10,
        default_ttl_secs: 1,
        cleanup_interval_secs: 1,
        enable_background_cleanup: true,
    };
    let storage = create_storage_with_config(config).await;

    let id = Uuid::new_v4();
    storage
        .store_episode(&create_test_episode(id))
        .await
        .unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 1);

    // Wait for expiration and background cleanup
    sleep(Duration::from_secs(3)).await;

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 0);
    assert!(metrics.expirations > 0);
}

#[tokio::test]
async fn test_cache_clear() {
    let storage = create_storage_with_config(CacheConfig::default()).await;

    // Add multiple episodes
    for _ in 0..5 {
        let id = Uuid::new_v4();
        storage
            .store_episode(&create_test_episode(id))
            .await
            .unwrap();
    }

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 5);

    // Clear cache
    storage.clear_all().await.unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 0);
    assert_eq!(metrics.total_size_bytes, 0);
}

#[tokio::test]
async fn test_cache_delete_removes_tracking() {
    let storage = create_storage_with_config(CacheConfig::default()).await;

    let id = Uuid::new_v4();
    storage
        .store_episode(&create_test_episode(id))
        .await
        .unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 1);

    // Delete episode
    storage.delete_episode(id).await.unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 0);
}

#[tokio::test]
async fn test_cache_size_tracking() {
    let storage = create_storage_with_config(CacheConfig::default()).await;

    storage
        .store_episode(&create_test_episode(Uuid::new_v4()))
        .await
        .unwrap();
    storage
        .store_episode(&create_test_episode(Uuid::new_v4()))
        .await
        .unwrap();
    storage
        .store_episode(&create_test_episode(Uuid::new_v4()))
        .await
        .unwrap();

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 3);
    assert!(metrics.total_size_bytes > 0);
}

#[tokio::test]
async fn test_zero_ttl_no_expiration() {
    let config = CacheConfig {
        max_size: 10,
        default_ttl_secs: 0, // No TTL
        cleanup_interval_secs: 300,
        enable_background_cleanup: false,
    };
    let storage = create_storage_with_config(config).await;

    let id = Uuid::new_v4();
    storage
        .store_episode(&create_test_episode(id))
        .await
        .unwrap();

    // Wait a bit
    sleep(Duration::from_secs(2)).await;

    // Should still be valid
    let result = storage.get_episode(id).await.unwrap();
    assert!(result.is_some());

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.expirations, 0);
    assert_eq!(metrics.hits, 1);
}

#[tokio::test]
async fn test_concurrent_access() {
    let storage = create_storage_with_config(CacheConfig::default()).await;
    let storage = std::sync::Arc::new(storage);

    // Create multiple tasks that access the cache concurrently
    let mut handles = vec![];

    for _ in 0..10 {
        let storage_clone = std::sync::Arc::clone(&storage);
        let handle = tokio::spawn(async move {
            let id = Uuid::new_v4();
            storage_clone
                .store_episode(&create_test_episode(id))
                .await
                .unwrap();
            storage_clone.get_episode(id).await.unwrap();
        });
        handles.push(handle);
    }

    // Wait for all tasks to complete
    for handle in handles {
        handle.await.unwrap();
    }

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.item_count, 10);
    assert_eq!(metrics.hits, 10);
}

#[tokio::test]
async fn test_eviction_frees_space() {
    let config = CacheConfig {
        max_size: 2,
        default_ttl_secs: 3600,
        cleanup_interval_secs: 300,
        enable_background_cleanup: false,
    };
    let storage = create_storage_with_config(config).await;

    // Add 3 episodes, third should evict first
    storage
        .store_episode(&create_test_episode(Uuid::new_v4()))
        .await
        .unwrap();
    let initial_size = storage.get_cache_metrics().await.total_size_bytes;

    storage
        .store_episode(&create_test_episode(Uuid::new_v4()))
        .await
        .unwrap();
    let second_size = storage.get_cache_metrics().await.total_size_bytes;
    assert!(second_size > initial_size);

    storage
        .store_episode(&create_test_episode(Uuid::new_v4()))
        .await
        .unwrap();
    let third_size = storage.get_cache_metrics().await.total_size_bytes;

    // Size should be approximately 2x initial, not 3x (due to eviction)
    assert!(third_size < initial_size * 3);
    assert_eq!(storage.get_cache_metrics().await.item_count, 2);
}

#[tokio::test]
async fn test_hit_rate_calculation() {
    let storage = create_storage_with_config(CacheConfig::default()).await;

    let id = Uuid::new_v4();

    // 1 miss (store)
    storage
        .store_episode(&create_test_episode(id))
        .await
        .unwrap();

    // 4 hits
    for _ in 0..4 {
        storage.get_episode(id).await.unwrap();
    }

    let metrics = storage.get_cache_metrics().await;
    assert_eq!(metrics.hits, 4);
    assert_eq!(metrics.misses, 1);
    assert_eq!(metrics.hit_rate, 0.8); // 4/5
}