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
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
//! PulseDB main struct and lifecycle operations.
//!
//! The [`PulseDB`] struct is the primary interface for interacting with
//! the database. It provides methods for:
//!
//! - Opening and closing the database
//! - Managing collectives (isolation units)
//! - Recording and querying experiences
//! - Semantic search and context retrieval
//!
//! # Quick Start
//!
//! ```rust
//! # fn main() -> pulsedb::Result<()> {
//! # let dir = tempfile::tempdir().unwrap();
//! use pulsedb::{PulseDB, Config, NewExperience};
//!
//! // Open or create a database
//! let db = PulseDB::open(dir.path().join("test.db"), Config::default())?;
//!
//! // Create a collective for your project
//! let collective = db.create_collective("my-project")?;
//!
//! // Record an experience
//! db.record_experience(NewExperience {
//! collective_id: collective,
//! content: "Always validate user input".to_string(),
//! embedding: Some(vec![0.1f32; 384]),
//! ..Default::default()
//! })?;
//!
//! // Close when done
//! db.close()?;
//! # Ok(())
//! # }
//! ```
//!
//! # Thread Safety
//!
//! `PulseDB` is `Send + Sync` and can be shared across threads using `Arc`.
//! The underlying storage uses MVCC for concurrent reads with exclusive
//! write locking.
//!
//! ```rust
//! # fn main() -> pulsedb::Result<()> {
//! # let dir = tempfile::tempdir().unwrap();
//! use std::sync::Arc;
//! use pulsedb::{PulseDB, Config};
//!
//! let db = Arc::new(PulseDB::open(dir.path().join("test.db"), Config::default())?);
//!
//! // Clone Arc for use in another thread
//! let db_clone = Arc::clone(&db);
//! std::thread::spawn(move || {
//! // Safe to use db_clone here
//! });
//! # Ok(())
//! # }
//! ```
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
#[cfg(feature = "sync")]
use tracing::debug;
use tracing::{info, instrument, warn};
use crate::activity::{validate_new_activity, Activity, NewActivity};
use crate::collective::types::CollectiveStats;
use crate::collective::{validate_collective_name, Collective};
use crate::config::{Config, DecayConfig, EmbeddingProvider, RecallWeights};
use crate::embedding::{create_embedding_service, EmbeddingService};
use crate::error::{NotFoundError, PulseDBError, Result, ValidationError};
use crate::experience::{
energy as experience_energy, validate_experience_update, validate_new_experience, Experience,
ExperienceUpdate, NewExperience,
};
use crate::insight::{validate_new_insight, DerivedInsight, NewDerivedInsight};
#[cfg(feature = "sync")]
use crate::relation::ExperienceRelation;
use crate::search::rerank::{self, is_legacy_recall, resolve_recall_weights};
use crate::search::{ContextCandidates, ContextRequest, SearchFilter, SearchOptions, SearchResult};
use crate::storage::{open_storage, DatabaseMetadata, StorageEngine};
#[cfg(feature = "sync")]
use crate::types::InstanceId;
#[cfg(feature = "sync")]
use crate::types::RelationId;
use crate::types::{CollectiveId, ExperienceId, InsightId, Timestamp};
use crate::vector::HnswIndex;
use crate::watch::{WatchEvent, WatchEventType, WatchFilter, WatchService, WatchStream};
/// The main PulseDB database handle.
///
/// This is the primary interface for all database operations. Create an
/// instance with [`PulseDB::open()`] and close it with [`PulseDB::close()`].
///
/// # Ownership
///
/// `PulseDB` owns its storage and embedding service. When you call `close()`,
/// the database is consumed and cannot be used afterward. This ensures
/// resources are properly released.
pub struct PulseDB {
/// Storage engine (redb or mock for testing).
storage: Box<dyn StorageEngine>,
/// Embedding service (external or ONNX).
embedding: Box<dyn EmbeddingService>,
/// Configuration used to open this database.
config: Config,
/// Per-collective HNSW vector indexes for experience semantic search.
///
/// Outer RwLock protects the HashMap (add/remove collectives).
/// Each HnswIndex has its own internal RwLock for concurrent search+insert.
vectors: RwLock<HashMap<CollectiveId, HnswIndex>>,
/// Per-collective HNSW vector indexes for insight semantic search.
///
/// Separate from `vectors` to prevent ID collisions between experiences
/// and insights. Uses InsightId→ExperienceId byte conversion for the
/// HNSW API (safe because indexes are isolated per collective).
insight_vectors: RwLock<HashMap<CollectiveId, HnswIndex>>,
/// Watch service for real-time experience change notifications.
///
/// Arc-wrapped because [`WatchStream`] holds a weak reference for
/// cleanup on drop.
watch: Arc<WatchService>,
}
impl std::fmt::Debug for PulseDB {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let vector_count = self.vectors.read().map(|v| v.len()).unwrap_or(0);
let insight_vector_count = self.insight_vectors.read().map(|v| v.len()).unwrap_or(0);
f.debug_struct("PulseDB")
.field("config", &self.config)
.field("embedding_dimension", &self.embedding_dimension())
.field("vector_indexes", &vector_count)
.field("insight_vector_indexes", &insight_vector_count)
.finish_non_exhaustive()
}
}
impl PulseDB {
/// Opens or creates a PulseDB database at the specified path.
///
/// If the database doesn't exist, it will be created with the given
/// configuration. If it exists, the configuration will be validated
/// against the stored settings (e.g., embedding dimension must match).
///
/// # Arguments
///
/// * `path` - Path to the database file (created if it doesn't exist)
/// * `config` - Configuration options for the database
///
/// # Errors
///
/// Returns an error if:
/// - Configuration is invalid (see [`Config::validate`])
/// - Database file is corrupted
/// - Database is locked by another process
/// - Schema version doesn't match (needs migration)
/// - Embedding dimension doesn't match existing database
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// use pulsedb::{PulseDB, Config, EmbeddingDimension};
///
/// // Open with default configuration
/// let db = PulseDB::open(dir.path().join("default.db"), Config::default())?;
/// # drop(db);
///
/// // Open with custom embedding dimension
/// let db = PulseDB::open(dir.path().join("custom.db"), Config {
/// embedding_dimension: EmbeddingDimension::D768,
/// ..Default::default()
/// })?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(config), fields(path = %path.as_ref().display()))]
pub fn open(path: impl AsRef<Path>, config: Config) -> Result<Self> {
// Validate configuration first
config.validate().map_err(PulseDBError::from)?;
info!("Opening PulseDB");
// Open storage engine
let storage = open_storage(&path, &config)?;
// Create embedding service
let embedding = create_embedding_service(&config)?;
// Load or rebuild HNSW indexes for all existing collectives
let vectors = Self::load_all_indexes(&*storage, &config)?;
let insight_vectors = Self::load_all_insight_indexes(&*storage, &config)?;
info!(
dimension = config.embedding_dimension.size(),
sync_mode = ?config.sync_mode,
collectives = vectors.len(),
"PulseDB opened successfully"
);
let watch = Arc::new(WatchService::new(
config.watch.buffer_size,
config.watch.in_process,
));
Ok(Self {
storage,
embedding,
config,
vectors: RwLock::new(vectors),
insight_vectors: RwLock::new(insight_vectors),
watch,
})
}
/// Closes the database, flushing all pending writes.
///
/// This method consumes the `PulseDB` instance, ensuring it cannot
/// be used after closing. The underlying storage engine flushes all
/// buffered data to disk.
///
/// # Errors
///
/// Returns an error if the storage backend reports a flush failure.
/// Note: the current redb backend flushes durably on drop, so this
/// always returns `Ok(())` in practice.
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// use pulsedb::{PulseDB, Config};
///
/// let db = PulseDB::open(dir.path().join("test.db"), Config::default())?;
/// // ... use the database ...
/// db.close()?; // db is consumed here
/// // db.something() // Compile error: db was moved
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self))]
pub fn close(self) -> Result<()> {
info!("Closing PulseDB");
// Persist HNSW indexes BEFORE closing storage.
// If HNSW save fails, storage is still open for potential recovery.
// On next open(), stale/missing HNSW files trigger a rebuild from redb.
if let Some(hnsw_dir) = self.hnsw_dir() {
// Experience HNSW indexes
let vectors = self
.vectors
.read()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned during close"))?;
for (collective_id, index) in vectors.iter() {
if let Err(e) = index.save_to_dir(&hnsw_dir, &collective_id.to_string()) {
warn!(
collective = %collective_id,
error = %e,
"Failed to save HNSW index (will rebuild on next open)"
);
}
}
drop(vectors);
// Insight HNSW indexes (separate files with _insights suffix)
let insight_vectors = self
.insight_vectors
.read()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned during close"))?;
for (collective_id, index) in insight_vectors.iter() {
let name = format!("{}_insights", collective_id);
if let Err(e) = index.save_to_dir(&hnsw_dir, &name) {
warn!(
collective = %collective_id,
error = %e,
"Failed to save insight HNSW index (will rebuild on next open)"
);
}
}
}
// Close storage (flushes pending writes)
self.storage.close()?;
info!("PulseDB closed successfully");
Ok(())
}
/// Returns a reference to the database configuration.
///
/// This is the configuration that was used to open the database.
/// Note that some settings (like embedding dimension) are locked
/// on database creation and cannot be changed.
#[inline]
pub fn config(&self) -> &Config {
&self.config
}
/// Returns the database metadata.
///
/// Metadata includes schema version, embedding dimension, and timestamps
/// for when the database was created and last opened.
#[inline]
pub fn metadata(&self) -> &DatabaseMetadata {
self.storage.metadata()
}
/// Returns the embedding dimension configured for this database.
///
/// All embeddings stored in this database must have exactly this
/// many dimensions.
#[inline]
pub fn embedding_dimension(&self) -> usize {
self.config.embedding_dimension.size()
}
// =========================================================================
// Internal Accessors (for use by feature modules)
// =========================================================================
/// Returns a reference to the storage engine.
///
/// This is for internal use by other PulseDB modules.
#[inline]
#[allow(dead_code)] // Will be used by search (Phase 2) and other modules
pub(crate) fn storage(&self) -> &dyn StorageEngine {
self.storage.as_ref()
}
/// Returns a reference to the embedding service.
///
/// This is for internal use by other PulseDB modules.
#[inline]
#[allow(dead_code)] // Will be used by search (Phase 2) and other modules
pub(crate) fn embedding(&self) -> &dyn EmbeddingService {
self.embedding.as_ref()
}
// =========================================================================
// HNSW Index Lifecycle
// =========================================================================
/// Returns the directory for HNSW index files.
///
/// Derives `{db_path}.hnsw/` from the storage path. Returns `None` if
/// the storage has no file path (e.g., in-memory tests).
fn hnsw_dir(&self) -> Option<PathBuf> {
self.storage.path().map(|p| {
let mut hnsw_path = p.as_os_str().to_owned();
hnsw_path.push(".hnsw");
PathBuf::from(hnsw_path)
})
}
/// Loads or rebuilds HNSW indexes for all existing collectives.
///
/// For each collective in storage:
/// 1. Try loading metadata from `.hnsw.meta` file
/// 2. Rebuild the graph from redb embeddings (always, since we can't
/// load the graph due to hnsw_rs lifetime constraints)
/// 3. Restore deleted set from metadata if available
fn load_all_indexes(
storage: &dyn StorageEngine,
config: &Config,
) -> Result<HashMap<CollectiveId, HnswIndex>> {
let collectives = storage.list_collectives()?;
let mut vectors = HashMap::with_capacity(collectives.len());
let hnsw_dir = storage.path().map(|p| {
let mut hnsw_path = p.as_os_str().to_owned();
hnsw_path.push(".hnsw");
PathBuf::from(hnsw_path)
});
for collective in &collectives {
let dimension = collective.embedding_dimension as usize;
// List all experience IDs in this collective
let exp_ids = storage.list_experience_ids_in_collective(collective.id)?;
// Load embeddings from redb (source of truth)
let mut embeddings = Vec::with_capacity(exp_ids.len());
for exp_id in &exp_ids {
if let Some(embedding) = storage.get_embedding(*exp_id)? {
embeddings.push((*exp_id, embedding));
}
}
// Try loading metadata (for deleted set and ID mappings)
let metadata = hnsw_dir
.as_ref()
.and_then(|dir| HnswIndex::load_metadata(dir, &collective.id.to_string()).ok())
.flatten();
// Rebuild the HNSW graph from embeddings
let index = if embeddings.is_empty() {
HnswIndex::new(dimension, &config.hnsw)
} else {
let start = std::time::Instant::now();
let idx = HnswIndex::rebuild_from_embeddings(dimension, &config.hnsw, embeddings)?;
info!(
collective = %collective.id,
vectors = idx.active_count(),
elapsed_ms = start.elapsed().as_millis() as u64,
"Rebuilt HNSW index from redb embeddings"
);
idx
};
// Restore deleted set from metadata if available
if let Some(meta) = metadata {
index.restore_deleted_set(&meta.deleted)?;
}
vectors.insert(collective.id, index);
}
Ok(vectors)
}
/// Loads or rebuilds insight HNSW indexes for all existing collectives.
///
/// For each collective, loads all insights from storage and rebuilds
/// the HNSW graph from their inline embeddings. Uses InsightId→ExperienceId
/// byte conversion for the HNSW API.
fn load_all_insight_indexes(
storage: &dyn StorageEngine,
config: &Config,
) -> Result<HashMap<CollectiveId, HnswIndex>> {
let collectives = storage.list_collectives()?;
let mut insight_vectors = HashMap::with_capacity(collectives.len());
let hnsw_dir = storage.path().map(|p| {
let mut hnsw_path = p.as_os_str().to_owned();
hnsw_path.push(".hnsw");
PathBuf::from(hnsw_path)
});
for collective in &collectives {
let dimension = collective.embedding_dimension as usize;
// List all insight IDs in this collective
let insight_ids = storage.list_insight_ids_in_collective(collective.id)?;
// Load insights and extract embeddings (converting InsightId → ExperienceId)
let mut embeddings = Vec::with_capacity(insight_ids.len());
for insight_id in &insight_ids {
if let Some(insight) = storage.get_insight(*insight_id)? {
let exp_id = ExperienceId::from_bytes(*insight_id.as_bytes());
embeddings.push((exp_id, insight.embedding));
}
}
// Try loading metadata (for deleted set)
let name = format!("{}_insights", collective.id);
let metadata = hnsw_dir
.as_ref()
.and_then(|dir| HnswIndex::load_metadata(dir, &name).ok())
.flatten();
// Rebuild HNSW graph from embeddings
let index = if embeddings.is_empty() {
HnswIndex::new(dimension, &config.hnsw)
} else {
let start = std::time::Instant::now();
let idx = HnswIndex::rebuild_from_embeddings(dimension, &config.hnsw, embeddings)?;
info!(
collective = %collective.id,
insights = idx.active_count(),
elapsed_ms = start.elapsed().as_millis() as u64,
"Rebuilt insight HNSW index from stored insights"
);
idx
};
// Restore deleted set from metadata if available
if let Some(meta) = metadata {
index.restore_deleted_set(&meta.deleted)?;
}
insight_vectors.insert(collective.id, index);
}
Ok(insight_vectors)
}
/// Executes a closure with the HNSW index for a collective.
///
/// This is the primary accessor for vector search operations (used by
/// `search_similar()`). The closure runs while the outer RwLock guard
/// is held (read lock), so the HnswIndex reference stays valid.
/// Returns `None` if no index exists for the collective.
#[doc(hidden)]
pub fn with_vector_index<F, R>(&self, collective_id: CollectiveId, f: F) -> Result<Option<R>>
where
F: FnOnce(&HnswIndex) -> Result<R>,
{
let vectors = self
.vectors
.read()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?;
match vectors.get(&collective_id) {
Some(index) => Ok(Some(f(index)?)),
None => Ok(None),
}
}
// =========================================================================
// Test Helpers
// =========================================================================
/// Returns a reference to the storage engine for integration testing.
///
/// This method is intentionally hidden from documentation. It provides
/// test-only access to the storage layer for verifying ACID guarantees
/// and crash recovery. Production code should use the public PulseDB API.
#[doc(hidden)]
#[inline]
pub fn storage_for_test(&self) -> &dyn StorageEngine {
self.storage.as_ref()
}
/// Returns true if this database is in read-only mode.
pub fn is_read_only(&self) -> bool {
self.config.read_only
}
/// Checks if the database is read-only and returns an error if so.
#[inline]
fn check_writable(&self) -> Result<()> {
if self.config.read_only {
return Err(PulseDBError::ReadOnly);
}
Ok(())
}
// =========================================================================
// Collective Management (E1-S02)
// =========================================================================
/// Creates a new collective with the given name.
///
/// The collective's embedding dimension is locked to the database's
/// configured dimension at creation time.
///
/// # Arguments
///
/// * `name` - Human-readable name (1-255 characters, not whitespace-only)
///
/// # Errors
///
/// Returns a validation error if the name is empty, whitespace-only,
/// or exceeds 255 characters.
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// let id = db.create_collective("my-project")?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self))]
pub fn create_collective(&self, name: &str) -> Result<CollectiveId> {
self.check_writable()?;
validate_collective_name(name)?;
let dimension = self.config.embedding_dimension.size() as u16;
let collective = Collective::new(name, dimension);
let id = collective.id;
// Persist to redb first (source of truth)
self.storage.save_collective(&collective)?;
// Create empty HNSW indexes for this collective
let exp_index = HnswIndex::new(dimension as usize, &self.config.hnsw);
let insight_index = HnswIndex::new(dimension as usize, &self.config.hnsw);
self.vectors
.write()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?
.insert(id, exp_index);
self.insight_vectors
.write()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?
.insert(id, insight_index);
info!(id = %id, name = %name, "Collective created");
Ok(id)
}
/// Creates a new collective with an owner for multi-tenancy.
///
/// Same as [`create_collective`](Self::create_collective) but assigns
/// an owner ID, enabling filtering with
/// [`list_collectives_by_owner`](Self::list_collectives_by_owner).
///
/// # Arguments
///
/// * `name` - Human-readable name (1-255 characters)
/// * `owner_id` - Owner identifier (must not be empty)
///
/// # Errors
///
/// Returns a validation error if the name or owner_id is invalid.
#[instrument(skip(self))]
pub fn create_collective_with_owner(&self, name: &str, owner_id: &str) -> Result<CollectiveId> {
self.check_writable()?;
validate_collective_name(name)?;
if owner_id.is_empty() {
return Err(PulseDBError::from(
crate::error::ValidationError::required_field("owner_id"),
));
}
let dimension = self.config.embedding_dimension.size() as u16;
let collective = Collective::with_owner(name, owner_id, dimension);
let id = collective.id;
// Persist to redb first (source of truth)
self.storage.save_collective(&collective)?;
// Create empty HNSW indexes for this collective
let exp_index = HnswIndex::new(dimension as usize, &self.config.hnsw);
let insight_index = HnswIndex::new(dimension as usize, &self.config.hnsw);
self.vectors
.write()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?
.insert(id, exp_index);
self.insight_vectors
.write()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?
.insert(id, insight_index);
info!(id = %id, name = %name, owner = %owner_id, "Collective created with owner");
Ok(id)
}
/// Returns a collective by ID, or `None` if not found.
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let id = db.create_collective("example")?;
/// if let Some(collective) = db.get_collective(id)? {
/// println!("Found: {}", collective.name);
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self))]
pub fn get_collective(&self, id: CollectiveId) -> Result<Option<Collective>> {
self.storage.get_collective(id)
}
/// Lists all collectives in the database.
///
/// Returns an empty vector if no collectives exist.
pub fn list_collectives(&self) -> Result<Vec<Collective>> {
self.storage.list_collectives()
}
/// Lists collectives filtered by owner ID.
///
/// Returns only collectives whose `owner_id` matches the given value.
/// Returns an empty vector if no matching collectives exist.
pub fn list_collectives_by_owner(&self, owner_id: &str) -> Result<Vec<Collective>> {
let all = self.storage.list_collectives()?;
Ok(all
.into_iter()
.filter(|c| c.owner_id.as_deref() == Some(owner_id))
.collect())
}
/// Returns statistics for a collective.
///
/// # Errors
///
/// Returns [`NotFoundError::Collective`] if the collective doesn't exist.
#[instrument(skip(self))]
pub fn get_collective_stats(&self, id: CollectiveId) -> Result<CollectiveStats> {
// Verify collective exists
self.storage
.get_collective(id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(id)))?;
let experience_count = self.storage.count_experiences_in_collective(id)?;
Ok(CollectiveStats {
experience_count,
storage_bytes: 0,
oldest_experience: None,
newest_experience: None,
})
}
/// Deletes a collective and all its associated data.
///
/// Performs cascade deletion: removes all experiences belonging to the
/// collective before removing the collective record itself.
///
/// # Errors
///
/// Returns [`NotFoundError::Collective`] if the collective doesn't exist.
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let collective_id = db.create_collective("to-delete")?;
/// db.delete_collective(collective_id)?;
/// assert!(db.get_collective(collective_id)?.is_none());
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self))]
pub fn delete_collective(&self, id: CollectiveId) -> Result<()> {
self.check_writable()?;
// Verify collective exists
self.storage
.get_collective(id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(id)))?;
// Cascade: delete all experiences for this collective
let deleted_count = self.storage.delete_experiences_by_collective(id)?;
if deleted_count > 0 {
info!(count = deleted_count, "Cascade-deleted experiences");
}
// Cascade: delete all insights for this collective
let deleted_insights = self.storage.delete_insights_by_collective(id)?;
if deleted_insights > 0 {
info!(count = deleted_insights, "Cascade-deleted insights");
}
// Cascade: delete all activities for this collective
let deleted_activities = self.storage.delete_activities_by_collective(id)?;
if deleted_activities > 0 {
info!(count = deleted_activities, "Cascade-deleted activities");
}
// Delete the collective record from storage
self.storage.delete_collective(id)?;
// Remove HNSW indexes from memory
self.vectors
.write()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?
.remove(&id);
self.insight_vectors
.write()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?
.remove(&id);
// Remove HNSW files from disk (non-fatal if fails)
if let Some(hnsw_dir) = self.hnsw_dir() {
if let Err(e) = HnswIndex::remove_files(&hnsw_dir, &id.to_string()) {
warn!(
collective = %id,
error = %e,
"Failed to remove experience HNSW files (non-fatal)"
);
}
let insight_name = format!("{}_insights", id);
if let Err(e) = HnswIndex::remove_files(&hnsw_dir, &insight_name) {
warn!(
collective = %id,
error = %e,
"Failed to remove insight HNSW files (non-fatal)"
);
}
}
info!(id = %id, "Collective deleted");
Ok(())
}
// =========================================================================
// Experience CRUD (E1-S03)
// =========================================================================
/// Records a new experience in the database.
///
/// This is the primary method for storing agent-learned knowledge. The method:
/// 1. Validates the input (content, scores, tags, embedding)
/// 2. Verifies the collective exists
/// 3. Resolves the embedding (generates if Builtin, requires if External)
/// 4. Stores the experience atomically across 4 tables
///
/// # Arguments
///
/// * `exp` - The experience to record (see [`NewExperience`])
///
/// # Errors
///
/// - [`ValidationError`](crate::ValidationError) if input is invalid
/// - [`NotFoundError::Collective`] if the collective doesn't exist
/// - [`PulseDBError::Embedding`] if embedding generation fails (Builtin mode)
#[instrument(skip(self, exp), fields(collective_id = %exp.collective_id))]
pub fn record_experience(&self, exp: NewExperience) -> Result<ExperienceId> {
self.check_writable()?;
let is_external = matches!(self.config.embedding_provider, EmbeddingProvider::External);
// Verify collective exists and get its dimension
let collective = self
.storage
.get_collective(exp.collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(exp.collective_id)))?;
// Validate input
validate_new_experience(&exp, collective.embedding_dimension, is_external)?;
// Resolve embedding
let embedding = match exp.embedding {
Some(emb) => emb,
None => {
// Builtin mode: generate embedding from content
self.embedding.embed(&exp.content)?
}
};
// Clone embedding for HNSW insertion (~1.5KB for 384d, negligible vs I/O)
let embedding_for_hnsw = embedding.clone();
let collective_id = exp.collective_id;
let timestamp = Timestamp::now();
// Construct the full experience record
let experience = Experience {
id: ExperienceId::new(),
collective_id,
content: exp.content,
embedding,
experience_type: exp.experience_type,
importance: exp.importance,
confidence: exp.confidence,
applications: BTreeMap::new(),
domain: exp.domain,
related_files: exp.related_files,
source_agent: exp.source_agent,
source_task: exp.source_task,
timestamp,
last_reinforced: timestamp,
archived: false,
};
let id = experience.id;
// Write to redb FIRST (source of truth). If crash happens after
// this but before HNSW insert, rebuild on next open will include it.
self.storage.save_experience(&experience)?;
// Insert into HNSW index (derived structure)
let vectors = self
.vectors
.read()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?;
if let Some(index) = vectors.get(&collective_id) {
index.insert_experience(id, &embedding_for_hnsw)?;
}
// Emit watch event after both storage and HNSW succeed
self.watch.emit(
WatchEvent {
experience_id: id,
collective_id,
event_type: WatchEventType::Created,
timestamp: experience.timestamp,
experience: Some(experience.clone()),
},
&experience,
)?;
info!(id = %id, "Experience recorded");
Ok(id)
}
/// Retrieves an experience by ID, including its embedding.
///
/// Returns `None` if no experience with the given ID exists.
#[instrument(skip(self))]
pub fn get_experience(&self, id: ExperienceId) -> Result<Option<Experience>> {
self.storage.get_experience(id)
}
/// Updates mutable fields of an experience.
///
/// Only fields set to `Some(...)` in the update are changed.
/// Content and embedding are immutable — create a new experience instead.
///
/// # Errors
///
/// - [`ValidationError`](crate::ValidationError) if updated values are invalid
/// - [`NotFoundError::Experience`] if the experience doesn't exist
#[instrument(skip(self, update))]
pub fn update_experience(&self, id: ExperienceId, update: ExperienceUpdate) -> Result<()> {
self.check_writable()?;
validate_experience_update(&update)?;
let updated = self.storage.update_experience(id, &update)?;
if !updated {
return Err(PulseDBError::from(NotFoundError::experience(id)));
}
// Emit watch event (fetch experience for collective_id + filter matching)
if self.watch.has_subscribers() {
if let Ok(Some(exp)) = self.storage.get_experience(id) {
let event_type = if update.archived == Some(true) {
WatchEventType::Archived
} else {
WatchEventType::Updated
};
self.watch.emit(
WatchEvent {
experience_id: id,
collective_id: exp.collective_id,
event_type,
timestamp: Timestamp::now(),
experience: Some(exp.clone()),
},
&exp,
)?;
}
}
info!(id = %id, "Experience updated");
Ok(())
}
/// Archives an experience (soft-delete).
///
/// Archived experiences remain in storage but are excluded from search
/// results. Use [`unarchive_experience`](Self::unarchive_experience) to restore.
///
/// # Errors
///
/// Returns [`NotFoundError::Experience`] if the experience doesn't exist.
#[instrument(skip(self))]
pub fn archive_experience(&self, id: ExperienceId) -> Result<()> {
self.check_writable()?;
self.update_experience(
id,
ExperienceUpdate {
archived: Some(true),
..Default::default()
},
)
}
/// Restores an archived experience.
///
/// The experience will once again appear in search results.
///
/// # Errors
///
/// Returns [`NotFoundError::Experience`] if the experience doesn't exist.
#[instrument(skip(self))]
pub fn unarchive_experience(&self, id: ExperienceId) -> Result<()> {
self.check_writable()?;
self.update_experience(
id,
ExperienceUpdate {
archived: Some(false),
..Default::default()
},
)
}
/// Permanently deletes an experience and its embedding.
///
/// This removes the experience from all tables and indices.
/// Unlike archiving, this is irreversible.
///
/// # Errors
///
/// Returns [`NotFoundError::Experience`] if the experience doesn't exist.
#[instrument(skip(self))]
pub fn delete_experience(&self, id: ExperienceId) -> Result<()> {
self.check_writable()?;
// Read experience first to get collective_id for HNSW lookup.
// This adds one extra read, but delete is not a hot path.
let experience = self
.storage
.get_experience(id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::experience(id)))?;
// Cascade-delete any relations involving this experience.
// Done before experience deletion so we can still look up relation data.
let rel_count = self.storage.delete_relations_for_experience(id)?;
if rel_count > 0 {
info!(
count = rel_count,
"Cascade-deleted relations for experience"
);
}
// Delete from redb FIRST (source of truth). If crash happens after
// this but before HNSW soft-delete, on reopen the experience won't be
// loaded from redb, so it's automatically excluded from the rebuilt index.
self.storage.delete_experience(id)?;
// Soft-delete from HNSW index (mark as deleted, not removed from graph).
// This takes effect immediately for the current session's searches.
let vectors = self
.vectors
.read()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?;
if let Some(index) = vectors.get(&experience.collective_id) {
index.delete_experience(id)?;
}
// Emit watch event after storage + HNSW deletion
self.watch.emit(
WatchEvent {
experience_id: id,
collective_id: experience.collective_id,
event_type: WatchEventType::Deleted,
timestamp: Timestamp::now(),
experience: None, // Deleted — no data to include
},
&experience,
)?;
info!(id = %id, "Experience deleted");
Ok(())
}
/// Reinforces an experience by incrementing its application count.
///
/// Each call atomically increments the `applications` counter by 1.
/// Returns the new application count.
///
/// # Errors
///
/// Returns [`NotFoundError::Experience`] if the experience doesn't exist.
#[instrument(skip(self))]
pub fn reinforce_experience(&self, id: ExperienceId) -> Result<u32> {
self.check_writable()?;
let new_count = self
.storage
.reinforce_experience(id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::experience(id)))?;
// Emit watch event (fetch experience for collective_id + filter matching)
if self.watch.has_subscribers() {
if let Ok(Some(exp)) = self.storage.get_experience(id) {
self.watch.emit(
WatchEvent {
experience_id: id,
collective_id: exp.collective_id,
event_type: WatchEventType::Updated,
timestamp: Timestamp::now(),
experience: Some(exp.clone()),
},
&exp,
)?;
}
}
info!(id = %id, applications = new_count, "Experience reinforced");
Ok(new_count)
}
/// Computes the current temporal energy for an experience.
///
/// This is a read-only diagnostic: it never writes to storage and does not
/// require a writable database handle. Per-collective decay configuration
/// takes precedence over the database's global default.
///
/// # Errors
///
/// Returns [`NotFoundError::Experience`] if the experience doesn't exist.
#[instrument(skip(self))]
pub fn energy(&self, id: ExperienceId) -> Result<f32> {
let experience = self
.storage
.get_experience(id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::experience(id)))?;
let decay_config = self
.storage
.get_decay_config(experience.collective_id)?
.unwrap_or_else(|| self.config.decay.clone());
Ok(experience_energy(
experience.importance,
experience.applications(),
experience.last_reinforced,
Timestamp::now(),
&decay_config,
))
}
/// Surfaces prune-eligible cold experiences in a collective, coldest-first.
///
/// Returns lightweight `(ExperienceId, energy)` pairs — **never** full
/// [`Experience`] records — for every experience whose current temporal
/// energy is `< below` **and** that is **not already archived**
/// (`energy < below && !archived`). Results are sorted ascending by energy
/// (coldest first) and truncated to `limit`.
///
/// This is a **human-triggered review tool**, not an automatic actuator: it
/// merely *surfaces* candidates a consumer may choose to archive/prune. It
/// **does not archive** anything and never mutates storage — the
/// `auto_archive_below_floor` flag is inert and read by no actuator.
///
/// # Archived exclusion
///
/// Already-archived experiences are excluded even when their energy is
/// `< below`: re-listing them is noise that would double-count a consumer's
/// prune loop. Only *cold AND not-yet-archived* experiences are returned.
///
/// # Performance
///
/// This is a **deliberate `O(n)` single-pass full-collective scan** (enumerate
/// all experience IDs → load each → compute scalar energy → filter). There is
/// **no energy index**; the scan is acceptable precisely because this is a
/// human-triggered review tool invoked rarely, not a hot query path. The
/// `DecayConfig` is resolved once and `Timestamp::now()` is captured once for
/// the whole scan (scalar `experience_energy` per candidate), mirroring
/// [`energy()`](Self::energy) — never a per-item `self.energy(id)` re-resolve.
///
/// # Examples
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("cold.db"), pulsedb::Config::default())?;
/// let collective = db.create_collective("my-project")?;
///
/// // Surface up to 100 prune-eligible candidates with energy < 0.05,
/// // coldest-first. Returns lightweight (ExperienceId, energy) pairs —
/// // not full Experience records. Read-only: nothing is archived.
/// for (id, energy) in db.list_cold_experiences(collective, 0.05, 100)? {
/// println!("cold candidate {id} @ energy {energy}");
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Arguments
///
/// * `collective_id` - The collective to scan.
/// * `below` - Energy threshold in `[0.0, 1.0]`; experiences with current
/// energy strictly below this are surfaced.
/// * `limit` - Maximum number of pairs to return (1-1000).
///
/// # Errors
///
/// - [`ValidationError::InvalidField`] if `limit` is 0 or > 1000, or if
/// `below` is NaN or outside `[0.0, 1.0]`.
/// - [`NotFoundError::Collective`] if the collective doesn't exist.
#[instrument(skip(self))]
pub fn list_cold_experiences(
&self,
collective_id: CollectiveId,
below: f32,
limit: usize,
) -> Result<Vec<(ExperienceId, f32)>> {
// Validate limit (mirror get_recent_experiences_filtered).
if limit == 0 || limit > 1000 {
return Err(
ValidationError::invalid_field("limit", "must be between 1 and 1000").into(),
);
}
// Validate threshold: reject NaN and out-of-range.
if below.is_nan() || !(0.0..=1.0).contains(&below) {
return Err(
ValidationError::invalid_field("below", "must be between 0.0 and 1.0").into(),
);
}
// Verify collective exists.
self.storage
.get_collective(collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(collective_id)))?;
// Resolve decay config ONCE and capture `now` ONCE for the whole scan
// (hot-path rule: never re-resolve per item via self.energy(id)).
let decay_config = self
.storage
.get_decay_config(collective_id)?
.unwrap_or_else(|| self.config.decay.clone());
let now = Timestamp::now();
// Single-pass full-collective scan. Stream every experience ID in ONE
// index iteration (limit = usize::MAX, offset = 0) — offset-restart
// pagination was quadratic (each page re-skipped from the start). The
// remaining per-row-txn / embedding-hauling / snapshot-safety rework is
// tracked in #21. Load each, compute scalar energy, keep
// `energy < below && !archived`.
let mut cold: Vec<(ExperienceId, f32)> = Vec::new();
let ids = self
.storage
.list_experience_ids_paginated(collective_id, usize::MAX, 0)?;
for id in ids {
let Some(experience) = self.storage.get_experience(id)? else {
continue;
};
if experience.archived {
continue;
}
let energy = experience_energy(
experience.importance,
experience.applications(),
experience.last_reinforced,
now,
&decay_config,
);
if energy < below {
cold.push((id, energy));
}
}
// Coldest-first (ascending energy), then truncate to limit.
cold.sort_by(|a, b| a.1.total_cmp(&b.1));
cold.truncate(limit);
Ok(cold)
}
// =========================================================================
// Recent Experiences
// =========================================================================
// =========================================================================
// Paginated List Operations (PulseVision)
// =========================================================================
/// Lists experiences in a collective with pagination.
///
/// Returns full `Experience` records (including embeddings) ordered by
/// timestamp. Use `offset` and `limit` for pagination.
///
/// Designed for visualization tools (PulseVision) that need to enumerate
/// the entire embedding space of a collective.
#[instrument(skip(self))]
pub fn list_experiences(
&self,
collective_id: CollectiveId,
limit: usize,
offset: usize,
) -> Result<Vec<Experience>> {
let ids = self
.storage
.list_experience_ids_paginated(collective_id, limit, offset)?;
let mut experiences = Vec::with_capacity(ids.len());
for id in ids {
if let Some(exp) = self.storage.get_experience(id)? {
experiences.push(exp);
}
}
Ok(experiences)
}
/// Lists relations in a collective with pagination.
#[instrument(skip(self))]
pub fn list_relations(
&self,
collective_id: CollectiveId,
limit: usize,
offset: usize,
) -> Result<Vec<crate::relation::ExperienceRelation>> {
self.storage
.list_relations_in_collective(collective_id, limit, offset)
}
/// Lists insights in a collective with pagination.
///
/// Returns full `DerivedInsight` records including embeddings.
#[instrument(skip(self))]
pub fn list_insights(
&self,
collective_id: CollectiveId,
limit: usize,
offset: usize,
) -> Result<Vec<DerivedInsight>> {
let ids = self
.storage
.list_insight_ids_paginated(collective_id, limit, offset)?;
let mut insights = Vec::with_capacity(ids.len());
for id in ids {
if let Some(insight) = self.storage.get_insight(id)? {
insights.push(insight);
}
}
Ok(insights)
}
/// Retrieves the most recent experiences in a collective.
///
/// Returns full experiences ordered by timestamp (newest first).
#[instrument(skip(self))]
pub fn get_recent_experiences(
&self,
collective_id: CollectiveId,
limit: usize,
) -> Result<Vec<Experience>> {
self.get_recent_experiences_filtered(collective_id, limit, SearchFilter::default())
}
/// Retrieves the most recent experiences in a collective with filtering.
///
/// Like [`get_recent_experiences()`](Self::get_recent_experiences), but
/// applies additional filters on domain, experience type, importance,
/// confidence, and timestamp.
///
/// Over-fetches from storage (2x `limit`) to account for entries removed
/// by post-filtering, then truncates to the requested `limit`.
///
/// # Arguments
///
/// * `collective_id` - The collective to query
/// * `limit` - Maximum number of experiences to return (1-1000)
/// * `filter` - Filter criteria to apply
///
/// # Errors
///
/// - [`ValidationError::InvalidField`] if `limit` is 0 or > 1000
/// - [`NotFoundError::Collective`] if the collective doesn't exist
#[instrument(skip(self, filter))]
pub fn get_recent_experiences_filtered(
&self,
collective_id: CollectiveId,
limit: usize,
filter: SearchFilter,
) -> Result<Vec<Experience>> {
// Validate limit
if limit == 0 || limit > 1000 {
return Err(
ValidationError::invalid_field("limit", "must be between 1 and 1000").into(),
);
}
// Verify collective exists
self.storage
.get_collective(collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(collective_id)))?;
// Over-fetch IDs to account for post-filtering losses
let over_fetch = limit.saturating_mul(2).min(2000);
let recent_ids = self
.storage
.get_recent_experience_ids(collective_id, over_fetch)?;
// Load full experiences and apply filter
let mut results = Vec::with_capacity(limit);
for (exp_id, _timestamp) in recent_ids {
if results.len() >= limit {
break;
}
if let Some(experience) = self.storage.get_experience(exp_id)? {
if filter.matches(&experience) {
results.push(experience);
}
}
}
Ok(results)
}
// =========================================================================
// Similarity Search (E2-S02)
// =========================================================================
/// Searches for experiences semantically similar to the query embedding.
///
/// Uses the HNSW vector index for approximate nearest neighbor search,
/// then fetches full experience records from storage. Archived experiences
/// are excluded by default.
///
/// Results are sorted by similarity descending (most similar first).
/// Similarity is computed as `1.0 - cosine_distance`.
///
/// # Arguments
///
/// * `collective_id` - The collective to search within
/// * `query` - Query embedding vector (must match collective's dimension)
/// * `k` - Maximum number of results to return (1-1000)
///
/// # Errors
///
/// - [`ValidationError::InvalidField`] if `k` is 0 or > 1000
/// - [`ValidationError::DimensionMismatch`] if `query.len()` doesn't match
/// the collective's embedding dimension
/// - [`NotFoundError::Collective`] if the collective doesn't exist
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let collective_id = db.create_collective("example")?;
/// let query = vec![0.1f32; 384]; // Your query embedding
/// let results = db.search_similar(collective_id, &query, 10)?;
/// for result in &results {
/// println!(
/// "[{:.3}] {}",
/// result.similarity, result.experience.content
/// );
/// }
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, query))]
pub fn search_similar(
&self,
collective_id: CollectiveId,
query: &[f32],
k: usize,
) -> Result<Vec<SearchResult>> {
self.search_similar_filtered(collective_id, query, k, SearchFilter::default())
}
/// Searches for experiences with optional recall weighting.
///
/// This is the forward-compatible search entry for VS-3.5.2. When the
/// resolved energy weight is zero, it delegates to the unchanged legacy
/// similarity path. Positive energy weights over-fetch vector candidates,
/// blend similarity with temporal energy, then sort and truncate.
///
/// # Arguments
///
/// * `collective_id` - The collective to search within
/// * `query` - Query embedding vector (must match collective's dimension)
/// * `options` - Result limit, filter, and optional recall weights
///
/// # Errors
///
/// - [`ValidationError::InvalidField`] if request weights are invalid
/// - [`ValidationError::DimensionMismatch`] if `query.len()` doesn't match
/// the collective's embedding dimension
/// - Legacy search errors from [`search_similar_filtered`](Self::search_similar_filtered)
#[instrument(skip(self, query, options))]
pub fn search(
&self,
collective_id: CollectiveId,
query: &[f32],
options: SearchOptions,
) -> Result<Vec<SearchResult>> {
// Effective per-collective decay config: a stored per-collective override
// wins; otherwise fall back to the global `Config.decay` — matching the
// record/energy reads elsewhere. This also honors the documented global
// `Config.decay.default_recall_weights` for collectives with no stored
// override (PR #23 review; precedence stored > global > none, relates to #16).
let decay_config = self
.storage
.get_decay_config(collective_id)?
.unwrap_or_else(|| self.config.decay.clone());
let collective_default =
decay_config.default_recall_weights.filter(|weights| {
match weights.validate("decay.default_recall_weights") {
Ok(()) => true,
Err(error) => {
warn!(
?error,
"ignoring invalid default_recall_weights (issue #14)"
);
false
}
}
});
let effective = resolve_recall_weights(options.weights, collective_default)?;
if is_legacy_recall(effective) {
return self.search_similar_filtered(collective_id, query, options.k, options.filter);
}
let weights = effective.expect("non-legacy recall implies weights are present");
self.search_similar_weighted(
collective_id,
query,
options.k,
options.filter,
weights,
decay_config,
)
}
fn search_similar_weighted(
&self,
collective_id: CollectiveId,
query: &[f32],
k: usize,
filter: SearchFilter,
weights: RecallWeights,
decay_config: DecayConfig,
) -> Result<Vec<SearchResult>> {
if k == 0 || k > 1000 {
return Err(ValidationError::invalid_field("k", "must be between 1 and 1000").into());
}
let collective = self
.storage
.get_collective(collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(collective_id)))?;
let expected_dim = collective.embedding_dimension as usize;
if query.len() != expected_dim {
return Err(ValidationError::dimension_mismatch(expected_dim, query.len()).into());
}
let over_fetch = std::cmp::max(k.saturating_mul(4), k.saturating_add(16)).min(2000);
let ef_search = self.config.hnsw.ef_search.max(over_fetch);
let now = Timestamp::now();
let candidates = self
.with_vector_index(collective_id, |index| {
index.search_experiences(query, over_fetch, ef_search)
})?
.unwrap_or_default();
let mut scored = Vec::with_capacity(candidates.len());
for (exp_id, distance) in candidates {
if let Some(experience) = self.storage.get_experience(exp_id)? {
if filter.matches(&experience) {
let similarity = 1.0 - distance;
let energy = experience_energy(
experience.importance,
experience.applications(),
experience.last_reinforced,
now,
&decay_config,
);
let score = rerank::blend_score(similarity, energy, weights);
scored.push((
SearchResult {
experience,
similarity,
},
score,
));
}
}
}
Ok(rerank::rerank(scored, k))
}
/// Searches for semantically similar experiences with additional filtering.
///
/// Like [`search_similar()`](Self::search_similar), but applies additional
/// filters on domain, experience type, importance, confidence, and timestamp.
///
/// Over-fetches from the HNSW index (2x `k`) to account for entries removed
/// by post-filtering, then truncates to the requested `k`.
///
/// # Arguments
///
/// * `collective_id` - The collective to search within
/// * `query` - Query embedding vector (must match collective's dimension)
/// * `k` - Maximum number of results to return (1-1000)
/// * `filter` - Filter criteria to apply after vector search
///
/// # Errors
///
/// - [`ValidationError::InvalidField`] if `k` is 0 or > 1000
/// - [`ValidationError::DimensionMismatch`] if `query.len()` doesn't match
/// the collective's embedding dimension
/// - [`NotFoundError::Collective`] if the collective doesn't exist
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let collective_id = db.create_collective("example")?;
/// # let query_embedding = vec![0.1f32; 384];
/// use pulsedb::SearchFilter;
///
/// let filter = SearchFilter {
/// domains: Some(vec!["rust".to_string()]),
/// min_importance: Some(0.5),
/// ..SearchFilter::default()
/// };
/// let results = db.search_similar_filtered(
/// collective_id,
/// &query_embedding,
/// 10,
/// filter,
/// )?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, query, filter))]
pub fn search_similar_filtered(
&self,
collective_id: CollectiveId,
query: &[f32],
k: usize,
filter: SearchFilter,
) -> Result<Vec<SearchResult>> {
// Validate k
if k == 0 || k > 1000 {
return Err(ValidationError::invalid_field("k", "must be between 1 and 1000").into());
}
// Verify collective exists and check embedding dimension
let collective = self
.storage
.get_collective(collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(collective_id)))?;
let expected_dim = collective.embedding_dimension as usize;
if query.len() != expected_dim {
return Err(ValidationError::dimension_mismatch(expected_dim, query.len()).into());
}
// Over-fetch from HNSW to compensate for post-filtering losses
let over_fetch = k.saturating_mul(2).min(2000);
let ef_search = self.config.hnsw.ef_search;
// Search HNSW index — returns (ExperienceId, cosine_distance) sorted
// by distance ascending (closest first)
let candidates = self
.with_vector_index(collective_id, |index| {
index.search_experiences(query, over_fetch, ef_search)
})?
.unwrap_or_default();
// Fetch full experiences, apply filter, convert distance → similarity
let mut results = Vec::with_capacity(k);
for (exp_id, distance) in candidates {
if results.len() >= k {
break;
}
if let Some(experience) = self.storage.get_experience(exp_id)? {
if filter.matches(&experience) {
results.push(SearchResult {
experience,
similarity: 1.0 - distance,
});
}
}
}
Ok(results)
}
// =========================================================================
// Experience Relations (E3-S01)
// =========================================================================
/// Stores a new relation between two experiences.
///
/// Relations are typed, directed edges connecting a source experience to a
/// target experience. Both experiences must exist and belong to the same
/// collective. Duplicate relations (same source, target, and type) are
/// rejected.
///
/// # Arguments
///
/// * `relation` - The relation to create (source, target, type, strength)
///
/// # Errors
///
/// Returns an error if:
/// - Source or target experience doesn't exist ([`NotFoundError::Experience`])
/// - Experiences belong to different collectives ([`ValidationError::InvalidField`])
/// - A relation with the same (source, target, type) already exists
/// - Self-relation attempted (source == target)
/// - Strength is out of range `[0.0, 1.0]`
#[instrument(skip(self, relation))]
pub fn store_relation(
&self,
relation: crate::relation::NewExperienceRelation,
) -> Result<crate::types::RelationId> {
self.check_writable()?;
use crate::relation::{validate_new_relation, ExperienceRelation};
use crate::types::RelationId;
// Validate input fields (self-relation, strength bounds, metadata size)
validate_new_relation(&relation)?;
// Load source and target experiences to verify existence
let source = self
.storage
.get_experience(relation.source_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::experience(relation.source_id)))?;
let target = self
.storage
.get_experience(relation.target_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::experience(relation.target_id)))?;
// Verify same collective
if source.collective_id != target.collective_id {
return Err(PulseDBError::from(ValidationError::invalid_field(
"target_id",
"source and target experiences must belong to the same collective",
)));
}
// Check for duplicate (same source, target, type)
if self.storage.relation_exists(
relation.source_id,
relation.target_id,
relation.relation_type,
)? {
return Err(PulseDBError::from(ValidationError::invalid_field(
"relation_type",
"a relation with this source, target, and type already exists",
)));
}
// Construct the full relation
let id = RelationId::new();
let full_relation = ExperienceRelation {
id,
source_id: relation.source_id,
target_id: relation.target_id,
relation_type: relation.relation_type,
strength: relation.strength,
metadata: relation.metadata,
created_at: Timestamp::now(),
};
self.storage.save_relation(&full_relation)?;
info!(
id = %id,
source = %relation.source_id,
target = %relation.target_id,
relation_type = ?full_relation.relation_type,
"Relation stored"
);
Ok(id)
}
/// Retrieves experiences related to the given experience.
///
/// Returns pairs of `(Experience, ExperienceRelation)` based on the
/// requested direction:
/// - `Outgoing`: experiences that this experience points TO (as source)
/// - `Incoming`: experiences that point TO this experience (as target)
/// - `Both`: union of outgoing and incoming
///
/// To filter by relation type, use
/// [`get_related_experiences_filtered`](Self::get_related_experiences_filtered).
///
/// Silently skips relations where the related experience no longer exists
/// (orphan tolerance).
///
/// # Errors
///
/// Returns a storage error if the read transaction fails.
#[instrument(skip(self))]
pub fn get_related_experiences(
&self,
experience_id: ExperienceId,
direction: crate::relation::RelationDirection,
) -> Result<Vec<(Experience, crate::relation::ExperienceRelation)>> {
self.get_related_experiences_filtered(experience_id, direction, None)
}
/// Retrieves experiences related to the given experience, with optional
/// type filtering.
///
/// Like [`get_related_experiences()`](Self::get_related_experiences), but
/// accepts an optional [`RelationType`](crate::RelationType) filter.
/// When `Some(rt)`, only relations matching that type are returned.
///
/// # Arguments
///
/// * `experience_id` - The experience to query relations for
/// * `direction` - Which direction(s) to traverse
/// * `relation_type` - If `Some`, only return relations of this type
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let cid = db.create_collective("example")?;
/// # let exp_a = db.record_experience(pulsedb::NewExperience {
/// # collective_id: cid,
/// # content: "a".into(),
/// # embedding: Some(vec![0.1f32; 384]),
/// # ..Default::default()
/// # })?;
/// use pulsedb::{RelationType, RelationDirection};
///
/// // Only "Supports" relations outgoing from exp_a
/// let supports = db.get_related_experiences_filtered(
/// exp_a,
/// RelationDirection::Outgoing,
/// Some(RelationType::Supports),
/// )?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self))]
pub fn get_related_experiences_filtered(
&self,
experience_id: ExperienceId,
direction: crate::relation::RelationDirection,
relation_type: Option<crate::relation::RelationType>,
) -> Result<Vec<(Experience, crate::relation::ExperienceRelation)>> {
use crate::relation::RelationDirection;
let mut results = Vec::new();
// Outgoing: this experience is the source → fetch target experiences
if matches!(
direction,
RelationDirection::Outgoing | RelationDirection::Both
) {
let rel_ids = self.storage.get_relation_ids_by_source(experience_id)?;
for rel_id in rel_ids {
if let Some(relation) = self.storage.get_relation(rel_id)? {
if relation_type.is_some_and(|rt| rt != relation.relation_type) {
continue;
}
if let Some(experience) = self.storage.get_experience(relation.target_id)? {
results.push((experience, relation));
}
}
}
}
// Incoming: this experience is the target → fetch source experiences
if matches!(
direction,
RelationDirection::Incoming | RelationDirection::Both
) {
let rel_ids = self.storage.get_relation_ids_by_target(experience_id)?;
for rel_id in rel_ids {
if let Some(relation) = self.storage.get_relation(rel_id)? {
if relation_type.is_some_and(|rt| rt != relation.relation_type) {
continue;
}
if let Some(experience) = self.storage.get_experience(relation.source_id)? {
results.push((experience, relation));
}
}
}
}
Ok(results)
}
/// Retrieves a relation by ID.
///
/// Returns `None` if no relation with the given ID exists.
pub fn get_relation(
&self,
id: crate::types::RelationId,
) -> Result<Option<crate::relation::ExperienceRelation>> {
self.storage.get_relation(id)
}
/// Deletes a relation by ID.
///
/// # Errors
///
/// Returns [`NotFoundError::Relation`] if no relation with the given ID exists.
#[instrument(skip(self))]
pub fn delete_relation(&self, id: crate::types::RelationId) -> Result<()> {
self.check_writable()?;
let deleted = self.storage.delete_relation(id)?;
if !deleted {
return Err(PulseDBError::from(NotFoundError::relation(id)));
}
info!(id = %id, "Relation deleted");
Ok(())
}
// =========================================================================
// Derived Insights (E3-S02)
// =========================================================================
/// Stores a new derived insight.
///
/// Creates a synthesized knowledge record from multiple source experiences.
/// The method:
/// 1. Validates the input (content, confidence, sources)
/// 2. Verifies the collective exists
/// 3. Verifies all source experiences exist and belong to the same collective
/// 4. Resolves the embedding (generates if Builtin, requires if External)
/// 5. Stores the insight with inline embedding
/// 6. Inserts into the insight HNSW index
///
/// # Arguments
///
/// * `insight` - The insight to store (see [`NewDerivedInsight`])
///
/// # Errors
///
/// - [`ValidationError`](crate::ValidationError) if input is invalid
/// - [`NotFoundError::Collective`] if the collective doesn't exist
/// - [`NotFoundError::Experience`] if any source experience doesn't exist
/// - [`ValidationError::InvalidField`] if source experiences belong to
/// different collectives
/// - [`ValidationError::DimensionMismatch`] if embedding dimension is wrong
#[instrument(skip(self, insight), fields(collective_id = %insight.collective_id))]
pub fn store_insight(&self, insight: NewDerivedInsight) -> Result<InsightId> {
self.check_writable()?;
let is_external = matches!(self.config.embedding_provider, EmbeddingProvider::External);
// Validate input fields
validate_new_insight(&insight)?;
// Verify collective exists
let collective = self
.storage
.get_collective(insight.collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(insight.collective_id)))?;
// Verify all source experiences exist and belong to this collective
for source_id in &insight.source_experience_ids {
let source_exp = self
.storage
.get_experience(*source_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::experience(*source_id)))?;
if source_exp.collective_id != insight.collective_id {
return Err(PulseDBError::from(ValidationError::invalid_field(
"source_experience_ids",
format!(
"experience {} belongs to collective {}, not {}",
source_id, source_exp.collective_id, insight.collective_id
),
)));
}
}
// Resolve embedding
let embedding = match insight.embedding {
Some(ref emb) => {
// Validate dimension
let expected_dim = collective.embedding_dimension as usize;
if emb.len() != expected_dim {
return Err(ValidationError::dimension_mismatch(expected_dim, emb.len()).into());
}
emb.clone()
}
None => {
if is_external {
return Err(PulseDBError::embedding(
"embedding is required when using External embedding provider",
));
}
self.embedding.embed(&insight.content)?
}
};
let embedding_for_hnsw = embedding.clone();
let now = Timestamp::now();
let id = InsightId::new();
// Construct the full insight record
let derived_insight = DerivedInsight {
id,
collective_id: insight.collective_id,
content: insight.content,
embedding,
source_experience_ids: insight.source_experience_ids,
insight_type: insight.insight_type,
confidence: insight.confidence,
domain: insight.domain,
created_at: now,
updated_at: now,
};
// Write to redb FIRST (source of truth)
self.storage.save_insight(&derived_insight)?;
// Insert into insight HNSW index (using InsightId→ExperienceId byte conversion)
let exp_id = ExperienceId::from_bytes(*id.as_bytes());
let insight_vectors = self
.insight_vectors
.read()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?;
if let Some(index) = insight_vectors.get(&insight.collective_id) {
index.insert_experience(exp_id, &embedding_for_hnsw)?;
}
info!(id = %id, "Insight stored");
Ok(id)
}
/// Retrieves a derived insight by ID.
///
/// Returns `None` if no insight with the given ID exists.
#[instrument(skip(self))]
pub fn get_insight(&self, id: InsightId) -> Result<Option<DerivedInsight>> {
self.storage.get_insight(id)
}
/// Searches for insights semantically similar to the query embedding.
///
/// Uses the insight-specific HNSW index for approximate nearest neighbor
/// search, then fetches full insight records from storage.
///
/// # Arguments
///
/// * `collective_id` - The collective to search within
/// * `query` - Query embedding vector (must match collective's dimension)
/// * `k` - Maximum number of results to return
///
/// # Errors
///
/// - [`ValidationError::DimensionMismatch`] if `query.len()` doesn't match
/// - [`NotFoundError::Collective`] if the collective doesn't exist
#[instrument(skip(self, query))]
pub fn get_insights(
&self,
collective_id: CollectiveId,
query: &[f32],
k: usize,
) -> Result<Vec<(DerivedInsight, f32)>> {
// Verify collective exists and check embedding dimension
let collective = self
.storage
.get_collective(collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(collective_id)))?;
let expected_dim = collective.embedding_dimension as usize;
if query.len() != expected_dim {
return Err(ValidationError::dimension_mismatch(expected_dim, query.len()).into());
}
let ef_search = self.config.hnsw.ef_search;
// Search insight HNSW — returns (ExperienceId, distance) pairs
let insight_vectors = self
.insight_vectors
.read()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?;
let candidates = match insight_vectors.get(&collective_id) {
Some(index) => index.search_experiences(query, k, ef_search)?,
None => return Ok(vec![]),
};
drop(insight_vectors);
// Convert ExperienceId back to InsightId and fetch records
let mut results = Vec::with_capacity(candidates.len());
for (exp_id, distance) in candidates {
let insight_id = InsightId::from_bytes(*exp_id.as_bytes());
if let Some(insight) = self.storage.get_insight(insight_id)? {
// Convert HNSW distance to similarity (1.0 - distance), matching search_similar pattern
results.push((insight, 1.0 - distance));
}
}
Ok(results)
}
/// Deletes a derived insight by ID.
///
/// Removes the insight from storage and soft-deletes it from the HNSW index.
///
/// # Errors
///
/// Returns [`NotFoundError::Insight`] if no insight with the given ID exists.
#[instrument(skip(self))]
pub fn delete_insight(&self, id: InsightId) -> Result<()> {
self.check_writable()?;
// Read insight first to get collective_id for HNSW lookup
let insight = self
.storage
.get_insight(id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::insight(id)))?;
// Delete from redb FIRST (source of truth)
self.storage.delete_insight(id)?;
// Soft-delete from insight HNSW (using InsightId→ExperienceId byte conversion)
let exp_id = ExperienceId::from_bytes(*id.as_bytes());
let insight_vectors = self
.insight_vectors
.read()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?;
if let Some(index) = insight_vectors.get(&insight.collective_id) {
index.delete_experience(exp_id)?;
}
info!(id = %id, "Insight deleted");
Ok(())
}
// =========================================================================
// Activity Tracking (E3-S03)
// =========================================================================
/// Registers an agent's presence in a collective.
///
/// Creates a new activity record or replaces an existing one for the
/// same `(collective_id, agent_id)` pair (upsert semantics). Both
/// `started_at` and `last_heartbeat` are set to `Timestamp::now()`.
///
/// # Arguments
///
/// * `activity` - The activity registration (see [`NewActivity`])
///
/// # Errors
///
/// - [`ValidationError`] if agent_id is empty or fields exceed size limits
/// - [`NotFoundError::Collective`] if the collective doesn't exist
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let collective_id = db.create_collective("example")?;
/// use pulsedb::NewActivity;
///
/// db.register_activity(NewActivity {
/// agent_id: "claude-opus".to_string(),
/// collective_id,
/// current_task: Some("Reviewing pull request".to_string()),
/// context_summary: None,
/// })?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, activity), fields(agent_id = %activity.agent_id, collective_id = %activity.collective_id))]
pub fn register_activity(&self, activity: NewActivity) -> Result<()> {
// Validate input
validate_new_activity(&activity)?;
// Verify collective exists
self.storage
.get_collective(activity.collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(activity.collective_id)))?;
// Build stored activity with timestamps
let now = Timestamp::now();
let stored = Activity {
agent_id: activity.agent_id,
collective_id: activity.collective_id,
current_task: activity.current_task,
context_summary: activity.context_summary,
started_at: now,
last_heartbeat: now,
};
self.storage.save_activity(&stored)?;
info!(
agent_id = %stored.agent_id,
collective_id = %stored.collective_id,
"Activity registered"
);
Ok(())
}
/// Updates an agent's heartbeat timestamp.
///
/// Refreshes the `last_heartbeat` to `Timestamp::now()` without changing
/// any other fields. The agent must have an existing activity registered.
///
/// # Errors
///
/// - [`NotFoundError::Activity`] if no activity exists for the agent/collective pair
#[instrument(skip(self))]
pub fn update_heartbeat(&self, agent_id: &str, collective_id: CollectiveId) -> Result<()> {
self.check_writable()?;
let mut activity = self
.storage
.get_activity(agent_id, collective_id)?
.ok_or_else(|| {
PulseDBError::from(NotFoundError::activity(format!(
"{} in {}",
agent_id, collective_id
)))
})?;
activity.last_heartbeat = Timestamp::now();
self.storage.save_activity(&activity)?;
info!(agent_id = %agent_id, collective_id = %collective_id, "Heartbeat updated");
Ok(())
}
/// Ends an agent's activity in a collective.
///
/// Removes the activity record. After calling this, the agent will no
/// longer appear in `get_active_agents()` results.
///
/// # Errors
///
/// - [`NotFoundError::Activity`] if no activity exists for the agent/collective pair
#[instrument(skip(self))]
pub fn end_activity(&self, agent_id: &str, collective_id: CollectiveId) -> Result<()> {
let deleted = self.storage.delete_activity(agent_id, collective_id)?;
if !deleted {
return Err(PulseDBError::from(NotFoundError::activity(format!(
"{} in {}",
agent_id, collective_id
))));
}
info!(agent_id = %agent_id, collective_id = %collective_id, "Activity ended");
Ok(())
}
/// Returns all active (non-stale) agents in a collective.
///
/// Fetches all activities, filters out those whose `last_heartbeat` is
/// older than `config.activity.stale_threshold`, and returns the rest
/// sorted by `last_heartbeat` descending (most recently active first).
///
/// # Errors
///
/// - [`NotFoundError::Collective`] if the collective doesn't exist
#[instrument(skip(self))]
pub fn get_active_agents(&self, collective_id: CollectiveId) -> Result<Vec<Activity>> {
// Verify collective exists
self.storage
.get_collective(collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(collective_id)))?;
let all_activities = self.storage.list_activities_in_collective(collective_id)?;
// Filter stale activities
let now = Timestamp::now();
let threshold_ms = self.config.activity.stale_threshold.as_millis() as i64;
let cutoff = now.as_millis() - threshold_ms;
let mut active: Vec<Activity> = all_activities
.into_iter()
.filter(|a| a.last_heartbeat.as_millis() >= cutoff)
.collect();
// Sort by last_heartbeat descending (most recently active first)
active.sort_by_key(|a| std::cmp::Reverse(a.last_heartbeat));
Ok(active)
}
// =========================================================================
// Context Candidates (E2-S04)
// =========================================================================
/// Retrieves unified context candidates from all retrieval primitives.
///
/// This is the primary API for context assembly. It orchestrates:
/// 1. Similarity search ([`search_similar_filtered`](Self::search_similar_filtered))
/// 2. Recent experiences ([`get_recent_experiences_filtered`](Self::get_recent_experiences_filtered))
/// 3. Insight search ([`get_insights`](Self::get_insights)) — if requested
/// 4. Relation collection ([`get_related_experiences`](Self::get_related_experiences)) — if requested
/// 5. Active agents ([`get_active_agents`](Self::get_active_agents)) — if requested
///
/// # Arguments
///
/// * `request` - Configuration for which primitives to query and limits
///
/// # Errors
///
/// - [`ValidationError::InvalidField`] if `max_similar` or `max_recent` is 0 or > 1000
/// - [`ValidationError::DimensionMismatch`] if `query_embedding.len()` doesn't match
/// the collective's embedding dimension
/// - [`NotFoundError::Collective`] if the collective doesn't exist
///
/// # Performance
///
/// Target: < 100ms at 100K experiences. The similarity search (~50ms) dominates;
/// all other sub-calls are < 10ms each.
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let collective_id = db.create_collective("example")?;
/// # let query_vec = vec![0.1f32; 384];
/// use pulsedb::{ContextRequest, SearchFilter};
///
/// let candidates = db.get_context_candidates(ContextRequest {
/// collective_id,
/// query_embedding: query_vec,
/// max_similar: 10,
/// max_recent: 5,
/// include_insights: true,
/// include_relations: true,
/// include_active_agents: true,
/// filter: SearchFilter {
/// domains: Some(vec!["rust".to_string()]),
/// ..SearchFilter::default()
/// },
/// ..ContextRequest::default()
/// })?;
/// # Ok(())
/// # }
/// ```
#[instrument(skip(self, request), fields(collective_id = %request.collective_id))]
pub fn get_context_candidates(&self, request: ContextRequest) -> Result<ContextCandidates> {
// ── Validate limits ──────────────────────────────────────
if request.max_similar == 0 || request.max_similar > 1000 {
return Err(ValidationError::invalid_field(
"max_similar",
"must be between 1 and 1000",
)
.into());
}
if request.max_recent == 0 || request.max_recent > 1000 {
return Err(
ValidationError::invalid_field("max_recent", "must be between 1 and 1000").into(),
);
}
// ── Verify collective exists and check dimension ─────────
let collective = self
.storage
.get_collective(request.collective_id)?
.ok_or_else(|| PulseDBError::from(NotFoundError::collective(request.collective_id)))?;
let expected_dim = collective.embedding_dimension as usize;
if request.query_embedding.len() != expected_dim {
return Err(ValidationError::dimension_mismatch(
expected_dim,
request.query_embedding.len(),
)
.into());
}
// ── 1. Similar experiences (HNSW vector search) ──────────
let similar_experiences = self.search(
request.collective_id,
&request.query_embedding,
SearchOptions {
k: request.max_similar,
filter: request.filter.clone(),
weights: request.recall_weights,
},
)?;
// ── 2. Recent experiences (timestamp index scan) ─────────
let recent_experiences = self.get_recent_experiences_filtered(
request.collective_id,
request.max_recent,
request.filter,
)?;
// ── 3. Insights (HNSW vector search on insight index) ────
let insights = if request.include_insights {
self.get_insights(
request.collective_id,
&request.query_embedding,
request.max_similar,
)?
.into_iter()
.map(|(insight, _score)| insight)
.collect()
} else {
vec![]
};
// ── 4. Relations (graph traversal from result experiences) ─
let relations = if request.include_relations {
use std::collections::HashSet;
let mut seen = HashSet::new();
let mut all_relations = Vec::new();
// Collect unique experience IDs from both result sets
let exp_ids: Vec<_> = similar_experiences
.iter()
.map(|r| r.experience.id)
.chain(recent_experiences.iter().map(|e| e.id))
.collect();
for exp_id in exp_ids {
let related =
self.get_related_experiences(exp_id, crate::relation::RelationDirection::Both)?;
for (_experience, relation) in related {
if seen.insert(relation.id) {
all_relations.push(relation);
}
}
}
all_relations
} else {
vec![]
};
// ── 5. Active agents (staleness-filtered activity records) ─
let active_agents = if request.include_active_agents {
self.get_active_agents(request.collective_id)?
} else {
vec![]
};
Ok(ContextCandidates {
similar_experiences,
recent_experiences,
insights,
relations,
active_agents,
})
}
/// Inserts a backdated experience fixture into storage and the vector index.
#[cfg(test)]
pub(crate) fn insert_experience_backdated(
&self,
collective_id: CollectiveId,
content: &str,
embedding: Vec<f32>,
importance: f32,
applications: BTreeMap<crate::types::InstanceId, u32>,
last_reinforced: Timestamp,
) -> Result<ExperienceId> {
self.check_writable()?;
let embedding_for_hnsw = embedding.clone();
let now = Timestamp::now();
let experience = Experience {
id: ExperienceId::new(),
collective_id,
content: content.to_string(),
embedding,
experience_type: crate::experience::ExperienceType::default(),
importance,
confidence: 0.8,
applications,
domain: vec![],
related_files: vec![],
source_agent: crate::types::AgentId::new("test"),
source_task: None,
timestamp: now,
last_reinforced,
archived: false,
};
let id = experience.id;
self.storage.save_experience(&experience)?;
let vectors = self
.vectors
.read()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?;
let index = vectors
.get(&collective_id)
.ok_or_else(|| PulseDBError::vector("HNSW index missing for collective"))?;
index.insert_experience(id, &embedding_for_hnsw)?;
Ok(id)
}
/// Stores a collective decay config fixture for tests.
#[cfg(test)]
pub(crate) fn set_decay_config_for_test(
&self,
collective_id: CollectiveId,
config: DecayConfig,
) -> Result<()> {
self.storage.set_decay_config(collective_id, config)
}
// =========================================================================
// Watch System (E4-S01)
// =========================================================================
/// Subscribes to all experience changes in a collective.
///
/// Returns a [`WatchStream`] that yields [`WatchEvent`] values for every
/// create, update, archive, and delete operation. The stream ends when
/// dropped or when the `PulseDB` instance is closed.
///
/// Multiple subscribers per collective are supported. Each gets an
/// independent copy of every event.
///
/// # Example
///
/// ```rust,no_run
/// # #[tokio::main]
/// # async fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let collective_id = db.create_collective("example")?;
/// use futures::StreamExt;
///
/// let mut stream = db.watch_experiences(collective_id)?;
/// while let Some(event) = stream.next().await {
/// println!("{:?}: {}", event.event_type, event.experience_id);
/// }
/// # Ok(())
/// # }
/// ```
pub fn watch_experiences(&self, collective_id: CollectiveId) -> Result<WatchStream> {
self.watch.subscribe(collective_id, None)
}
/// Subscribes to filtered experience changes in a collective.
///
/// Like [`watch_experiences`](Self::watch_experiences), but only delivers
/// events that match the filter criteria. Filters are applied on the
/// sender side before channel delivery.
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// # let collective_id = db.create_collective("example")?;
/// use pulsedb::WatchFilter;
///
/// let filter = WatchFilter {
/// domains: Some(vec!["security".to_string()]),
/// min_importance: Some(0.7),
/// ..Default::default()
/// };
/// let mut stream = db.watch_experiences_filtered(collective_id, filter)?;
/// # Ok(())
/// # }
/// ```
pub fn watch_experiences_filtered(
&self,
collective_id: CollectiveId,
filter: WatchFilter,
) -> Result<WatchStream> {
self.watch.subscribe(collective_id, Some(filter))
}
// =========================================================================
// Cross-Process Watch (E4-S02)
// =========================================================================
/// Returns the current WAL sequence number.
///
/// Use this to establish a baseline before starting to poll for changes.
/// Returns 0 if no experience writes have occurred yet.
///
/// # Example
///
/// ```rust
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// let seq = db.get_current_sequence()?;
/// // ... later ...
/// let (events, new_seq) = db.poll_changes(seq)?;
/// # Ok(())
/// # }
/// ```
pub fn get_current_sequence(&self) -> Result<u64> {
self.storage.get_wal_sequence()
}
/// Polls for experience changes since the given sequence number.
///
/// Returns a tuple of `(events, new_sequence)`:
/// - `events`: New [`WatchEvent`]s in sequence order
/// - `new_sequence`: Pass this value back on the next call
///
/// Returns an empty vec and the same sequence if no changes exist.
///
/// # Arguments
///
/// * `since_seq` - The last sequence number you received (0 for first call)
///
/// # Performance
///
/// Target: < 10ms per call. Internally performs a range scan on the
/// watch_events table, O(k) where k is the number of new events.
///
/// # Example
///
/// ```rust,no_run
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// use std::time::Duration;
///
/// let mut seq = 0u64;
/// loop {
/// let (events, new_seq) = db.poll_changes(seq)?;
/// seq = new_seq;
/// for event in events {
/// println!("{:?}: {}", event.event_type, event.experience_id);
/// }
/// std::thread::sleep(Duration::from_millis(100));
/// }
/// # }
/// ```
pub fn poll_changes(&self, since_seq: u64) -> Result<(Vec<WatchEvent>, u64)> {
use crate::storage::schema::EntityTypeTag;
let (records, new_seq) = self.storage.poll_watch_events(since_seq, 1000)?;
let events = records
.into_iter()
.filter(|r| r.entity_type == EntityTypeTag::Experience)
.map(WatchEvent::from)
.collect();
Ok((events, new_seq))
}
/// Polls for changes with a custom batch size limit.
///
/// Same as [`poll_changes`](Self::poll_changes) but returns at most
/// `limit` events per call. Use this for backpressure control.
pub fn poll_changes_batch(
&self,
since_seq: u64,
limit: usize,
) -> Result<(Vec<WatchEvent>, u64)> {
use crate::storage::schema::EntityTypeTag;
let (records, new_seq) = self.storage.poll_watch_events(since_seq, limit)?;
let events = records
.into_iter()
.filter(|r| r.entity_type == EntityTypeTag::Experience)
.map(WatchEvent::from)
.collect();
Ok((events, new_seq))
}
// =========================================================================
// Sync WAL Compaction (feature: sync)
// =========================================================================
/// Compacts the WAL by removing events that all peers have already synced.
///
/// Finds the minimum cursor across all known peers and deletes WAL events
/// up to that sequence. If no peers exist, no compaction occurs (events
/// may be needed when a peer connects later).
///
/// Call this periodically (e.g., daily) to reclaim disk space.
/// Returns the number of WAL events deleted.
///
/// # Example
///
/// ```rust,no_run
/// # fn main() -> pulsedb::Result<()> {
/// # let dir = tempfile::tempdir().unwrap();
/// # let db = pulsedb::PulseDB::open(dir.path().join("test.db"), pulsedb::Config::default())?;
/// let deleted = db.compact_wal()?;
/// println!("Compacted {} WAL events", deleted);
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "sync")]
pub fn compact_wal(&self) -> Result<u64> {
let cursors = self
.storage
.list_sync_cursors()
.map_err(|e| PulseDBError::internal(format!("Failed to list sync cursors: {}", e)))?;
if cursors.is_empty() {
// No peers — don't compact (events may be needed later)
return Ok(0);
}
let min_seq = cursors.iter().map(|c| c.last_sequence).min().unwrap_or(0);
if min_seq == 0 {
return Ok(0);
}
let deleted = self.storage.compact_wal_events(min_seq)?;
info!(deleted, min_seq, "WAL compacted");
Ok(deleted)
}
// =========================================================================
// Sync Apply Methods (feature: sync)
// =========================================================================
//
// These methods apply remote changes received via sync. They bypass
// validation and embedding generation (data was validated on the source).
// WAL recording is suppressed by the SyncApplyGuard (entered by the caller).
// Watch emit is skipped (no in-process notifications for sync changes).
//
// These are pub(crate) and will be called by the sync applier in Phase 3.
/// Applies a synced experience from a remote peer.
///
/// Writes the full experience to storage and inserts into HNSW.
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
#[allow(dead_code)] // Called by sync applier (Phase 3)
pub fn apply_synced_experience(&self, experience: Experience) -> Result<()> {
let collective_id = experience.collective_id;
let id = experience.id;
let embedding = experience.embedding.clone();
self.storage.save_experience(&experience)?;
// Insert into HNSW index
let vectors = self
.vectors
.read()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?;
if let Some(index) = vectors.get(&collective_id) {
index.insert_experience(id, &embedding)?;
}
debug!(id = %id, "Synced experience applied");
Ok(())
}
/// Applies a synced experience update from a remote peer.
///
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
#[allow(dead_code)] // Called by sync applier (Phase 3)
pub fn apply_synced_experience_update(
&self,
id: ExperienceId,
update: ExperienceUpdate,
) -> Result<()> {
self.storage.update_experience(id, &update)?;
debug!(id = %id, "Synced experience update applied");
Ok(())
}
/// Merges synced G-counter reinforcement fields from a remote peer.
///
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
pub(crate) fn apply_synced_experience_counter_merge(
&self,
id: ExperienceId,
applications: &BTreeMap<InstanceId, u32>,
last_reinforced: Option<Timestamp>,
) -> Result<bool> {
let merged =
self.storage
.merge_experience_applications(id, applications, last_reinforced)?;
if merged {
debug!(id = %id, "Synced experience counter merge applied");
}
Ok(merged)
}
/// Applies a synced experience deletion from a remote peer.
///
/// Removes from storage and soft-deletes from HNSW.
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
#[allow(dead_code)] // Called by sync applier (Phase 3)
pub fn apply_synced_experience_delete(&self, id: ExperienceId) -> Result<()> {
// Get collective_id for HNSW lookup before deleting
if let Some(exp) = self.storage.get_experience(id)? {
let collective_id = exp.collective_id;
// Cascade delete relations
self.storage.delete_relations_for_experience(id)?;
self.storage.delete_experience(id)?;
// Soft-delete from HNSW
let vectors = self
.vectors
.read()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?;
if let Some(index) = vectors.get(&collective_id) {
index.delete_experience(id)?;
}
}
debug!(id = %id, "Synced experience delete applied");
Ok(())
}
/// Applies a synced relation from a remote peer.
///
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
#[allow(dead_code)] // Called by sync applier (Phase 3)
pub fn apply_synced_relation(&self, relation: ExperienceRelation) -> Result<()> {
let id = relation.id;
self.storage.save_relation(&relation)?;
debug!(id = %id, "Synced relation applied");
Ok(())
}
/// Applies a synced relation deletion from a remote peer.
///
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
#[allow(dead_code)] // Called by sync applier (Phase 3)
pub fn apply_synced_relation_delete(&self, id: RelationId) -> Result<()> {
self.storage.delete_relation(id)?;
debug!(id = %id, "Synced relation delete applied");
Ok(())
}
/// Applies a synced insight from a remote peer.
///
/// Writes to storage and inserts into insight HNSW index.
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
#[allow(dead_code)] // Called by sync applier (Phase 3)
pub fn apply_synced_insight(&self, insight: DerivedInsight) -> Result<()> {
let id = insight.id;
let collective_id = insight.collective_id;
let embedding = insight.embedding.clone();
self.storage.save_insight(&insight)?;
// Insert into insight HNSW (using InsightId→ExperienceId byte conversion)
let exp_id = ExperienceId::from_bytes(*id.as_bytes());
let insight_vectors = self
.insight_vectors
.read()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?;
if let Some(index) = insight_vectors.get(&collective_id) {
index.insert_experience(exp_id, &embedding)?;
}
debug!(id = %id, "Synced insight applied");
Ok(())
}
/// Applies a synced insight deletion from a remote peer.
///
/// Removes from storage and soft-deletes from insight HNSW.
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
#[allow(dead_code)] // Called by sync applier (Phase 3)
pub fn apply_synced_insight_delete(&self, id: InsightId) -> Result<()> {
if let Some(insight) = self.storage.get_insight(id)? {
self.storage.delete_insight(id)?;
// Soft-delete from insight HNSW
let exp_id = ExperienceId::from_bytes(*id.as_bytes());
let insight_vectors = self
.insight_vectors
.read()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?;
if let Some(index) = insight_vectors.get(&insight.collective_id) {
index.delete_experience(exp_id)?;
}
}
debug!(id = %id, "Synced insight delete applied");
Ok(())
}
/// Applies a synced collective from a remote peer.
///
/// Writes to storage and creates HNSW indexes for the collective.
/// Caller must hold `SyncApplyGuard` to suppress WAL recording.
#[cfg(feature = "sync")]
#[allow(dead_code)] // Called by sync applier (Phase 3)
pub fn apply_synced_collective(&self, collective: Collective) -> Result<()> {
let id = collective.id;
let dimension = collective.embedding_dimension as usize;
self.storage.save_collective(&collective)?;
// Create HNSW indexes (same as create_collective)
let exp_index = crate::vector::HnswIndex::new(dimension, &self.config.hnsw);
let insight_index = crate::vector::HnswIndex::new(dimension, &self.config.hnsw);
self.vectors
.write()
.map_err(|_| PulseDBError::vector("Vectors lock poisoned"))?
.insert(id, exp_index);
self.insight_vectors
.write()
.map_err(|_| PulseDBError::vector("Insight vectors lock poisoned"))?
.insert(id, insight_index);
debug!(id = %id, "Synced collective applied");
Ok(())
}
}
// PulseDB is auto Send + Sync: Box<dyn StorageEngine + Send + Sync>,
// Box<dyn EmbeddingService + Send + Sync>, and Config are all Send + Sync.
#[cfg(test)]
mod tests {
use super::*;
use crate::config::EmbeddingDimension;
use tempfile::tempdir;
#[test]
fn test_open_creates_database() {
let dir = tempdir().unwrap();
let path = dir.path().join("test.db");
let db = PulseDB::open(&path, Config::default()).unwrap();
assert!(path.exists());
assert_eq!(db.embedding_dimension(), 384);
db.close().unwrap();
}
#[test]
fn test_open_existing_database() {
let dir = tempdir().unwrap();
let path = dir.path().join("test.db");
// Create
let db = PulseDB::open(&path, Config::default()).unwrap();
db.close().unwrap();
// Reopen
let db = PulseDB::open(&path, Config::default()).unwrap();
assert_eq!(db.embedding_dimension(), 384);
db.close().unwrap();
}
#[test]
fn test_config_validation() {
let dir = tempdir().unwrap();
let path = dir.path().join("test.db");
let invalid_config = Config {
cache_size_mb: 0, // Invalid
..Default::default()
};
let result = PulseDB::open(&path, invalid_config);
assert!(result.is_err());
}
#[test]
fn test_dimension_mismatch() {
let dir = tempdir().unwrap();
let path = dir.path().join("test.db");
// Create with D384
let db = PulseDB::open(
&path,
Config {
embedding_dimension: EmbeddingDimension::D384,
..Default::default()
},
)
.unwrap();
db.close().unwrap();
// Try to reopen with D768
let result = PulseDB::open(
&path,
Config {
embedding_dimension: EmbeddingDimension::D768,
..Default::default()
},
);
assert!(result.is_err());
}
#[test]
fn test_metadata_access() {
let dir = tempdir().unwrap();
let path = dir.path().join("test.db");
let db = PulseDB::open(&path, Config::default()).unwrap();
let metadata = db.metadata();
assert_eq!(metadata.embedding_dimension, EmbeddingDimension::D384);
db.close().unwrap();
}
#[test]
fn test_pulsedb_is_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<PulseDB>();
}
// =========================================================================
// list_cold_experiences — conservative-lifecycle surfacing (VS-3.5.3 / FR-034)
// =========================================================================
/// A 384-d embedding fixture (dimension must match the default D384 index).
fn cold_test_embedding() -> Vec<f32> {
let mut embedding = vec![0.0f32; 384];
embedding[0] = 1.0;
embedding
}
/// Backdates `last_reinforced` by `days` so the fixture decays well below
/// the default `floor` (0.05) under a 30-day half-life.
fn days_ago(days: i64) -> Timestamp {
Timestamp::from_millis(Timestamp::now().as_millis() - days * 24 * 60 * 60 * 1000)
}
/// Opens a default-config db with a single collective.
fn open_cold_fixture(name: &str) -> (tempfile::TempDir, PulseDB, CollectiveId) {
let dir = tempdir().unwrap();
let db = PulseDB::open(dir.path().join(format!("{name}.db")), Config::default()).unwrap();
let collective_id = db.create_collective(name).unwrap();
(dir, db, collective_id)
}
#[test]
fn list_cold_experiences_surfaces_below_floor() {
let (_dir, db, collective_id) = open_cold_fixture("cold-surfaces");
let floor = Config::default().decay.floor; // 0.05
// A cold experience: importance 0.9 last reinforced ~365 days ago decays
// far below the 0.05 floor under the default 30-day half-life.
let cold_id = db
.insert_experience_backdated(
collective_id,
"cold memory",
cold_test_embedding(),
0.9,
std::collections::BTreeMap::new(),
days_ago(365),
)
.unwrap();
// A warm experience: importance 0.9 reinforced now stays at ~0.9 (> floor).
let warm_id = db
.insert_experience_backdated(
collective_id,
"warm memory",
cold_test_embedding(),
0.9,
std::collections::BTreeMap::new(),
Timestamp::now(),
)
.unwrap();
let cold = db.list_cold_experiences(collective_id, floor, 100).unwrap();
// Only the cold experience is surfaced, with its energy reported.
assert_eq!(cold.len(), 1, "exactly one experience is below the floor");
assert_eq!(cold[0].0, cold_id, "the cold experience is surfaced");
assert!(
cold[0].1 < floor,
"reported energy {} is below floor {floor}",
cold[0].1
);
assert!(
!cold.iter().any(|(id, _)| *id == warm_id),
"the warm experience is not surfaced"
);
// Coldest-first ordering: add a second, even-colder experience and assert
// the result is sorted ascending by energy.
let colder_id = db
.insert_experience_backdated(
collective_id,
"even colder memory",
cold_test_embedding(),
0.1,
std::collections::BTreeMap::new(),
days_ago(365),
)
.unwrap();
let cold = db.list_cold_experiences(collective_id, floor, 100).unwrap();
assert_eq!(cold.len(), 2, "both cold experiences are surfaced");
assert!(
cold[0].1 <= cold[1].1,
"results are coldest-first (ascending energy): {:?}",
cold
);
assert_eq!(cold[0].0, colder_id, "the coldest experience comes first");
// limit/below validation: limit 0 and out-of-range `below` are rejected.
assert!(db.list_cold_experiences(collective_id, floor, 0).is_err());
assert!(db.list_cold_experiences(collective_id, 1.5, 100).is_err());
assert!(db
.list_cold_experiences(collective_id, f32::NAN, 100)
.is_err());
db.close().unwrap();
}
#[test]
fn cold_experience_not_auto_archived_by_default() {
// D3 invariant: under DEFAULT config, recording → searching → listing a
// cold experience NEVER flips `archived` — auto_archive_below_floor is
// inert (read by no actuator).
let (_dir, db, collective_id) = open_cold_fixture("auto-archive-off");
let floor = Config::default().decay.floor;
let cold_id = db
.insert_experience_backdated(
collective_id,
"cold-but-not-archived",
cold_test_embedding(),
0.9,
std::collections::BTreeMap::new(),
days_ago(365),
)
.unwrap();
// Freshly recorded: archived must be false.
assert!(
!db.storage
.get_experience(cold_id)
.unwrap()
.unwrap()
.archived,
"archived is false immediately after record"
);
// search: a query touching the collective must not flip archived.
let _ = db
.search_similar(collective_id, &cold_test_embedding(), 10)
.unwrap();
assert!(
!db.storage
.get_experience(cold_id)
.unwrap()
.unwrap()
.archived,
"archived is false after search"
);
// list_cold_experiences surfaces it but must NOT archive it.
let cold = db.list_cold_experiences(collective_id, floor, 100).unwrap();
assert!(
cold.iter().any(|(id, _)| *id == cold_id),
"the cold experience is surfaced"
);
assert!(
!db.storage
.get_experience(cold_id)
.unwrap()
.unwrap()
.archived,
"archived is STILL false after list_cold_experiences (no auto-archive)"
);
db.close().unwrap();
}
#[test]
fn list_cold_excludes_archived_experiences() {
// C5: an experience that is cold (E < below) AND already archived is
// EXCLUDED from the result (prune-eligible = cold and not yet archived).
let (_dir, db, collective_id) = open_cold_fixture("cold-excludes-archived");
let floor = Config::default().decay.floor;
// Two genuinely-cold experiences (both would match E < below).
let surfaced_id = db
.insert_experience_backdated(
collective_id,
"cold not archived",
cold_test_embedding(),
0.9,
std::collections::BTreeMap::new(),
days_ago(365),
)
.unwrap();
let archived_id = db
.insert_experience_backdated(
collective_id,
"cold already archived",
cold_test_embedding(),
0.9,
std::collections::BTreeMap::new(),
days_ago(365),
)
.unwrap();
// Non-vacuity guard: confirm BOTH are below the floor BEFORE archiving —
// so the exclusion below is genuinely the !archived filter at work, not a
// side-effect of the archived experience being warm.
let before = db.list_cold_experiences(collective_id, floor, 100).unwrap();
assert_eq!(
before.len(),
2,
"both cold experiences match E < below before archiving"
);
// Archive one of them — it now matches E < below but is archived.
db.archive_experience(archived_id).unwrap();
let after = db.list_cold_experiences(collective_id, floor, 100).unwrap();
assert_eq!(
after.len(),
1,
"the archived cold experience is excluded by the !archived filter"
);
assert_eq!(
after[0].0, surfaced_id,
"only the non-archived cold exp remains"
);
assert!(
!after.iter().any(|(id, _)| *id == archived_id),
"the archived cold experience does NOT appear"
);
db.close().unwrap();
}
}