velesdb-core 5.0.0

High-performance vector database engine written in Rust
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
//! Unit tests for SemanticMemory (EPIC-010/US-002).

#[cfg(test)]
mod tests {
    use super::super::error::AgentMemoryError;
    use super::super::semantic_memory::SemanticMemory;
    use super::super::ttl::{MemoryKind, MemoryTtl};
    use crate::Database;
    use std::collections::HashSet;
    use std::sync::Arc;
    use tempfile::tempdir;

    fn make_semantic(db: Arc<Database>) -> SemanticMemory {
        SemanticMemory::new(db, 4, Arc::new(MemoryTtl::new())).expect("SemanticMemory::new failed")
    }

    // ── Basic API ──────────────────────────────────────────────────────────────

    #[test]
    fn test_collection_name_prefixed() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        assert!(sm.collection_name().starts_with("_semantic"));
    }

    #[test]
    fn test_dimension_accessor() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        assert_eq!(sm.dimension(), 4);
    }

    // ── store() / query() ─────────────────────────────────────────────────────

    #[test]
    fn test_store_and_query_returns_fact() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "Paris is the capital of France", &emb).unwrap();

        let results = sm.query(&emb, 1).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, 1);
        assert!(results[0].2.contains("Paris"));
    }

    #[test]
    fn test_query_ranks_similar_first() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb_target = vec![1.0_f32, 0.0, 0.0, 0.0];
        let emb_other = vec![0.0_f32, 1.0, 0.0, 0.0];
        sm.store(1, "target fact", &emb_target).unwrap();
        sm.store(2, "unrelated fact", &emb_other).unwrap();

        let results = sm.query(&emb_target, 2).unwrap();
        assert!(!results.is_empty());
        assert_eq!(results[0].0, 1, "most similar fact must rank first");
    }

    #[test]
    fn test_store_upserts_existing_id() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "original content", &emb).unwrap();
        sm.store(1, "updated content", &emb).unwrap();

        let results = sm.query(&emb, 1).unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].2.contains("updated"));
    }

    // ── delete() ──────────────────────────────────────────────────────────────

    #[test]
    fn test_delete_removes_fact() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "to delete", &emb).unwrap();
        sm.delete(1).unwrap();

        let results = sm.query(&emb, 5).unwrap();
        assert!(results.iter().all(|r| r.0 != 1));
    }

    // ── Dimension validation ───────────────────────────────────────────────────

    #[test]
    fn test_store_dimension_mismatch_rejected() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db)); // dim = 4

        let bad_emb = vec![1.0_f32, 0.0]; // dim = 2
        let result = sm.store(1, "bad", &bad_emb);
        assert!(result.is_err());
    }

    #[test]
    fn test_query_dimension_mismatch_rejected() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db)); // dim = 4

        let bad_query = vec![0.5_f32]; // dim = 1
        let result = sm.query(&bad_query, 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_new_detects_dimension_mismatch_on_existing_collection() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());

        let _sm = SemanticMemory::new_from_db(Arc::clone(&db), 4).unwrap();

        let result = SemanticMemory::new_from_db(Arc::clone(&db), 8);
        assert!(result.is_err());
    }

    // ── TTL ───────────────────────────────────────────────────────────────────

    #[test]
    fn test_ttl_zero_expires_immediately() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store_with_ttl(99, "short-lived fact", &emb, 0).unwrap();

        let results = sm.query(&emb, 5).unwrap();
        assert!(
            results.iter().all(|r| r.0 != 99),
            "TTL-0 fact must not appear in query results"
        );
    }

    #[test]
    fn test_store_with_positive_ttl_still_visible() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store_with_ttl(5, "long-lived fact", &emb, 9_999)
            .unwrap();

        let results = sm.query(&emb, 5).unwrap();
        assert!(
            results.iter().any(|r| r.0 == 5),
            "fact with future TTL must appear in query results"
        );
    }

    // ── Serialize / Deserialize ────────────────────────────────────────────────

    #[test]
    fn test_serialize_deserialize_roundtrip() {
        let dir1 = tempdir().unwrap();
        let db1 = Arc::new(Database::open(dir1.path()).unwrap());
        let sm1 = make_semantic(Arc::clone(&db1));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm1.store(10, "fact to persist", &emb).unwrap();
        sm1.store(11, "another fact", &emb).unwrap();
        let bytes = sm1.serialize().unwrap();

        // Restore into a fresh collection on a different database.
        let dir2 = tempdir().unwrap();
        let db2 = Arc::new(Database::open(dir2.path()).unwrap());
        let sm2 = make_semantic(Arc::clone(&db2));
        sm2.deserialize(&bytes).unwrap();

        let results = sm2.query(&emb, 5).unwrap();
        assert_eq!(results.len(), 2);
        let ids: Vec<u64> = results.iter().map(|r| r.0).collect();
        assert!(ids.contains(&10));
        assert!(ids.contains(&11));
    }

    #[test]
    fn test_deserialize_empty_bytes_is_noop() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "existing fact", &emb).unwrap();

        sm.deserialize(&[]).unwrap(); // must not error or wipe data

        let results = sm.query(&emb, 5).unwrap();
        assert_eq!(results.len(), 1);
    }

    // ── #1040: expired top-k point must not shrink results below k ──────────────

    #[test]
    fn test_expired_topk_point_freed_slot_filled_by_live_point() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        // Shared TTL so we can mark an already-persisted live point as expired
        // without physically deleting it (the bug shape: expired-but-present).
        let ttl = Arc::new(MemoryTtl::new());
        let sm = SemanticMemory::new(Arc::clone(&db), 4, Arc::clone(&ttl)).unwrap();

        let q = vec![1.0_f32, 0.0, 0.0, 0.0];
        let near = vec![0.99_f32, 0.14, 0.0, 0.0];
        // id=1 is the absolute best match and physically present, but expired.
        sm.store(1, "expired best match", &q).unwrap();
        // Keyed by the semantic namespace so the subsystem observes the expiry.
        ttl.set_ttl(MemoryKind::Semantic, 1, 0); // expires immediately, point still persisted
        sm.store(2, "live runner up", &near).unwrap();

        // Asking for k=1 must still return the live point, not an empty result.
        let results = sm.query(&q, 1).unwrap();
        assert_eq!(
            results.len(),
            1,
            "live point must fill the slot freed by the expired top-k point"
        );
        assert_eq!(results[0].0, 2);
    }

    // ── #1043(a): TTL-bearing serialize roundtrip ───────────────────────────────

    #[test]
    fn test_serialize_omits_ttl_facts_survive_roundtrip() {
        let dir1 = tempdir().unwrap();
        let db1 = Arc::new(Database::open(dir1.path()).unwrap());
        let ttl = Arc::new(MemoryTtl::new());
        let sm1 = SemanticMemory::new(Arc::clone(&db1), 4, Arc::clone(&ttl)).unwrap();

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm1.store_with_ttl(10, "fact with ttl", &emb, 9_999)
            .unwrap();
        assert!(
            ttl.get(MemoryKind::Semantic, 10).is_some(),
            "TTL entry tracked before serialize"
        );

        let bytes = sm1.serialize().unwrap();

        // Restore into a fresh subsystem with an independent TTL map.
        let dir2 = tempdir().unwrap();
        let db2 = Arc::new(Database::open(dir2.path()).unwrap());
        let ttl2 = Arc::new(MemoryTtl::new());
        let sm2 = SemanticMemory::new(Arc::clone(&db2), 4, Arc::clone(&ttl2)).unwrap();
        sm2.deserialize(&bytes).unwrap();

        // The fact survives the per-subsystem roundtrip.
        let results = sm2.query(&emb, 5).unwrap();
        assert!(results.iter().any(|r| r.0 == 10));
        // Documented limitation: TTL is NOT carried by per-subsystem serialize.
        assert!(
            ttl2.get(MemoryKind::Semantic, 10).is_none(),
            "per-subsystem serialize intentionally omits TTL state"
        );
    }

    // ── #1043(b): ttl=0 physical removal ────────────────────────────────────────

    #[test]
    fn test_store_with_ttl_zero_does_not_persist_point() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store_with_ttl(7, "ephemeral", &emb, 0).unwrap();

        // Not tracked and not physically present.
        assert_eq!(sm.count(), 0);
        assert!(sm.get(7).unwrap().is_none());
    }

    #[test]
    fn test_store_with_ttl_zero_evicts_preexisting_point() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(7, "live", &emb).unwrap();
        assert_eq!(sm.count(), 1);

        // ttl=0 over an existing id removes it physically.
        sm.store_with_ttl(7, "replace-then-expire", &emb, 0)
            .unwrap();
        assert_eq!(sm.count(), 0);
        assert!(sm.get(7).unwrap().is_none());
    }

    #[test]
    fn test_store_with_ttl_zero_dimension_mismatch_rejected() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let bad = vec![1.0_f32]; // dim = 1, expected 4
        assert!(sm.store_with_ttl(1, "bad", &bad, 0).is_err());
    }

    // ── #1044: list_all / get / count / is_empty / clear / store_batch ──────────

    #[test]
    fn test_count_and_is_empty() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        assert!(sm.is_empty());
        assert_eq!(sm.count(), 0);

        sm.store(1, "a", &[1.0, 0.0, 0.0, 0.0]).unwrap();
        assert!(!sm.is_empty());
        assert_eq!(sm.count(), 1);
    }

    #[test]
    fn test_get_returns_content_and_embedding() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![0.0_f32, 1.0, 0.0, 0.0];
        sm.store(3, "hello", &emb).unwrap();

        let (content, vector) = sm.get(3).unwrap().expect("fact present");
        assert_eq!(content, "hello");
        assert_eq!(vector, emb);
        assert!(sm.get(404).unwrap().is_none());
    }

    #[test]
    fn test_get_metadata_returns_payload_excluding_none_for_unknown() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let mut meta = serde_json::Map::new();
        meta.insert("tag".to_string(), serde_json::json!("science"));
        sm.store_with_metadata(1, "Photosynthesis", &emb, &meta)
            .unwrap();

        let payload = sm.get_metadata(1).unwrap().expect("payload present");
        assert_eq!(payload.get("tag"), Some(&serde_json::json!("science")));
        assert!(sm.get_metadata(404).unwrap().is_none());
    }

    #[test]
    fn test_get_metadata_bare_store_has_no_extra_fields() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        sm.store(1, "no metadata here", &[1.0, 0.0, 0.0, 0.0])
            .unwrap();

        // `store()` still writes a payload (the reserved `content` key), so the
        // map is Some, just without any caller-supplied field.
        let payload = sm.get_metadata(1).unwrap().expect("payload present");
        assert!(!payload.contains_key("tag"));
    }

    #[test]
    fn test_get_metadata_batch_matches_individual_calls_order_and_length() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let mut tagged = serde_json::Map::new();
        tagged.insert("tag".to_string(), serde_json::json!("science"));
        sm.store_with_metadata(1, "photosynthesis", &[1.0, 0.0, 0.0, 0.0], &tagged)
            .unwrap();
        sm.store(2, "no metadata here", &[0.0, 1.0, 0.0, 0.0])
            .unwrap();

        let batch = sm.get_metadata_batch(&[1, 2, 404]).unwrap();
        assert_eq!(batch.len(), 3, "one result per input id, in order");
        assert_eq!(
            batch[0].as_ref().and_then(|m| m.get("tag")),
            Some(&serde_json::json!("science"))
        );
        assert!(!batch[1].as_ref().unwrap().contains_key("tag"));
        assert!(batch[2].is_none(), "unknown id maps to None, not an error");
    }

    #[test]
    fn test_get_metadata_batch_handles_a_gap_among_present_ids() {
        // `store_with_ttl(id, .., 0)` deletes on the spot (see
        // `test_store_with_ttl_zero_does_not_persist_point`), so id 1 here is
        // absent from storage entirely by the time the batch runs — the same
        // "missing id in the middle of the batch" shape a real expired-TTL
        // gap would produce, without needing a real-time sleep to test it.
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        sm.store_with_ttl(1, "never actually persisted", &[1.0, 0.0, 0.0, 0.0], 0)
            .unwrap();
        sm.store(2, "live", &[0.0, 1.0, 0.0, 0.0]).unwrap();

        let batch = sm.get_metadata_batch(&[1, 2]).unwrap();
        assert!(batch[0].is_none());
        assert!(batch[1].is_some());
    }

    #[test]
    fn test_get_metadata_batch_excludes_a_durably_expired_id() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        sm.store(1, "will expire", &[1.0, 0.0, 0.0, 0.0]).unwrap();
        sm.set_ttl_durable(1, 0).unwrap();
        sm.store(2, "live", &[0.0, 1.0, 0.0, 0.0]).unwrap();

        let batch = sm.get_metadata_batch(&[1, 2]).unwrap();
        assert!(
            batch[0].is_none(),
            "durably-expired id must not surface metadata"
        );
        assert!(batch[1].is_some());
    }

    #[test]
    fn test_list_all_returns_live_facts() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        sm.store(1, "first", &[1.0, 0.0, 0.0, 0.0]).unwrap();
        sm.store(2, "second", &[0.0, 1.0, 0.0, 0.0]).unwrap();

        let mut listed = sm.list_all().unwrap();
        listed.sort_by_key(|(id, _)| *id);
        assert_eq!(
            listed,
            vec![(1, "first".to_string()), (2, "second".to_string())]
        );
    }

    #[test]
    fn test_clear_removes_all_facts() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        sm.store(1, "a", &[1.0, 0.0, 0.0, 0.0]).unwrap();
        sm.store(2, "b", &[0.0, 1.0, 0.0, 0.0]).unwrap();
        sm.clear().unwrap();

        assert!(sm.is_empty());
        assert!(sm.list_all().unwrap().is_empty());
    }

    #[test]
    fn test_store_batch_inserts_all() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let e1 = vec![1.0_f32, 0.0, 0.0, 0.0];
        let e2 = vec![0.0_f32, 1.0, 0.0, 0.0];
        let facts: Vec<(u64, &str, &[f32])> =
            vec![(1, "one", e1.as_slice()), (2, "two", e2.as_slice())];
        sm.store_batch(&facts).unwrap();

        assert_eq!(sm.count(), 2);
        assert_eq!(sm.get(1).unwrap().unwrap().0, "one");
        assert_eq!(sm.get(2).unwrap().unwrap().0, "two");
    }

    #[test]
    fn test_store_batch_rejects_dimension_mismatch() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let good = vec![1.0_f32, 0.0, 0.0, 0.0];
        let bad = vec![1.0_f32]; // wrong dim
        let facts: Vec<(u64, &str, &[f32])> =
            vec![(1, "ok", good.as_slice()), (2, "bad", bad.as_slice())];
        assert!(sm.store_batch(&facts).is_err());
    }

    // ── #1044: store_with_metadata / update_metadata / query_filtered ───────────

    #[test]
    fn test_store_with_metadata_persists_extra_fields() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let mut meta = serde_json::Map::new();
        meta.insert("tag".to_string(), serde_json::json!("science"));
        sm.store_with_metadata(1, "Photosynthesis", &emb, &meta)
            .unwrap();

        let results = sm.query(&emb, 1).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, 1);
        // content field still set correctly
        assert!(results[0].2.contains("Photosynthesis"));
    }

    #[test]
    fn test_store_with_metadata_content_wins_on_collision() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let mut meta = serde_json::Map::new();
        // caller tries to inject a different content via metadata
        meta.insert(
            "content".to_string(),
            serde_json::json!("should be overwritten"),
        );
        sm.store_with_metadata(1, "canonical content", &emb, &meta)
            .unwrap();

        let results = sm.query(&emb, 1).unwrap();
        assert_eq!(results[0].2, "canonical content", "content param must win");
    }

    #[test]
    fn test_update_metadata_merges_fields() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "original", &emb).unwrap();

        let mut updates = serde_json::Map::new();
        updates.insert("tag".to_string(), serde_json::json!("updated"));
        sm.update_metadata(1, &updates).unwrap();

        // content field must still be present after update
        let results = sm.query(&emb, 1).unwrap();
        assert_eq!(results.len(), 1);
        assert!(results[0].2.contains("original"));
    }

    #[test]
    fn test_update_metadata_unknown_id_errors() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let updates = serde_json::Map::new();
        assert!(
            sm.update_metadata(9999, &updates).is_err(),
            "unknown id must return NotFound"
        );
    }

    #[test]
    fn test_update_metadata_expired_id_errors() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let ttl = Arc::new(super::super::ttl::MemoryTtl::new());
        let sm = SemanticMemory::new(Arc::clone(&db), 4, Arc::clone(&ttl)).expect("init failed");

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "fact", &emb).unwrap();
        ttl.set_ttl(MemoryKind::Semantic, 1, 0); // immediate expiry

        let updates = serde_json::Map::new();
        assert!(
            sm.update_metadata(1, &updates).is_err(),
            "expired id must return NotFound"
        );
    }

    #[test]
    fn test_query_filtered_matches_tag() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let mut meta_a = serde_json::Map::new();
        meta_a.insert("category".to_string(), serde_json::json!("physics"));
        let mut meta_b = serde_json::Map::new();
        meta_b.insert("category".to_string(), serde_json::json!("biology"));

        sm.store_with_metadata(1, "gravity", &emb, &meta_a).unwrap();
        sm.store_with_metadata(2, "photosynthesis", &emb, &meta_b)
            .unwrap();

        let mut filter = serde_json::Map::new();
        filter.insert("category".to_string(), serde_json::json!("physics"));

        let results = sm.query_filtered(&emb, 5, &filter, 0).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, 1);
    }

    #[test]
    fn test_ensure_index_creates_and_is_idempotent() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let mut meta = serde_json::Map::new();
        meta.insert("project".to_string(), serde_json::json!("veles"));
        sm.store_with_metadata(1, "auth bug", &emb, &meta).unwrap();

        let collection = db
            .get_vector_collection(sm.collection_name())
            .expect("semantic collection exists")
            .inner;
        assert!(
            !collection.has_secondary_index("project"),
            "no secondary index before ensure_index — recall would post-filter O(n)"
        );

        sm.ensure_index("project").expect("ensure_index");
        assert!(
            collection.has_secondary_index("project"),
            "ensure_index activates the bitmap prefilter index on the field"
        );

        // Idempotent: a second call is a cheap no-op that still succeeds.
        sm.ensure_index("project")
            .expect("ensure_index is idempotent");
        assert!(collection.has_secondary_index("project"));
    }

    #[test]
    fn test_query_filtered_skips_expired() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let ttl = Arc::new(super::super::ttl::MemoryTtl::new());
        let sm = SemanticMemory::new(Arc::clone(&db), 4, Arc::clone(&ttl)).expect("init failed");

        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let mut meta = serde_json::Map::new();
        meta.insert("kind".to_string(), serde_json::json!("test"));

        sm.store_with_metadata(1, "live fact", &emb, &meta).unwrap();
        sm.store_with_metadata(2, "expired fact", &emb, &meta)
            .unwrap();
        ttl.set_ttl(MemoryKind::Semantic, 2, 0); // expire id=2

        let mut filter = serde_json::Map::new();
        filter.insert("kind".to_string(), serde_json::json!("test"));

        let results = sm.query_filtered(&emb, 5, &filter, 0).unwrap();
        assert_eq!(results.len(), 1, "expired point must be excluded");
        assert_eq!(results[0].0, 1);
    }

    #[test]
    fn test_query_filtered_with_offset() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let e1 = vec![1.0_f32, 0.0, 0.0, 0.0];
        let e2 = vec![0.99_f32, 0.14, 0.0, 0.0];
        let e3 = vec![0.98_f32, 0.20, 0.0, 0.0];

        let mut meta = serde_json::Map::new();
        meta.insert("grp".to_string(), serde_json::json!("x"));

        sm.store_with_metadata(1, "best", &e1, &meta).unwrap();
        sm.store_with_metadata(2, "second", &e2, &meta).unwrap();
        sm.store_with_metadata(3, "third", &e3, &meta).unwrap();

        let mut filter = serde_json::Map::new();
        filter.insert("grp".to_string(), serde_json::json!("x"));

        // offset=1 skips the top result, so second-best appears first
        let paged = sm.query_filtered(&e1, 2, &filter, 1).unwrap();
        assert_eq!(paged.len(), 2, "should get the 2nd and 3rd results");
        assert!(
            paged.iter().all(|r| r.0 != 1),
            "top result must be skipped by offset"
        );
    }

    // ── #1049: edge-case / robustness tests ─────────────────────────────────────

    #[test]
    fn test_delete_unknown_id_is_ok() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        assert!(sm.delete(12345).is_ok());
    }

    #[test]
    fn test_deserialize_malformed_bytes_errors() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        // Non-empty, not valid JSON for Vec<Point>.
        let garbage = vec![0xFF_u8, 0x00, 0x42, 0x13];
        assert!(sm.deserialize(&garbage).is_err());
    }

    #[test]
    fn test_deserialize_replaces_not_merges() {
        let dir1 = tempdir().unwrap();
        let db1 = Arc::new(Database::open(dir1.path()).unwrap());
        let sm1 = make_semantic(Arc::clone(&db1));
        sm1.store(10, "snapshot fact", &[1.0, 0.0, 0.0, 0.0])
            .unwrap();
        let bytes = sm1.serialize().unwrap();

        let dir2 = tempdir().unwrap();
        let db2 = Arc::new(Database::open(dir2.path()).unwrap());
        let sm2 = make_semantic(Arc::clone(&db2));
        // Pre-existing fact that must NOT survive the deserialize.
        sm2.store(99, "preexisting fact", &[0.0, 1.0, 0.0, 0.0])
            .unwrap();

        sm2.deserialize(&bytes).unwrap();

        let ids: Vec<u64> = sm2
            .list_all()
            .unwrap()
            .into_iter()
            .map(|(id, _)| id)
            .collect();
        assert_eq!(ids, vec![10], "deserialize must replace, not merge");
    }

    #[test]
    fn test_concurrent_store_query_delete() {
        use std::thread;

        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = Arc::new(make_semantic(Arc::clone(&db)));

        let mut handles = Vec::new();
        for t in 0..4u64 {
            let sm = Arc::clone(&sm);
            handles.push(thread::spawn(move || {
                let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
                for i in 0..25u64 {
                    let id = t * 100 + i;
                    sm.store(id, "c", &emb).unwrap();
                    let _ = sm.query(&emb, 3).unwrap();
                    if i % 2 == 0 {
                        sm.delete(id).unwrap();
                    }
                }
            }));
        }
        for h in handles {
            h.join().expect("worker thread panicked");
        }

        // Half of each thread's writes were deleted: 4 threads * 12 survivors.
        assert_eq!(sm.count(), 4 * 12);
    }

    // ── Reserved durable-TTL key: user "expires_at" metadata is business data ──

    /// Reopens the database at `path` into a fresh `SemanticMemory` with its
    /// own TTL map, mimicking a process restart (payload-driven TTL rebuild).
    fn reopen_semantic(path: &std::path::Path) -> (Arc<MemoryTtl>, SemanticMemory) {
        let db = Arc::new(Database::open(path).unwrap());
        let ttl = Arc::new(MemoryTtl::new());
        let sm = SemanticMemory::new(db, 4, Arc::clone(&ttl)).unwrap();
        (ttl, sm)
    }

    /// Builds a one-entry metadata map.
    fn meta_one(key: &str, value: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        let mut map = serde_json::Map::new();
        map.insert(key.to_string(), value);
        map
    }

    /// `set_ttl_durable` on an existing fact persists the expiry: after a
    /// reopen the TTL map is rebuilt from the payload and the fact expires.
    #[test]
    fn test_set_ttl_durable_survives_restart() {
        let dir = tempdir().unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        {
            let db = Arc::new(Database::open(dir.path()).unwrap());
            let sm = make_semantic(Arc::clone(&db));
            sm.store(1, "post-hoc expiring fact", &emb).unwrap();
            // Post-hoc durable TTL: already elapsed (0 seconds).
            sm.set_ttl_durable(1, 0).unwrap();
        }

        let (ttl, sm) = reopen_semantic(dir.path());

        assert!(
            ttl.get(MemoryKind::Semantic, 1).is_some(),
            "durable post-hoc TTL must be rebuilt into the TTL map on reopen"
        );
        assert!(
            ttl.is_expired(MemoryKind::Semantic, 1),
            "a 0-second TTL must be expired after reopen"
        );
        assert!(
            sm.get(1).unwrap().is_none(),
            "expired fact must be invisible after reopen"
        );
    }

    /// `set_ttl_durable` keeps the fact's existing metadata intact and only
    /// adds the reserved expiry key.
    #[test]
    fn test_set_ttl_durable_preserves_existing_metadata() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        let meta = meta_one("source", serde_json::json!("chat"));
        sm.store_with_metadata(1, "fact with metadata", &emb, &meta)
            .unwrap();
        sm.set_ttl_durable(1, 3600).unwrap();

        let fact = sm.get(1).unwrap().expect("fact still alive (1h TTL)");
        assert_eq!(fact.0, "fact with metadata", "content preserved");
        let results = sm.query(&emb, 5).unwrap();
        assert!(results.iter().any(|r| r.0 == 1), "fact stays queryable");
    }

    /// `set_ttl_durable` on an expired-but-not-yet-swept id must surface
    /// `NotFound` instead of resurrecting the dead fact with a fresh TTL
    /// (expired entries are invisible on every read AND write surface).
    #[test]
    fn test_set_ttl_durable_expired_id_is_not_found() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        sm.store(1, "fact to expire", &emb).unwrap();
        sm.set_ttl_durable(1, 0).unwrap(); // expires immediately
        assert!(sm.get(1).unwrap().is_none(), "fact invisible once expired");

        let err = sm.set_ttl_durable(1, 3600).unwrap_err();
        assert!(
            matches!(err, AgentMemoryError::NotFound(_)),
            "refreshing an expired id must not resurrect it, got: {err:?}"
        );
        assert!(sm.get(1).unwrap().is_none(), "fact must stay invisible");
    }

    /// `set_ttl_durable` on a missing id surfaces a `NotFound` error instead
    /// of silently arming a TTL for a nonexistent fact.
    #[test]
    fn test_set_ttl_durable_missing_id_is_not_found() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));

        let err = sm.set_ttl_durable(999, 60).unwrap_err();
        assert!(
            matches!(err, AgentMemoryError::NotFound(_)),
            "missing id must yield NotFound, got: {err:?}"
        );
    }

    // ── Graph dimension: relate / relations / unrelate ─────────────────────

    /// relate() creates a typed edge between two live facts; relations()
    /// exposes it; unrelate() removes it.
    #[test]
    fn test_relate_relations_unrelate_roundtrip() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "context", &emb).unwrap();
        sm.store(2, "fact", &emb).unwrap();

        let props = meta_one("weight", serde_json::json!(0.9));
        let edge_id = sm.relate(1, 2, "RELATES_TO", Some(&props)).unwrap();

        let rels = sm.relations(1).unwrap();
        assert_eq!(rels.len(), 1);
        assert_eq!(rels[0].id(), edge_id);
        assert_eq!(rels[0].target(), 2);
        assert_eq!(rels[0].label(), "RELATES_TO");
        assert_eq!(rels[0].property("weight"), Some(&serde_json::json!(0.9)));

        assert!(sm.unrelate(edge_id).unwrap(), "edge must be removed");
        assert!(sm.relations(1).unwrap().is_empty());
    }

    /// incoming_relations() is the mirror of relations(): the edge `1 -> 2`
    /// is visible from `2`'s side with its source intact, and only there.
    #[test]
    fn test_incoming_relations_exposes_the_edge_from_the_target_side() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "context", &emb).unwrap();
        sm.store(2, "fact", &emb).unwrap();
        let edge_id = sm.relate(1, 2, "RELATES_TO", None).unwrap();

        let incoming = sm.incoming_relations(2).unwrap();
        assert_eq!(incoming.len(), 1);
        assert_eq!(incoming[0].id(), edge_id);
        assert_eq!(incoming[0].source(), 1);
        assert_eq!(incoming[0].label(), "RELATES_TO");
        assert!(
            sm.incoming_relations(1).unwrap().is_empty(),
            "the source side has no incoming edge"
        );
    }

    /// incoming_relations() drops an edge whose SOURCE is TTL-expired — the
    /// mirror of relations() filtering expired targets: the live endpoint is
    /// always the queried one, the filter guards the far end.
    #[test]
    fn test_incoming_relations_filters_expired_source() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "ephemeral", &emb).unwrap();
        sm.store(2, "fact", &emb).unwrap();
        sm.relate(1, 2, "RELATES_TO", None).unwrap();

        sm.set_ttl_durable(1, 0).unwrap(); // source expires immediately

        assert!(
            sm.incoming_relations(2).unwrap().is_empty(),
            "an edge from an expired source is dead and must not be reported"
        );
    }

    /// relate() refuses missing and expired endpoints (write surfaces must
    /// not resurrect or dangle).
    #[test]
    fn test_relate_rejects_missing_and_expired_endpoints() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "context", &emb).unwrap();

        let err = sm.relate(1, 999, "RELATES_TO", None).unwrap_err();
        assert!(matches!(err, AgentMemoryError::NotFound(_)));

        sm.store(2, "ephemeral", &emb).unwrap();
        sm.set_ttl_durable(2, 0).unwrap(); // expires immediately
        let err = sm.relate(1, 2, "RELATES_TO", None).unwrap_err();
        assert!(matches!(err, AgentMemoryError::NotFound(_)));
    }

    /// Deleting a memory cascades to its relation edges (no dangling edges).
    #[test]
    fn test_delete_memory_cascades_relations() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "context", &emb).unwrap();
        sm.store(2, "fact", &emb).unwrap();
        sm.relate(1, 2, "RELATES_TO", None).unwrap();

        sm.delete(2).unwrap();
        assert!(
            sm.relations(1).unwrap().is_empty(),
            "deleting the target memory must cascade away the edge"
        );
    }

    /// Relations survive a restart (edge WAL) and the edge-id allocator
    /// reseeds past persisted edges.
    #[test]
    fn test_relations_survive_restart_without_id_collision() {
        let dir = tempdir().unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let first_edge;
        {
            let db = Arc::new(Database::open(dir.path()).unwrap());
            let sm = make_semantic(Arc::clone(&db));
            sm.store(1, "context", &emb).unwrap();
            sm.store(2, "fact", &emb).unwrap();
            first_edge = sm.relate(1, 2, "RELATES_TO", None).unwrap();
        }

        let (_ttl, sm) = reopen_semantic(dir.path());
        let rels = sm.relations(1).unwrap();
        assert_eq!(rels.len(), 1, "edge must survive the restart (edge WAL)");
        assert_eq!(rels[0].id(), first_edge);

        sm.store(3, "another fact", &emb).unwrap();
        let second_edge = sm.relate(1, 3, "SUPPORTS", None).unwrap();
        assert_ne!(
            second_edge, first_edge,
            "reseeded allocator must not collide with persisted edges"
        );
        assert_eq!(sm.relations(1).unwrap().len(), 2);
    }

    /// Snapshot round-trip preserves relations: serialize captures the edges
    /// between snapshotted memories and restore re-adds them (review
    /// 2026-06-11: restore previously wiped every relation via the cascade).
    #[test]
    fn test_snapshot_roundtrip_preserves_relations() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "ctx", &emb).unwrap();
        sm.store(2, "fact", &emb).unwrap();
        let edge_id = sm.relate(1, 2, "RELATES_TO", None).unwrap();

        let snapshot = sm.serialize().unwrap();
        // Mutate after the snapshot: unrelate + add a new relation.
        sm.unrelate(edge_id).unwrap();
        sm.store(3, "other", &emb).unwrap();
        sm.relate(1, 3, "SUPPORTS", None).unwrap();

        sm.deserialize(&snapshot).unwrap();

        let rels = sm.relations(1).unwrap();
        assert_eq!(rels.len(), 1, "restore must bring back the snapshot edge");
        assert_eq!(rels[0].target(), 2);
        assert_eq!(rels[0].label(), "RELATES_TO");
    }

    /// Pre-graph snapshots (bare point arrays) still load — without edges.
    #[test]
    fn test_legacy_bare_array_snapshot_still_loads() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "ctx", &emb).unwrap();

        // Simulate an old snapshot: a bare JSON array of points.
        let points: Vec<crate::Point> = vec![crate::Point::new(
            7,
            emb.clone(),
            Some(serde_json::json!({"content": "legacy"})),
        )];
        let legacy = serde_json::to_vec(&points).unwrap();

        sm.deserialize(&legacy).unwrap();
        assert!(sm.get(7).unwrap().is_some(), "legacy snapshot points load");
        assert!(sm.relations(7).unwrap().is_empty());
    }

    /// flush() compacts the edge WAL into the snapshot for memory (vector)
    /// collections too, and edges survive the reopen via the snapshot
    /// (review 2026-06-11: the WAL previously grew forever and a torn tail
    /// permanently broke edge durability).
    #[test]
    fn test_flush_compacts_edge_wal_and_edges_survive_reopen() {
        let dir = tempdir().unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        {
            let db = Arc::new(Database::open(dir.path()).unwrap());
            let sm = make_semantic(Arc::clone(&db));
            sm.store(1, "ctx", &emb).unwrap();
            sm.store(2, "fact", &emb).unwrap();
            sm.relate(1, 2, "RELATES_TO", None).unwrap();
            db.flush_all();
        }

        let collection_dir = std::fs::read_dir(dir.path())
            .unwrap()
            .filter_map(Result::ok)
            .find(|e| e.file_name().to_string_lossy().starts_with("_semantic"))
            .expect("semantic collection dir")
            .path();
        assert!(
            collection_dir.join("edge_store.bin").exists(),
            "flush must snapshot the edge store for memory collections"
        );
        let wal_len = std::fs::metadata(collection_dir.join("edges.wal")).map_or(0, |m| m.len());
        assert_eq!(wal_len, 0, "flush must truncate the compacted edge WAL");

        let (_ttl, sm) = reopen_semantic(dir.path());
        assert_eq!(
            sm.relations(1).unwrap().len(),
            1,
            "edges must survive reopen via the snapshot"
        );
    }

    /// relations() hides edges whose endpoint has expired (read invisibility
    /// extends to the graph surface).
    #[test]
    fn test_relations_hide_expired_endpoints() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "ctx", &emb).unwrap();
        sm.store(2, "ephemeral fact", &emb).unwrap();
        sm.relate(1, 2, "RELATES_TO", None).unwrap();

        sm.set_ttl_durable(2, 0).unwrap(); // expires immediately
        assert!(
            sm.relations(1).unwrap().is_empty(),
            "edges to expired endpoints must be invisible"
        );
    }

    /// THE mission query: vector NEAR + graph MATCH + scalar metadata over
    /// agent memory, end-to-end through the VelesQL bridge.
    #[test]
    fn test_mission_query_near_match_scalar_over_memory() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let memory = crate::agent::AgentMemory::with_dimension(Arc::clone(&db), 4)
            .expect("test: AgentMemory::with_dimension");
        let sm = memory.semantic();

        let close = vec![1.0_f32, 0.0, 0.0, 0.0];
        let far = vec![0.0_f32, 1.0, 0.0, 0.0];
        let tech = meta_one("category", serde_json::json!("tech"));
        let bio = meta_one("category", serde_json::json!("bio"));

        // ctx(1) relates to fact(2); ctx(3) has no relations; ctx(4) wrong category.
        sm.store_with_metadata(1, "ctx about rust", &close, &tech)
            .unwrap();
        sm.store_with_metadata(2, "fact: rust is fast", &close, &tech)
            .unwrap();
        sm.store_with_metadata(3, "ctx unrelated", &close, &tech)
            .unwrap();
        sm.store_with_metadata(4, "ctx other domain", &far, &bio)
            .unwrap();
        sm.relate(1, 2, "RELATES_TO", None).unwrap();
        sm.relate(4, 2, "RELATES_TO", None).unwrap();

        let mut params = std::collections::HashMap::new();
        params.insert("q".to_string(), serde_json::json!([1.0, 0.0, 0.0, 0.0]));
        let results = memory
            .query_semantic(
                "SELECT * FROM memory AS m \
                 WHERE vector NEAR $q AND category = 'tech' \
                 AND MATCH (m)-[:RELATES_TO]->(f) LIMIT 5",
                &params,
            )
            .unwrap();

        let ids: Vec<u64> = results.iter().map(|r| r.point.id).collect();
        assert_eq!(
            ids,
            vec![1],
            "only ctx 1 is tech AND relates to a fact; got {ids:?}"
        );
    }

    /// A user business field named `expires_at` (subscription, offer, token…)
    /// stored via `store_with_metadata` must stay plain metadata: visible in
    /// session AND after a reopen, never rebuilt into the durable TTL map.
    #[test]
    fn test_user_expires_at_metadata_survives_restart() {
        let dir = tempdir().unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let past_epoch = 1_000_000_u64; // long-gone epoch seconds

        {
            let db = Arc::new(Database::open(dir.path()).unwrap());
            let sm = make_semantic(Arc::clone(&db));
            let meta = meta_one("expires_at", serde_json::json!(past_epoch));
            sm.store_with_metadata(1, "offer expired yesterday", &emb, &meta)
                .unwrap();
            assert!(sm.get(1).unwrap().is_some(), "fact visible in session");
        }

        let (ttl, sm) = reopen_semantic(dir.path());

        assert!(
            ttl.get(MemoryKind::Semantic, 1).is_none(),
            "user expires_at metadata must not be rebuilt into the TTL map"
        );
        assert!(
            sm.get(1).unwrap().is_some(),
            "fact with user expires_at metadata must stay alive after reopen"
        );
        let results = sm.query(&emb, 5).unwrap();
        assert!(results.iter().any(|r| r.0 == 1), "fact must stay queryable");

        // The business field itself is preserved and filterable.
        let filter = meta_one("expires_at", serde_json::json!(past_epoch));
        let filtered = sm.query_filtered(&emb, 5, &filter, 0).unwrap();
        assert_eq!(
            filtered.len(),
            1,
            "user expires_at field must be preserved as metadata"
        );
    }

    /// Same collision via `update_metadata`: merging a user `expires_at` into
    /// an existing fact must not arm a durable TTL at the next reopen.
    #[test]
    fn test_update_metadata_user_expires_at_survives_restart() {
        let dir = tempdir().unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        {
            let db = Arc::new(Database::open(dir.path()).unwrap());
            let sm = make_semantic(Arc::clone(&db));
            sm.store(1, "subscription fact", &emb).unwrap();
            let updates = meta_one("expires_at", serde_json::json!(1_000_000_u64));
            sm.update_metadata(1, &updates).unwrap();
        }

        let (ttl, sm) = reopen_semantic(dir.path());

        assert!(
            ttl.get(MemoryKind::Semantic, 1).is_none(),
            "user expires_at update must not be rebuilt into the TTL map"
        );
        assert!(
            sm.get(1).unwrap().is_some(),
            "fact must stay alive after reopen"
        );
    }

    /// The reserved durable-expiry key (`_veles_expires_at`) is stripped from
    /// user metadata, mirroring how the `content` parameter owns `content`.
    #[test]
    fn test_reserved_expiry_key_stripped_from_store_metadata() {
        let dir = tempdir().unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        {
            let db = Arc::new(Database::open(dir.path()).unwrap());
            let sm = make_semantic(Arc::clone(&db));
            let meta = meta_one("_veles_expires_at", serde_json::json!(1_u64));
            sm.store_with_metadata(1, "spoof attempt", &emb, &meta)
                .unwrap();
        }

        let (ttl, sm) = reopen_semantic(dir.path());

        assert!(
            ttl.get(MemoryKind::Semantic, 1).is_none(),
            "reserved key must be stripped at store time"
        );
        assert!(sm.get(1).unwrap().is_some());
    }

    /// `update_metadata` must neither inject nor clobber the reserved durable
    /// expiry: a legitimate `store_with_ttl` expiry survives a metadata update
    /// and is rebuilt identically at reopen.
    #[test]
    fn test_update_metadata_preserves_legit_durable_ttl() {
        let dir = tempdir().unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let original_expiry;

        {
            let db = Arc::new(Database::open(dir.path()).unwrap());
            let ttl = Arc::new(MemoryTtl::new());
            let sm = SemanticMemory::new(Arc::clone(&db), 4, Arc::clone(&ttl)).unwrap();
            sm.store_with_ttl(1, "mortal fact", &emb, 9_999).unwrap();
            original_expiry = ttl
                .get(MemoryKind::Semantic, 1)
                .expect("TTL tracked at store time")
                .expires_at;

            let mut updates = meta_one("tag", serde_json::json!("updated"));
            updates.insert("_veles_expires_at".to_string(), serde_json::json!(1_u64));
            sm.update_metadata(1, &updates).unwrap();
        }

        let (ttl, _sm) = reopen_semantic(dir.path());

        let entry = ttl
            .get(MemoryKind::Semantic, 1)
            .expect("durable TTL must survive a metadata update");
        assert_eq!(
            entry.expires_at, original_expiry,
            "reserved key in updates must not clobber the durable expiry"
        );
    }

    // ── Reserved-key carry-forward on re-store ────────────────────────────────

    /// Re-storing the same id (a `remember` on an already-known fact) rewrites
    /// the payload from scratch. Reserved `_veles_*` system keys written by
    /// other subsystems (RL confidence, entity tags) must be carried forward
    /// from the previous version, or a plain content refresh silently wipes
    /// learned state.
    #[test]
    fn test_restore_carries_forward_reserved_system_keys() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        let mut meta = meta_one("_veles_confidence", serde_json::json!(0.75));
        meta.insert(
            "_veles_entities".to_string(),
            serde_json::json!(["parking_lot"]),
        );
        meta.insert("project".to_string(), serde_json::json!("veles"));
        sm.store_with_metadata(1, "first version", &emb, &meta)
            .unwrap();

        sm.store(1, "second version", &emb).unwrap();

        let after = sm.get_metadata(1).unwrap().expect("fact still stored");
        assert_eq!(
            after.get("_veles_confidence"),
            Some(&serde_json::json!(0.75)),
            "reserved RL confidence must survive a content re-store"
        );
        assert_eq!(
            after.get("_veles_entities"),
            Some(&serde_json::json!(["parking_lot"])),
            "reserved entity tags must survive a content re-store"
        );
        assert_eq!(
            after.get("content"),
            Some(&serde_json::json!("second version")),
            "the new content must win"
        );
        assert!(
            !after.contains_key("project"),
            "non-reserved user metadata is NOT carried forward (only `_veles_*` is)"
        );
    }

    /// Carry-forward never overrides: a reserved key supplied by the caller in
    /// the new metadata wins over the value stored under the previous version.
    #[test]
    fn test_restore_caller_reserved_key_wins_over_carried_forward() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        sm.store_with_metadata(
            1,
            "first",
            &emb,
            &meta_one("_veles_confidence", serde_json::json!(0.10)),
        )
        .unwrap();
        sm.store_with_metadata(
            1,
            "second",
            &emb,
            &meta_one("_veles_confidence", serde_json::json!(0.90)),
        )
        .unwrap();

        let after = sm.get_metadata(1).unwrap().expect("fact still stored");
        assert_eq!(
            after.get("_veles_confidence"),
            Some(&serde_json::json!(0.90)),
            "the caller's reserved value must not be shadowed by the prior one"
        );
    }

    /// An explicit TTL still wins over a carried-forward `_veles_expires_at`:
    /// the durable expiry parameter is applied after the carry-forward pass.
    #[test]
    fn test_restore_explicit_ttl_wins_over_carried_forward_expiry() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let ttl = Arc::new(MemoryTtl::new());
        let sm = SemanticMemory::new(Arc::clone(&db), 4, Arc::clone(&ttl)).unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        sm.store_with_ttl(1, "mortal fact", &emb, 10).unwrap();
        let first = ttl
            .get(MemoryKind::Semantic, 1)
            .expect("TTL tracked at store time")
            .expires_at;

        sm.store_with_ttl(1, "mortal fact, refreshed", &emb, 9_999)
            .unwrap();
        let second = ttl
            .get(MemoryKind::Semantic, 1)
            .expect("TTL still tracked after re-store")
            .expires_at;

        assert!(
            second > first,
            "the explicit expiry must overwrite the carried-forward one \
             (first={first}, second={second})"
        );
    }

    /// Carry-forward reads the *live* prior version: an id whose fact has
    /// expired contributes nothing, so a re-store starts from a clean payload.
    #[test]
    fn test_restore_after_expiry_carries_nothing_forward() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let ttl = Arc::new(MemoryTtl::new());
        let sm = SemanticMemory::new(Arc::clone(&db), 4, Arc::clone(&ttl)).unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];

        let meta = meta_one("_veles_confidence", serde_json::json!(0.75));
        sm.store_with_metadata(1, "doomed", &emb, &meta).unwrap();
        ttl.set_ttl(MemoryKind::Semantic, 1, 0);
        assert!(sm.get(1).unwrap().is_none(), "fact must be expired");

        // `store_with_ttl` re-arms the TTL map, so the refreshed fact is live
        // again and its payload observable.
        sm.store_with_ttl(1, "fresh start", &emb, 9_999).unwrap();

        let after = sm.get_metadata(1).unwrap().expect("fact re-stored");
        assert!(
            !after.contains_key("_veles_confidence"),
            "an expired prior version must not leak its reserved keys forward"
        );
    }
    /// What the `!contains_key` guard of `carry_forward_reserved_keys` actually
    /// protects — and the reason this test exists separately from the expiry
    /// one next to it.
    ///
    /// The durable expiry is guaranteed TWICE: carry-forward may copy an old
    /// one, then `attach_expiry` overwrites it unconditionally. So no
    /// single-fault mutation of the guard can change the expiry, and a test
    /// phrased around it is inert by construction — mutation testing showed
    /// exactly that.
    ///
    /// The learned state has no second mechanism. `_veles_confidence` is
    /// written by reinforcement, never re-supplied by a content re-store, and
    /// the guard is the only thing standing between it and the payload the
    /// caller hands in. Remove the guard and a re-store that carries its own
    /// value has it silently replaced by the stale one.
    #[test]
    fn test_restore_keeps_a_freshly_supplied_reserved_key_over_the_carried_one() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let ttl = Arc::new(MemoryTtl::new());
        let sm = SemanticMemory::new(Arc::clone(&db), 4, Arc::clone(&ttl)).unwrap();
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        let mut learned = serde_json::Map::new();
        learned.insert("_veles_confidence".to_string(), serde_json::json!(0.10));
        sm.store_with_metadata(1, "a fact the agent has doubted", &emb, &learned)
            .unwrap();
        // A re-store that supplies its OWN value for the same reserved key.
        let mut refreshed = serde_json::Map::new();
        refreshed.insert("_veles_confidence".to_string(), serde_json::json!(0.90));
        sm.store_with_metadata(1, "the same fact, now trusted", &emb, &refreshed)
            .unwrap();
        let payload = sm
            .get_metadata(1)
            .expect("the re-stored fact is readable")
            .expect("and it exists");
        assert_eq!(
            payload.get("_veles_confidence"),
            Some(&serde_json::json!(0.90)),
            "a value the caller supplied must not be shadowed by the carried-forward \
             one — got {:?}",
            payload.get("_veles_confidence")
        );
    }

    // ── Idempotence of relate (DC-1, issue #1703) ─────────────────────────

    /// `relate` publishes "Idempotent per (from, relation, to)" and now IS.
    ///
    /// Before this, every call allocated a fresh id from an atomic counter, so
    /// an agent replaying the same link across sessions accumulated parallel
    /// edges: `why()` returned the same edge N times and `unrelate` answered
    /// `removed: N` for what the caller believed was one link.
    #[test]
    fn test_relate_is_idempotent_per_from_relation_to() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "decision", &emb).unwrap();
        sm.store(2, "incident", &emb).unwrap();

        let first = sm.relate(1, 2, "caused_by", None).unwrap();
        for _ in 0..4 {
            assert_eq!(
                sm.relate(1, 2, "caused_by", None).unwrap(),
                first,
                "a repeated relation must answer the id already there"
            );
        }

        let rels = sm.relations(1).unwrap();
        assert_eq!(rels.len(), 1, "five identical calls, one edge");
        assert_eq!(rels[0].id(), first);
    }

    /// The dedup key is the TRIPLE, not the endpoint pair.
    ///
    /// The application-level dedup in `velesdb-memory` keyed on `(from, to)`
    /// alone, which silently dropped a second, differently-labelled relation
    /// between the same two facts. Keying on the label too is what keeps
    /// `unrelate(from, to, "supports")` from touching `"contradicts"`.
    #[test]
    fn test_relate_distinguishes_two_labels_between_the_same_pair() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "claim", &emb).unwrap();
        sm.store(2, "evidence", &emb).unwrap();

        let supports = sm.relate(1, 2, "supports", None).unwrap();
        let contradicts = sm.relate(1, 2, "contradicts", None).unwrap();

        assert_ne!(
            supports, contradicts,
            "a different label is a different edge"
        );
        assert_eq!(sm.relations(1).unwrap().len(), 2);
    }

    /// Idempotence must read the LIVE graph, never a remembered decision.
    ///
    /// A persistent `(from, relation, to) -> edge_id` memo would pass the test
    /// above and still break here: after `unrelate`, the relation genuinely no
    /// longer exists and `relate` must write it again.
    #[test]
    fn test_relate_after_unrelate_recreates_the_edge() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = make_semantic(Arc::clone(&db));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "a", &emb).unwrap();
        sm.store(2, "b", &emb).unwrap();

        let first = sm.relate(1, 2, "supports", None).unwrap();
        assert!(sm.unrelate(first).unwrap(), "the edge must be gone");
        assert!(sm.relations(1).unwrap().is_empty());

        let again = sm.relate(1, 2, "supports", None).unwrap();
        assert_eq!(
            again, first,
            "the id is derived, so it comes back identical"
        );
        assert_eq!(sm.relations(1).unwrap().len(), 1);
    }

    /// Concurrent identical `relate` calls converge on ONE edge.
    ///
    /// This is what a lookup-then-write could not have delivered at this
    /// layer: nothing here can hold the edge store's locks, so a scan of the
    /// source node's out-edges would leave a window in which every thread
    /// reads "absent" and every thread writes. Deriving the id moves the
    /// decision inside the `edge_ids` write guard the store already holds
    /// across its whole check-and-insert.
    #[test]
    fn test_concurrent_identical_relate_calls_create_one_edge() {
        let dir = tempdir().unwrap();
        let db = Arc::new(Database::open(dir.path()).unwrap());
        let sm = Arc::new(make_semantic(Arc::clone(&db)));
        let emb = vec![1.0_f32, 0.0, 0.0, 0.0];
        sm.store(1, "decision", &emb).unwrap();
        sm.store(2, "incident", &emb).unwrap();

        let handles: Vec<_> = (0..8)
            .map(|_| {
                let sm = Arc::clone(&sm);
                std::thread::spawn(move || sm.relate(1, 2, "caused_by", None).unwrap())
            })
            .collect();
        let ids: Vec<u64> = handles.into_iter().map(|h| h.join().unwrap()).collect();

        assert_eq!(
            ids.iter().collect::<HashSet<_>>().len(),
            1,
            "one id: {ids:?}"
        );
        assert_eq!(sm.relations(1).unwrap().len(), 1, "eight threads, one edge");
    }
}