yantrikdb 0.23.0

Cognitive memory engine for persistent AI systems
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
use super::*;

// ── V4: Storage & Performance tests ──

#[test]
fn test_schema_v6_has_storage_tier() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    let rid = db
        .record(
            "tier test",
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            &vec_seed(1.0, 8),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();
    let mem = db.get(&rid).unwrap().unwrap();
    assert_eq!(mem.storage_tier, "hot");
}

#[test]
fn test_schema_v7_has_fts5_and_join_tables() {
    let db = YantrikDB::new(":memory:", 8).unwrap();

    // FTS5 virtual table exists — insert then search.
    // Must record BEFORE acquiring conn — db.record() internally takes
    // conn, so holding conn across record() would self-deadlock.
    let _rid = db
        .record(
            "The quick brown fox jumps over the lazy dog",
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            &vec_seed(1.0, 8),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();

    let conn = db.conn();

    let count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM memories_fts WHERE memories_fts MATCH 'quick brown'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(count, 1, "FTS5 should index inserted memory");

    // Join tables exist
    let _: i64 = conn
        .query_row("SELECT COUNT(*) FROM trigger_source_rids", [], |row| {
            row.get(0)
        })
        .unwrap();
    let _: i64 = conn
        .query_row("SELECT COUNT(*) FROM pattern_evidence", [], |row| {
            row.get(0)
        })
        .unwrap();
    let _: i64 = conn
        .query_row("SELECT COUNT(*) FROM pattern_entities", [], |row| {
            row.get(0)
        })
        .unwrap();

    // Schema version is current
    let ver: String = conn
        .query_row(
            "SELECT value FROM meta WHERE key = 'schema_version'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(ver, crate::schema::SCHEMA_VERSION.to_string());
}

#[test]
fn test_fts5_search_multiple_memories() {
    let db = YantrikDB::new(":memory:", 8).unwrap();

    db.record(
        "Alice loves Rust programming",
        "semantic",
        0.5,
        0.0,
        604800.0,
        &empty_meta(),
        &vec_seed(1.0, 8),
        "default",
        0.8,
        "general",
        "user",
        None,
    )
    .unwrap();
    db.record(
        "Bob prefers Python scripting",
        "semantic",
        0.5,
        0.0,
        604800.0,
        &empty_meta(),
        &vec_seed(0.5, 8),
        "default",
        0.8,
        "general",
        "user",
        None,
    )
    .unwrap();
    db.record(
        "Alice and Bob work on Rust projects",
        "episodic",
        0.5,
        0.0,
        604800.0,
        &empty_meta(),
        &vec_seed(0.3, 8),
        "default",
        0.8,
        "general",
        "user",
        None,
    )
    .unwrap();

    // Acquire conn AFTER records are written — db.record() internally takes
    // conn, and holding it across db.record() would self-deadlock (the
    // Mutex<Connection> is non-reentrant). See CONCURRENCY.md Rule 4.
    let conn = db.conn();

    // Search for "Rust" should match 2 memories
    let count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM memories_fts WHERE memories_fts MATCH 'rust'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(count, 2, "FTS5 should find 2 memories containing 'rust'");

    // Search for "Alice" should match 2 memories
    let count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM memories_fts WHERE memories_fts MATCH 'alice'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(count, 2, "FTS5 should find 2 memories containing 'alice'");

    // Search for "Python" should match 1
    let count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM memories_fts WHERE memories_fts MATCH 'python'",
            [],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(count, 1);
}

#[test]
fn test_archive_memory() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    let rid = db
        .record(
            "to archive",
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            &vec_seed(1.0, 8),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();

    // Archive
    assert!(db.archive(&rid).unwrap());
    let mem = db.get(&rid).unwrap().unwrap();
    assert_eq!(mem.storage_tier, "cold");

    // Verify removed from vec_memories (recall should not find it)
    let results = db
        .recall(
            &vec_seed(1.0, 8),
            10,
            None,
            None,
            false,
            false,
            None,
            true,
            None,
            None,
            None,
            None,
            None,
            false,
            None, // event_after (#149)
            None, // event_before (#149)
        )
        .unwrap();
    assert!(
        results.iter().all(|r| r.rid != rid),
        "archived memory should not appear in recall"
    );

    // Stats should show archived
    assert_eq!(db.stats(None).unwrap().archived_memories, 1);
}

#[test]
fn test_hydrate_memory() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    let emb = vec_seed(2.0, 8);
    let rid = db
        .record(
            "to hydrate",
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            &emb,
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();

    // Archive then hydrate
    db.archive(&rid).unwrap();
    assert!(db.hydrate(&rid).unwrap());
    let mem = db.get(&rid).unwrap().unwrap();
    assert_eq!(mem.storage_tier, "hot");

    // Should be back in recall
    let results = db
        .recall(
            &emb, 10, None, None, false, false, None, true, None, None, None, None, None, false,
            None, // event_after (#149)
            None, // event_before (#149)
        )
        .unwrap();
    assert!(
        results.iter().any(|r| r.rid == rid),
        "hydrated memory should appear in recall"
    );

    // Stats
    assert_eq!(db.stats(None).unwrap().archived_memories, 0);
}

#[test]
fn test_archive_idempotent() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    let rid = db
        .record(
            "idempotent",
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            &vec_seed(1.0, 8),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();

    assert!(db.archive(&rid).unwrap());
    assert!(!db.archive(&rid).unwrap()); // Already cold
}

#[test]
fn test_record_batch() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    let inputs: Vec<RecordInput> = (0..10)
        .map(|i| RecordInput {
            created_at: None,
            idempotency_key: None,
            text: format!("batch memory {i}"),
            memory_type: "episodic".to_string(),
            importance: 0.5,
            valence: 0.0,
            half_life: 604800.0,
            metadata: serde_json::json!({}),
            embedding: vec_seed(i as f32, 8),
            namespace: "default".to_string(),
            certainty: 0.8,
            domain: "general".to_string(),
            source: "user".to_string(),
            emotional_state: None,
        })
        .collect();

    let rids = db.record_batch(&inputs).unwrap();
    assert_eq!(rids.len(), 10);

    // All retrievable
    for rid in &rids {
        assert!(db.get(rid).unwrap().is_some());
    }
    assert_eq!(db.stats(None).unwrap().active_memories, 10);
}

#[test]
fn test_record_batch_empty() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    let rids = db.record_batch(&[]).unwrap();
    assert!(rids.is_empty());
}

#[test]
fn test_evict() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    // Seed 20 memories
    for i in 0..20 {
        db.record(
            &format!("evict mem {i}"),
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            &vec_seed(i as f32, 8),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();
    }
    assert_eq!(db.stats(None).unwrap().active_memories, 20);

    // Evict to keep 10
    let archived = db.evict(10).unwrap();
    assert_eq!(archived.len(), 10);

    let stats = db.stats(None).unwrap();
    assert_eq!(stats.archived_memories, 10);

    // Recall should only find hot memories
    let results = db
        .recall(
            &vec_seed(0.0, 8),
            20,
            None,
            None,
            false,
            false,
            None,
            true,
            None,
            None,
            None,
            None,
            None,
            false,
            None, // event_after (#149)
            None, // event_before (#149)
        )
        .unwrap();
    for r in &results {
        assert!(
            !archived.contains(&r.rid),
            "evicted memory should not be in recall"
        );
    }
}

#[test]
fn test_evict_no_action_when_under_limit() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    for i in 0..5 {
        db.record(
            &format!("small db {i}"),
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            &vec_seed(i as f32, 8),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();
    }
    let archived = db.evict(10).unwrap();
    assert!(archived.is_empty());
}

#[test]
fn test_query_builder_basic() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    for i in 0..10 {
        db.record(
            &format!("memory {i}"),
            "episodic",
            0.5,
            0.0,
            604800.0,
            &empty_meta(),
            &vec_seed(i as f32, 8),
            "default",
            0.8,
            "general",
            "user",
            None,
        )
        .unwrap();
    }

    let results = db
        .query(RecallQuery::new(vec_seed(0.0, 8)).top_k(3).skip_reinforce())
        .unwrap();
    assert_eq!(results.len(), 3);
}

#[test]
fn test_query_builder_with_filters() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    db.record(
        "episodic one",
        "episodic",
        0.5,
        0.0,
        604800.0,
        &empty_meta(),
        &vec_seed(1.0, 8),
        "work",
        0.8,
        "general",
        "user",
        None,
    )
    .unwrap();
    db.record(
        "semantic one",
        "semantic",
        0.5,
        0.0,
        604800.0,
        &empty_meta(),
        &vec_seed(2.0, 8),
        "work",
        0.8,
        "general",
        "user",
        None,
    )
    .unwrap();
    db.record(
        "episodic two",
        "episodic",
        0.5,
        0.0,
        604800.0,
        &empty_meta(),
        &vec_seed(3.0, 8),
        "personal",
        0.8,
        "general",
        "user",
        None,
    )
    .unwrap();

    // Filter by type + namespace
    let results = db
        .query(
            RecallQuery::new(vec_seed(1.0, 8))
                .top_k(10)
                .memory_type("episodic")
                .namespace("work")
                .skip_reinforce(),
        )
        .unwrap();
    assert_eq!(results.len(), 1);
    assert_eq!(results[0].memory_type, "episodic");
    assert_eq!(results[0].namespace, "work");
}

#[test]
fn test_query_builder_contributions_present() {
    let db = YantrikDB::new(":memory:", 8).unwrap();
    db.record(
        "test mem",
        "episodic",
        0.8,
        0.5,
        604800.0,
        &empty_meta(),
        &vec_seed(1.0, 8),
        "default",
        0.8,
        "general",
        "user",
        None,
    )
    .unwrap();

    let results = db
        .query(RecallQuery::new(vec_seed(1.0, 8)).top_k(1).skip_reinforce())
        .unwrap();
    assert_eq!(results.len(), 1);

    let r = &results[0];
    // Verify explainability fields
    assert!(r.scores.valence_multiplier >= 1.0);
    assert!(r.scores.contributions.similarity >= 0.0);
    assert!(r.scores.contributions.decay >= 0.0);
    assert!(r.scores.contributions.recency >= 0.0);
    assert!(r.scores.contributions.importance >= 0.0);
}