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
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
// SPDX-License-Identifier: Apache-2.0
//! `WriterActor`, `WriteCommand`, `WriteHandle` — single-writer actor on a
//! dedicated OS thread. See ADR-0003 §"Trait shapes" and §"Operational
//! invariants".
//!
//! ## Why a dedicated OS thread (not a tokio task)
//!
//! `rusqlite::Connection::execute` blocks the current thread. If the actor
//! ran on a tokio worker, every write would block one worker for the
//! duration of the SQL — under burst load the runtime would starve and
//! every other task (HTTP handlers, MCP handlers, the snapshot timer) would
//! stall. The dedicated thread isolates that blocking from the runtime.
//!
//! Inside `run()` we use `mpsc::Receiver::blocking_recv()`; from outside the
//! actor, `WriteHandle::send().await` is async, so callers don't block on
//! sends.
//!
//! ## Reply-before-drain (ADR-0003 §P8-E)
//!
//! `Remember` carries a oneshot reply channel. The reply is sent **after**
//! the SQL transaction commits and `hnsw.add` succeeds, but **before** the
//! `pending_index` row is drained. Callers see "Ok = durable AND searchable"
//! without waiting on cleanup. If the drain itself fails, the row replays
//! on next startup — same end state.
//!
//! ## What's stubbed in commit 1.2
//!
//! `handle_forget`, `handle_consolidate`, `handle_reembed`,
//! `handle_save_snapshot` return `Error::Other("not yet implemented (commit
//! 1.x)")`. They're plumbed through the dispatch so callers can wire the
//! API today; the bodies fill in as the relevant commits land.
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params, params_from_iter};
use solo_core::{
Embedder, Embedding, Episode, Error, InvalidateEvent, MemoryId, Result, Tier, VectorIndex,
};
use tokio::runtime::Handle;
use tokio::sync::{RwLock as AsyncRwLock, broadcast, mpsc, oneshot};
use crate::audit::{AuditEvent, AuditOperation, AuditResult, insert_audit_row_in_tx};
use crate::backup::backup_from_connection;
use crate::hnsw_id::{chunk_hnsw_id, episode_hnsw_id};
use crate::key_material::KeyMaterial;
/// Default mpsc channel capacity. ADR-0003 §"Channel capacity": 1024 lets a
/// 1000-write consolidation burst land without backpressure-blocking the
/// regular write path.
pub const DEFAULT_CHANNEL_CAPACITY: usize = 1024;
/// v0.10.0: capacity of the per-tenant `broadcast::Sender<InvalidateEvent>`
/// that the writer-actor uses to fan out post-commit invalidations to
/// `GET /v1/graph/stream` SSE subscribers.
///
/// 256 is plenty for the realistic ratio of (writer commits) :
/// (SSE-subscriber poll latency) — even a 100-write consolidation burst
/// against 3 connected solo-web clients leaves the slowest subscriber
/// 150+ slots of head-room. A subscriber that falls behind by more than
/// 256 events gets `broadcast::error::RecvError::Lagged(n)`, which the
/// SSE handler maps to a single emit-only-once warning + a graceful
/// skip (the client will see a heartbeat next and refetch on the next
/// real invalidate — there's no correctness loss because invalidation
/// events are idempotent "refetch your data" signals, not deltas).
pub const INVALIDATE_BROADCAST_CAPACITY: usize = 256;
/// v0.9.2: hard cap on `WriteCommand::RememberBatch` item count.
///
/// Bounds the worst case for batched-write from agentic clients
/// (solo-jarvis writes back a turn's worth of episodes at once). A
/// typical agent turn produces 5–30 items; 200 gives 6×+ head-room
/// without exposing the writer-actor to pathological batches.
/// Exceeded → the handler returns `Error::InvalidInput`; the request
/// never reaches the BEGIN IMMEDIATE tx.
pub const MAX_REMEMBER_BATCH_SIZE: usize = 200;
/// Filter + flags for `WriteCommand::Consolidate`.
///
/// Implements `Deserialize` so HTTP / future MCP transports can
/// build it from a JSON request body without extra plumbing.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct ConsolidationScope {
/// If `Some(N)`, only consolidate episodes with `ts_ms` in the last
/// N days. `None` = walk all `tier='hot' AND status='active'` rows.
/// Bounded windows are typical for the daemon's nightly timer;
/// unbounded for a one-shot bulk run.
pub window_days: Option<i64>,
/// When `true`, run the merge + regen passes even if there are
/// zero unclustered episodes to feed to `cluster_episodes`. The
/// usual flow short-circuits on empty candidates because there's
/// no fresh work — but pre-existing clusters can drift across
/// runs and should occasionally coalesce regardless. `--force-merge`
/// on `solo consolidate` (or `force_merge: true` in the HTTP
/// JSON body) opts into that drift catch-up.
#[serde(default)]
pub force_merge: bool,
}
/// What `WriteCommand::Consolidate` returns to the caller. v0.2.0
/// covers the SWS-equivalent clustering pass; abstraction +
/// contradiction counts will populate in later commits.
///
/// `Serialize` so HTTP responses can ship it directly as JSON.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ConsolidationReport {
/// Distinct episodes the candidate query returned.
pub episodes_seen: usize,
/// Clusters that survived the size + threshold filter and were
/// persisted to the `clusters` table.
pub clusters_built: usize,
/// Sum of episode_ids across all built clusters (i.e. how many
/// `cluster_episodes` rows were inserted).
pub episodes_clustered: usize,
/// Number of clusters absorbed into a survivor by the centroid-
/// merge pass (`solo_steward::cluster::merge_clusters_by_centroid`).
/// Closes the cross-UTC-day-bucket case where conversations
/// straddling midnight produce two clusters with similar centroids.
/// 0 when no merges were possible. Counts losers, not survivors —
/// `clusters_built` reflects the post-merge count.
pub clusters_merged: usize,
/// Number of freshly-built clusters absorbed into pre-existing
/// DB clusters via
/// `solo_steward::cluster::absorb_into_existing` (cross-run
/// re-consolidation). The absorbed cluster never gets its own
/// `clusters` row; its episodes link under the existing
/// cluster_id, and the existing cluster's centroid + coherence
/// refresh. Counts new-side clusters; `clusters_built` reflects
/// the post-absorb count of brand-new clusters that survived to
/// be inserted.
pub clusters_absorbed: usize,
/// Number of pre-existing clusters absorbed into another
/// pre-existing cluster by the existing-vs-existing merge pass
/// (`solo_steward::cluster::plan_existing_merges`). Closes the
/// long-tail case where two clusters drift toward each other
/// over time via repeated absorbs and should now coalesce.
/// Counts losers, not survivors. Each loser's
/// `cluster_episodes` rows reassign to the survivor's
/// `cluster_id`, then the loser row is DELETEd (cascading via
/// the 0001 + 0002 FKs through `cluster_episodes` (already
/// empty after the UPDATE), `semantic_abstractions`, and
/// `triples`). Survivor's stale abstraction is then regenerated
/// by the same regen pass that handles cross-run absorb
/// modifications.
pub existing_clusters_merged: usize,
/// Number of pre-existing clusters whose stale
/// `semantic_abstractions` + linked `triples` were dropped and
/// regenerated as a follow-on to the cross-run absorb pass.
/// Equal to the count of distinct existing cluster_ids that
/// absorbed at least one new cluster, **as long as** the
/// regenerate-abstract LLM call succeeds; per-cluster failures
/// are logged + skipped (the cluster row + its absorbed episodes
/// stay; the abstraction row stays empty until the next run).
/// 0 when no LLM steward is wired or no absorptions happened.
pub abstractions_regenerated: usize,
/// Number of `semantic_abstractions` rows successfully persisted
/// (Y.3.3). 0 when the writer was spawned without a `Steward` —
/// the prod default until a real `LlmClient` ships.
pub abstractions_built: usize,
/// Number of `triples` rows persisted alongside the abstractions
/// (Y.3.3). Each abstraction can produce 0..N triples; the LLM
/// is asked to extract them but may legitimately return none.
pub triples_built: usize,
/// Reserved for Y.4. Always 0 in this commit.
pub contradictions_found: usize,
}
/// Filter + flags for `WriteCommand::Reembed`.
#[derive(Debug, Clone, Default)]
pub struct ReembedScope {
/// If `Some((name, version))`, only reembed memories whose existing
/// embedding row was produced by this embedder identity. If `None`,
/// every memory whose embedding's `embedder_id` differs from the
/// writer's current `embedder_id` is a candidate.
pub from: Option<(String, String)>,
/// Walk + count only; write nothing.
pub dry_run: bool,
/// After re-embedding each touched memory, DELETE the prior
/// `embeddings` rows for that memory whose `embedder_id` differs
/// from the current. Without this flag, stale rows are retained
/// for forensics or rollback.
pub gc: bool,
}
#[derive(Debug, Clone, Default)]
pub struct ReembedReport {
/// Distinct memory_ids that matched the candidate query.
pub rows_seen: usize,
/// Memories whose new embedding was successfully written.
pub rows_reembedded: usize,
/// Memories that hit an error during embed or insert.
pub rows_failed: usize,
/// Number of stale `embeddings` rows DELETED via `--gc`.
pub rows_gc_deleted: usize,
/// Mirrors the scope flag so callers can format output without
/// retaining the original scope.
pub dry_run: bool,
}
/// What `WriteCommand::NormalizeSubjects` returns to the caller.
///
/// Opt-in backfill tool: rewrites historical `triples.subject_id` and
/// `triples.object_id` values according to a caller-supplied alias map.
/// The companion to v0.5.0's read-path alias resolution
/// (`IdentityConfig.user_aliases`) — that bridges queries transparently
/// against existing rows, while this rewrites the underlying data so
/// downstream consumers (third-party tools, exports) see the canonical
/// identity. See `docs/dev-log/0071-v0.5.x-roadmap.md` Priority 10.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct NormalizeReport {
/// Number of `(from, to)` alias pairs processed (== `scope.aliases.len()`).
pub aliases_processed: usize,
/// Rows whose `subject_id` was rewritten (summed across all pairs).
/// In `dry_run` mode this is the count that *would* be rewritten;
/// the transaction is rolled back before the change is persisted.
pub subject_rows_updated: usize,
/// Rows whose `object_id` was rewritten (summed across all pairs).
/// Same dry-run semantics as `subject_rows_updated`.
pub object_rows_updated: usize,
/// Mirrors the scope flag so callers can format output without
/// retaining the original scope.
pub dry_run: bool,
}
/// Default per-file ingest size cap when `SOLO_INGEST_MAX_BYTES` is not
/// set in the environment. 50 MB matches the value advertised in
/// `docs/releases/v0.7.0.md` §"`SOLO_INGEST_MAX_BYTES`".
///
/// Above the cap, the writer returns an error before `parse_file` opens
/// the file, so the SQL and HNSW state are untouched. Set
/// `SOLO_INGEST_MAX_BYTES=0` to disable the cap entirely (caller-managed
/// resource bound).
pub const DEFAULT_INGEST_MAX_BYTES: u64 = 50 * 1024 * 1024;
pub(crate) const SOLO_INGEST_MAX_BYTES_ENV: &str = "SOLO_INGEST_MAX_BYTES";
/// Effective per-file ingest cap.
///
/// Returns:
///
/// - `Some(n)` — enforce a cap of `n` bytes.
/// - `None` — cap disabled (env var explicitly set to `0`).
///
/// Resolution order:
///
/// 1. If `SOLO_INGEST_MAX_BYTES` is unset → `Some(DEFAULT_INGEST_MAX_BYTES)`.
/// 2. If `SOLO_INGEST_MAX_BYTES=0` → `None` (disabled).
/// 3. If `SOLO_INGEST_MAX_BYTES=<positive integer>` → `Some(n)`.
/// 4. If the env var is set but unparseable (negative, garbage, whitespace,
/// etc.) → `Some(DEFAULT_INGEST_MAX_BYTES)` plus a `tracing::warn!`. The
/// conservative fallback is "use the default" rather than "disable cap"
/// so a typo can't silently turn off the safety net.
pub fn resolve_ingest_max_bytes() -> Option<u64> {
match std::env::var(SOLO_INGEST_MAX_BYTES_ENV) {
Err(_) => Some(DEFAULT_INGEST_MAX_BYTES),
Ok(raw) => {
let trimmed = raw.trim();
match trimmed.parse::<u64>() {
Ok(0) => None,
Ok(n) => Some(n),
Err(_) => {
tracing::warn!(
value = %raw,
env = SOLO_INGEST_MAX_BYTES_ENV,
default_bytes = DEFAULT_INGEST_MAX_BYTES,
"unparseable SOLO_INGEST_MAX_BYTES; falling back to default"
);
Some(DEFAULT_INGEST_MAX_BYTES)
}
}
}
}
}
/// What `WriteCommand::IngestDocument` returns to the caller. New in
/// v0.7.0 (RAG / document-memory). See `docs/dev-log/0083-v0.7.0-
/// implementation-plan.md` §2 P3.
///
/// `deduped == true` indicates the same content_hash was already present
/// in `documents`; the returned `doc_id` is the pre-existing document's
/// id and `chunks_persisted` is zero (no new chunks were written, no
/// embeddings were called). Forgotten documents still participate in
/// dedup — re-ingesting the same text after `forget_document` returns
/// the forgotten doc_id unchanged (callers can re-activate via a
/// future `restore` command, or simply ingest under a different source
/// path if they want a fresh active doc).
#[derive(Debug, Clone, serde::Serialize)]
pub struct IngestReport {
pub doc_id: solo_core::DocumentId,
pub chunks_persisted: u32,
pub bytes_ingested: u64,
pub deduped: bool,
}
/// What `WriteCommand::ForgetDocument` returns to the caller. New in
/// v0.7.0.
///
/// `chunks_tombstoned` counts the `document_chunks` rows whose HNSW
/// rowid was tombstoned (so `index.len()` no longer counts them and
/// `detect_drift` stays clean). The chunk rows themselves are NOT
/// deleted from SQL — `documents.status='forgotten'` is the soft-delete
/// marker; chunks survive for forensic value (same pattern as episodes'
/// soft-delete via `episodes.status='forgotten'`).
#[derive(Debug, Clone, serde::Serialize)]
pub struct ForgetDocumentReport {
pub doc_id: solo_core::DocumentId,
pub chunks_tombstoned: u32,
}
/// Result for correcting an existing active episode through the
/// single-writer actor.
#[derive(Debug, Clone, serde::Serialize)]
pub struct MemoryUpdateReport {
pub memory_id: MemoryId,
pub rowid: i64,
pub content: String,
pub updated_at_ms: i64,
}
/// All write operations go through this enum. Each variant carries a
/// oneshot reply channel.
///
/// v0.8.0 P4: every mutating variant also carries `audit_principal:
/// Option<String>` — the authenticated principal's subject. Threaded
/// from the auth middleware (HTTP / MCP) through to the writer-actor,
/// where the synchronous audit emit records "who did this". `None`
/// covers CLI / no-auth / system-initiated paths.
#[derive(Debug)]
pub enum WriteCommand {
Remember {
episode: Episode,
embedding: Embedding,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<MemoryId>>,
},
/// v0.9.2: atomically insert N episodes in one BEGIN IMMEDIATE tx.
/// Used by agentic clients (solo-jarvis) that write back a full turn
/// — user message + assistant response + tool outputs — as one
/// transactional unit so a session crash can never leave a half-
/// persisted turn.
///
/// Same outbox-via-`pending_index` discipline as single `Remember`:
/// BEGIN IMMEDIATE → INSERTs (episodes + embeddings + pending_index
/// per item) → ONE batch-level audit row inside the tx → COMMIT →
/// `hnsw.add` per item → DELETE `pending_index` rows. If an
/// `hnsw.add` crashes mid-batch the SQL state is already committed
/// and the un-drained outbox rows replay on next startup.
///
/// Item count capped at [`MAX_REMEMBER_BATCH_SIZE`]; over-cap
/// requests are rejected before BEGIN with `Error::InvalidInput`.
///
/// Reply is `Vec<MemoryId>` in input order — caller pairs them with
/// their input items by position.
RememberBatch {
items: Vec<(Episode, Embedding)>,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<Vec<MemoryId>>>,
},
Forget {
memory_id: MemoryId,
reason: String,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<()>>,
},
Update {
memory_id: MemoryId,
content: String,
embedding: Embedding,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<MemoryUpdateReport>>,
},
/// Ingest a document from `path` into the documents / document_chunks
/// tables, embedding each chunk via the writer's configured Embedder.
/// Same outbox-via-`pending_index` discipline as `Remember`: BEGIN
/// IMMEDIATE → INSERT documents → INSERT document_chunks → INSERT
/// pending_index (kind='chunk') → COMMIT → hnsw.add per chunk →
/// DELETE pending_index rows. Content-hash dedup short-circuits
/// re-ingest of the same normalized text.
///
/// Available only when the writer was spawned with an active embedder
/// (the `spawn_full_with_embedder*` variants). Other spawn paths get
/// a clear "not configured" error — same pattern as `Reembed`.
IngestDocument {
path: std::path::PathBuf,
chunk_config: crate::document::ChunkConfig,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<IngestReport>>,
},
/// Soft-delete a document: set `documents.status='forgotten'` and
/// tombstone every chunk's HNSW rowid. Chunks remain in SQL for
/// forensic value; queries that JOIN through `documents` filter
/// `status='active'`. Forgotten docs survive content-hash dedup —
/// re-ingesting the same content returns the forgotten doc_id.
ForgetDocument {
doc_id: solo_core::DocumentId,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<ForgetDocumentReport>>,
},
Consolidate {
scope: ConsolidationScope,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<ConsolidationReport>>,
},
Reembed {
scope: ReembedScope,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<ReembedReport>>,
},
SaveSnapshot {
reply: oneshot::Sender<Result<()>>,
},
/// Online encrypted backup of the writer's source database to
/// `dest_path`. The destination is created with PRAGMA key bound to
/// the same raw key the writer holds, so the backup file restores
/// under the same passphrase + salt as the source.
///
/// Available only when the writer was spawned with a `KeyMaterial`
/// (the `spawn_full_with_key_and_optional_steward` variant). Other
/// spawn paths get a clear "not configured" error.
Backup {
dest_path: PathBuf,
reply: oneshot::Sender<Result<()>>,
},
/// Backfill: rewrite historical `triples.subject_id` and
/// `triples.object_id` values per a caller-supplied alias map.
/// Each `(from, to)` pair is applied to **both** the subject and
/// object columns (a name appearing in either position should
/// normalize identically).
///
/// Opt-in: read-path alias resolution (v0.5.0 P1) already covers
/// query-time bridging without touching stored rows. This command
/// is for users who want the underlying data to match the canonical
/// identity (e.g., when exporting to a system that won't honor
/// `IdentityConfig.user_aliases`). See `docs/dev-log/0071-v0.5.x-roadmap.md`
/// Priority 10.
NormalizeSubjects {
/// `(from_id, to_id)` pairs — e.g. `[("alex", "user"),
/// ("bob", "user")]`. Each pair is applied as
/// `UPDATE triples SET subject_id = to WHERE subject_id = from`
/// and the symmetric object update.
aliases: Vec<(String, String)>,
/// When true, run the UPDATEs inside a transaction, count the
/// affected rows, then `ROLLBACK` instead of committing. The
/// returned report's row counts reflect what *would* have been
/// rewritten.
dry_run: bool,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<NormalizeReport>>,
},
/// v0.9.0 P2: emit a single `AuditOperation::LlmSamplingCall` row
/// into the per-tenant `audit_events` table. Used by
/// `SamplingLlmClient` (in `solo-api`) on every
/// `peer.create_message` completion — success or failure.
///
/// Routed through the writer-actor so the INSERT lands inside a
/// dedicated sync transaction on the writer's connection (lesson
/// #30: ACID for the sampling call's only persisted trace). The
/// `reply` channel surfaces insert failures to the caller so a
/// missed audit row can NOT be silently swallowed — the caller
/// of `SamplingLlmClient::complete()` must see the failure
/// because this row is the ONLY record of the call.
///
/// **Privacy invariant**: `event.details` must NOT contain the
/// raw prompt content. Enforcement lives at the construction
/// site (`SamplingLlmClient::audit_event`); we surface only
/// metadata (model hint, message count, max_tokens, duration_ms,
/// total prompt char count). The audit test
/// `sampling_audit_row_omits_raw_prompt_text` pins this.
EmitLlmSamplingAudit {
event: AuditEvent,
reply: oneshot::Sender<Result<()>>,
},
/// v0.9.0 P4c: persist a batch of `(cluster_id, abstraction)`
/// pairs in a single transaction + emit ONE
/// `AuditOperation::MemoryTriplesExtract` audit row carrying the
/// batch's aggregate counts.
///
/// Sent by the daemon-side consolidate-timer's triples batch
/// path (see `crates/solo-cli/src/commands/daemon.rs::
/// triples_batch_tick`). For each `(cluster_id, abstraction)`:
///
/// * INSERT one `semantic_abstractions` row.
/// * INSERT N `triples` rows (where N = `abstraction.triples.len()`).
///
/// Then emit ONE audit row per batch, with
/// `details_json = {episode_count, cluster_count,
/// abstractions_built, triples_extracted, duration_ms}`.
///
/// **Atomicity** (plan §4 P4c / lesson #30): the entire batch
/// runs inside ONE `BEGIN IMMEDIATE` tx; the audit emit is
/// SYNC inside that same tx. If the audit emit fails, the
/// whole batch aborts — preserving the "audit row IS the only
/// persisted record of the batch" invariant.
///
/// **Partial-batch tolerance**: per-cluster INSERT failures
/// (e.g. FK violation if the cluster_id was dropped between
/// snapshot and persist) are LOGGED and skipped, but the tx
/// stays open. The audit row's `details_json.abstractions_built`
/// counter reflects the SUCCESSFUL inserts only. Test:
/// [`tests::p4c_attach_abstraction_batch_tests`].
AttachAbstractionBatch {
/// `(cluster_id, abstraction)` pairs to persist. The
/// abstraction's `cluster_id` field is REQUIRED to equal the
/// tuple's `MemoryId`; the handler asserts this and rejects
/// the whole batch on mismatch.
items: Vec<(MemoryId, solo_core::SemanticAbstraction)>,
/// Number of episodes that flowed into this batch (for the
/// audit row's `details_json.episode_count`).
episode_count: usize,
/// Wall-time the upstream collection+LLM round-trip took
/// (for the audit row's `details_json.duration_ms`). The
/// writer-actor's own tx duration is small and not included.
duration_ms: u64,
/// v0.10.1 (P4 audit m5): number of clusters that timed out
/// during their per-cluster `abstract_cluster` call. Surfaces
/// in the audit row's `details_json.clusters_deferred` and in
/// the returned `AttachAbstractionBatchReport.clusters_deferred`.
/// Distinct from `clusters_failed` (per-cluster INSERT
/// SAVEPOINT rollbacks): a deferred cluster never made it INTO
/// the batch's `items` because the LLM call timed out
/// upstream.
clusters_deferred: usize,
/// Cached audit `principal_subject` for the daemon path —
/// usually `None` since the consolidate timer runs without
/// an explicit principal.
audit_principal: Option<String>,
reply: oneshot::Sender<Result<AttachAbstractionBatchReport>>,
},
/// Mark a contradiction resolved / unresolved / reopened. Routes
/// through the writer actor (dev-log 0152 finding H1 — restores
/// ADR-0003: the previous code path used the **reader pool** to
/// UPDATE `contradictions`, racing with the writer-actor on multiple
/// connections and writing the audit row outside the tx).
///
/// **Atomicity**: UPDATE + audit emit inside one BEGIN IMMEDIATE
/// transaction. If the audit row insert fails, the UPDATE rolls back.
ResolveContradiction {
a_id: String,
b_id: String,
kind: String,
status: String,
resolution_note: Option<String>,
winning_triple_id: Option<String>,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<ResolveContradictionReport>>,
},
}
/// Report from [`WriteCommand::ResolveContradiction`] (dev-log 0152 H1).
/// Fields mirror the read-side `solo_query::ContradictionResolution`
/// shape so callers can convert by field name. Defined here in
/// solo-storage because the writer-actor cannot depend on solo-query
/// (which depends on solo-storage).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolveContradictionReport {
pub a_id: String,
pub b_id: String,
pub kind: String,
pub status: String,
pub resolved_at_ms: Option<i64>,
pub resolution_note: Option<String>,
pub winning_triple_id: Option<String>,
}
/// v0.9.0 P4c: report from
/// [`WriteCommand::AttachAbstractionBatch`]. The daemon-side caller
/// can log + surface these to the consolidate-timer's
/// `tracing::info!` summary.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AttachAbstractionBatchReport {
pub abstractions_built: usize,
pub triples_extracted: usize,
pub clusters_failed: usize,
/// v0.10.1 (P4 audit m5): number of clusters whose per-cluster
/// LLM call timed out in `Steward::extract_triples_batch`.
/// Echoed from the caller's `clusters_deferred` argument so the
/// daemon's `tracing::info!` summary surfaces it alongside the
/// SQL-level counters. Also lands in the audit row's
/// `details_json.clusters_deferred`.
pub clusters_deferred: usize,
}
/// Cheaply cloneable handle. Pass clones to every task that needs to write.
/// Dropping the *last* clone closes the channel and triggers actor shutdown.
#[derive(Clone, Debug)]
pub struct WriteHandle {
tx: mpsc::Sender<WriteCommand>,
}
impl WriteHandle {
pub async fn remember(
&self,
episode: Episode,
embedding: Embedding,
) -> Result<MemoryId> {
self.remember_as(None, episode, embedding).await
}
/// v0.8.0 P4: like `remember`, but records `audit_principal` in the
/// audit_events row. Pass `Some(subject)` from auth-aware transports
/// (HTTP via `AuthenticatedPrincipal`, MCP via cached principal).
/// `None` matches CLI / no-auth paths.
pub async fn remember_as(
&self,
audit_principal: Option<String>,
episode: Episode,
embedding: Embedding,
) -> Result<MemoryId> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::Remember {
episode,
embedding,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
/// v0.9.2: atomic batched-remember. See [`WriteCommand::RememberBatch`]
/// for semantics. Returns `MemoryId`s in input order.
pub async fn remember_batch_as(
&self,
audit_principal: Option<String>,
items: Vec<(Episode, Embedding)>,
) -> Result<Vec<MemoryId>> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::RememberBatch {
items,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
pub async fn forget(&self, memory_id: MemoryId, reason: String) -> Result<()> {
self.forget_as(None, memory_id, reason).await
}
/// v0.8.0 P4 audit-aware variant. See [`Self::remember_as`].
pub async fn forget_as(
&self,
audit_principal: Option<String>,
memory_id: MemoryId,
reason: String,
) -> Result<()> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::Forget {
memory_id,
reason,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
pub async fn update(
&self,
memory_id: MemoryId,
content: String,
embedding: Embedding,
) -> Result<MemoryUpdateReport> {
self.update_as(None, memory_id, content, embedding).await
}
/// Correct an active episode's content and embedding through the
/// writer actor so it serializes with remember/forget/drain work.
pub async fn update_as(
&self,
audit_principal: Option<String>,
memory_id: MemoryId,
content: String,
embedding: Embedding,
) -> Result<MemoryUpdateReport> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::Update {
memory_id,
content,
embedding,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
/// Ingest a document at `path` using `chunk_config` for splitting.
/// See [`WriteCommand::IngestDocument`] for the persistence pipeline.
pub async fn ingest_document(
&self,
path: std::path::PathBuf,
chunk_config: crate::document::ChunkConfig,
) -> Result<IngestReport> {
self.ingest_document_as(None, path, chunk_config).await
}
/// v0.8.0 P4 audit-aware variant. See [`Self::remember_as`].
pub async fn ingest_document_as(
&self,
audit_principal: Option<String>,
path: std::path::PathBuf,
chunk_config: crate::document::ChunkConfig,
) -> Result<IngestReport> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::IngestDocument {
path,
chunk_config,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
/// Soft-delete a document and tombstone its chunks' HNSW rowids.
/// See [`WriteCommand::ForgetDocument`] for semantics.
pub async fn forget_document(
&self,
doc_id: solo_core::DocumentId,
) -> Result<ForgetDocumentReport> {
self.forget_document_as(None, doc_id).await
}
/// v0.8.0 P4 audit-aware variant. See [`Self::remember_as`].
pub async fn forget_document_as(
&self,
audit_principal: Option<String>,
doc_id: solo_core::DocumentId,
) -> Result<ForgetDocumentReport> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::ForgetDocument {
doc_id,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
pub async fn consolidate(&self, scope: ConsolidationScope) -> Result<ConsolidationReport> {
self.consolidate_as(None, scope).await
}
/// v0.8.0 P4 audit-aware variant. See [`Self::remember_as`].
pub async fn consolidate_as(
&self,
audit_principal: Option<String>,
scope: ConsolidationScope,
) -> Result<ConsolidationReport> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::Consolidate {
scope,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
pub async fn reembed(&self, scope: ReembedScope) -> Result<ReembedReport> {
self.reembed_as(None, scope).await
}
/// v0.8.0 P4 audit-aware variant. See [`Self::remember_as`].
pub async fn reembed_as(
&self,
audit_principal: Option<String>,
scope: ReembedScope,
) -> Result<ReembedReport> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::Reembed {
scope,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
/// Run an online encrypted backup of the writer's source database
/// to `dest_path`. Available only when the writer was spawned with
/// a `KeyMaterial` (see [`WriterActor::spawn_full_with_key_and_optional_steward`]).
pub async fn backup(&self, dest_path: PathBuf) -> Result<()> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::Backup {
dest_path,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
pub async fn save_snapshot(&self) -> Result<()> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::SaveSnapshot { reply: reply_tx })
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
/// Rewrite historical `triples.subject_id` / `triples.object_id`
/// values for each `(from, to)` pair in `aliases`. See
/// [`WriteCommand::NormalizeSubjects`] for semantics.
pub async fn normalize_subjects(
&self,
aliases: Vec<(String, String)>,
dry_run: bool,
) -> Result<NormalizeReport> {
self.normalize_subjects_as(None, aliases, dry_run).await
}
/// v0.8.0 P4 audit-aware variant. See [`Self::remember_as`].
pub async fn normalize_subjects_as(
&self,
audit_principal: Option<String>,
aliases: Vec<(String, String)>,
dry_run: bool,
) -> Result<NormalizeReport> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::NormalizeSubjects {
aliases,
dry_run,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
/// v0.9.0 P2: emit a single `AuditOperation::LlmSamplingCall` row
/// into the per-tenant `audit_events` table via the writer-actor.
///
/// The INSERT lands inside a dedicated `BEGIN IMMEDIATE`
/// transaction on the writer's connection (lesson #30: ACID for
/// the sampling call's only persisted trace). Insert failures
/// surface to the caller — `SamplingLlmClient` propagates them up
/// so a missed audit row can NOT be silently swallowed.
///
/// **Privacy invariant**: callers MUST construct `event.details`
/// with metadata only (model hint, message count, max_tokens,
/// duration_ms, total prompt char count). The raw prompt content
/// is user data that the user did NOT consent to log here.
/// Enforcement lives at the call site
/// (`SamplingLlmClient::audit_event`); this method has no way to
/// scrub a malformed event in the writer-actor.
pub async fn emit_llm_sampling_audit(
&self,
event: AuditEvent,
) -> Result<()> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::EmitLlmSamplingAudit {
event,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
/// v0.9.0 P4c: persist a batch of cluster-level abstractions +
/// their extracted triples in a single writer-actor transaction,
/// emitting ONE `AuditOperation::MemoryTriplesExtract` audit row.
///
/// Called from the daemon-side consolidate-timer's triples batch
/// path. The writer-actor handles ACID: every successful
/// (cluster, abstraction) insert + the audit emit land or
/// rollback together. Per-cluster INSERT failures (e.g. cluster
/// row deleted concurrently) log + skip but do NOT abort the
/// batch's tx.
pub async fn attach_abstraction_batch(
&self,
items: Vec<(MemoryId, solo_core::SemanticAbstraction)>,
episode_count: usize,
duration_ms: u64,
clusters_deferred: usize,
audit_principal: Option<String>,
) -> Result<AttachAbstractionBatchReport> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::AttachAbstractionBatch {
items,
episode_count,
duration_ms,
clusters_deferred,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
/// Mark a contradiction resolved / unresolved / reopened (dev-log
/// 0152 H1). Routes through the writer actor so the UPDATE +
/// `audit_events` row land atomically in one BEGIN IMMEDIATE
/// transaction. Status must be one of `unresolved` | `resolved` |
/// `reopened`. Returns `Error::NotFound` if the (a_id, b_id, kind)
/// triple does not match any contradiction row.
#[allow(clippy::too_many_arguments)]
pub async fn resolve_contradiction_as(
&self,
audit_principal: Option<String>,
a_id: String,
b_id: String,
kind: String,
status: String,
resolution_note: Option<String>,
winning_triple_id: Option<String>,
) -> Result<ResolveContradictionReport> {
let (reply_tx, reply_rx) = oneshot::channel();
self.tx
.send(WriteCommand::ResolveContradiction {
a_id,
b_id,
kind,
status,
resolution_note,
winning_triple_id,
audit_principal,
reply: reply_tx,
})
.await
.map_err(|_| Error::storage("writer task gone (channel closed)"))?;
reply_rx
.await
.map_err(|_| Error::storage("writer dropped reply channel"))?
}
}
/// The writer actor.
pub struct WriterActor {
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
rx: mpsc::Receiver<WriteCommand>,
/// Directory for HNSW snapshot save. `None` means `SaveSnapshot` returns
/// an error (used in unit tests that don't exercise the snapshot path).
/// The daemon main (commit 1.5) sets this to the data dir.
snapshot_dir: Option<PathBuf>,
/// Resolved `embedders.embedder_id` for the active embedder. Set once
/// at startup (`solo_storage::startup::run` resolves via
/// `get_or_insert_embedder_id`) and cached for every `INSERT INTO
/// embeddings` row. `None` means the writer was spawned in a test
/// context that doesn't exercise the embeddings-table-write path —
/// `dispatch_remember` falls back to skipping the embeddings INSERT
/// and just writes pending_index.
embedder_id: Option<i64>,
/// The active embedder. Required by `handle_reembed` to regenerate
/// vectors for episodes whose embeddings were produced by a different
/// (older) embedder. The regular `Remember` path does NOT call this —
/// callers pass pre-computed `Embedding` objects in `WriteCommand::
/// Remember`. `None` here means `solo reembed` is not available on
/// this writer (unit tests, daemon paths that opt out).
embedder: Option<Arc<dyn Embedder>>,
/// Handle to the tokio runtime that constructed this actor. Captured
/// at `spawn_full_with_embedder` time so the dedicated writer thread
/// can `block_on` async embedder calls during reembed. `None` matches
/// `embedder == None`.
runtime_handle: Option<Handle>,
/// The Steward (clustering + LLM-driven abstraction). Required by
/// `handle_consolidate`'s abstraction step (Y.3.3); the cheap
/// clustering step (Y.2) always runs and uses
/// `StewardConfig::default()` even when the steward is `None`. So:
/// - `None` → `consolidate` runs cluster persistence only,
/// `abstractions_built` stays 0. This is the default for prod
/// today since no real `LlmClient` ships.
/// - `Some` → after cluster persistence, the actor walks each
/// cluster, calls `steward.abstract_cluster`, persists the
/// `SemanticAbstraction`. Failures per cluster are logged +
/// counted; clusters themselves are already-persisted ground
/// truth and never roll back.
steward: Option<Arc<solo_steward::Steward>>,
/// v0.9.0 P4a: per-tenant lazily-populated Steward slot
/// (`TenantHandle::steward_slot()` from P0c). When present, the
/// writer-actor PREFERS this slot's contents over `self.steward`
/// on every consolidate tick (see [`Self::current_steward`]).
///
/// This activates the v0.9.0 P2-plumbed-but-inert sampling Steward:
/// the MCP-initialize hook writes a peer-bound Steward into the
/// slot AFTER the writer-actor has spawned; reading the slot per
/// command (rather than capturing `self.steward` once at spawn)
/// is how the writer-actor observes that late-bound population.
///
/// Static backends (Anthropic / OpenAI / Ollama / None) populate
/// the slot eagerly at `TenantHandle::open` via the configured
/// `StewardFactory`. For those backends, `slot.try_read()` is an
/// uncontested fast-read returning `Some(steward)` — the slot and
/// `self.steward` carry the same `Arc` identity (the slot is the
/// canonical source, `self.steward` mirrors it for backwards-compat
/// with v0.8.x writer spawn paths that don't yet plumb the slot).
///
/// `None` here means the writer was spawned by a path that doesn't
/// know about the slot (older spawn variants, pure-storage tests
/// that don't go through `TenantHandle::open`). The writer falls
/// back to `self.steward` in that case (which preserves v0.8.x
/// behavior).
steward_slot:
Option<Arc<AsyncRwLock<Option<Arc<solo_steward::Steward>>>>>,
/// Raw SQLCipher key used to open the source connection. Required
/// by `handle_backup` so it can encrypt the destination connection
/// with the same key. `None` means the writer was spawned without
/// key material (test paths, the legacy spawn variants); `WriteCommand::
/// Backup` returns a clear "not configured" error in that case.
key: Option<KeyMaterial>,
/// v0.8.0 P5: PII redaction registry. Disabled by default
/// (`RedactionRegistry::is_enabled` returns `false`). When enabled,
/// the redactor runs over text content before INSERT in every
/// `remember` and `ingest_document` path. Built either from the
/// per-data-dir `[redaction]` config (prod) or from `builtin()`
/// (tests). Cheap to clone the `Arc`; cheaper still to skip the
/// whole pass via the early-exit `is_enabled` check.
redactor: Arc<crate::redaction::RedactionRegistry>,
/// v0.8.1 P3: per-tenant byte quota cached at open time. `None`
/// means unlimited — enforcement short-circuits at the top of every
/// growth-bearing handler (remember / ingest_document), so the no-
/// quota path is one branch and one Option compare. The cached
/// value is refreshed only on TenantHandle re-open; admins who
/// reduce a quota via `solo tenants set-quota` see the change after
/// the next daemon restart or tenant reopen.
quota_bytes: Option<u64>,
/// v0.8.1 P3: on-disk path used to estimate `current_size_bytes`
/// before checking against `quota_bytes`. `None` is the test-only
/// spawn variant; enforcement quietly skips when path is unknown.
db_path: Option<PathBuf>,
/// v0.9.0 P4-revision (P4 audit M1): count-based trigger signal for
/// the daemon-side `triples_batch_timer`. When wired, the actor
/// calls `signal.note_episode_remembered()` after every successful
/// `Remember` so the daemon can short-circuit to a batch run
/// before the next `trigger_interval_secs` tick.
///
/// `None` for v0.8.x spawn variants + test paths that don't drive
/// the count-based trigger. The note hook then becomes a no-op via
/// `Option::as_ref().map(...)` shape.
triples_batch_signal: Option<Arc<crate::triples_batch::TriplesBatchSignal>>,
/// v0.10.0: per-tenant broadcast channel for invalidation events.
/// Populated by `TenantHandle::open`; the SSE subscribers
/// (`GET /v1/graph/stream` handlers) call `tx.subscribe()` to get
/// a `Receiver`. The writer-actor calls `tx.send(...).ok()` AFTER
/// every successful commit; the `.ok()` swallows "no subscribers"
/// (a normal state when no clients are connected).
///
/// `None` for pure-storage test spawn paths that don't drive the
/// SSE surface; every prod path via `TenantHandle::open` wires this.
/// See `INVALIDATE_BROADCAST_CAPACITY` for the channel sizing.
invalidate_tx: Option<broadcast::Sender<InvalidateEvent>>,
/// v0.10.0: cached tenant id (as a string) used to populate the
/// `tenant_id` field of every emitted `InvalidateEvent`. Paired
/// 1:1 with `invalidate_tx` — both `Some(_)` or both `None`.
invalidate_tenant_id: Option<String>,
}
/// What `WriterActor::spawn*` returns. The daemon needs the
/// `std::thread::JoinHandle<()>` so it can wait for the writer's
/// `shutdown()` (`PRAGMA wal_checkpoint(TRUNCATE)`, final HNSW save)
/// to complete after the last `WriteHandle` is dropped. Without this,
/// the OS reaps the writer thread when `main` returns, possibly
/// mid-checkpoint.
///
/// Tests that don't care about clean shutdown timing can simply drop
/// the JoinHandle along with the WriteHandle.
pub struct WriterSpawn {
pub handle: WriteHandle,
pub join: std::thread::JoinHandle<()>,
}
impl WriterSpawn {
/// Drop the WriteHandle (closing the mpsc) and block until the writer
/// thread finishes its `shutdown()` and exits. No timeout — production
/// supervisors decide when to force-kill via SIGKILL.
pub fn shutdown_blocking(self) {
drop(self.handle);
if let Err(panic) = self.join.join() {
tracing::error!(?panic, "solo-writer thread panicked during shutdown");
}
}
}
impl WriterActor {
pub fn spawn(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
) -> WriterSpawn {
Self::spawn_with_capacity(conn, hnsw, DEFAULT_CHANNEL_CAPACITY)
}
pub fn spawn_with_capacity(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
capacity: usize,
) -> WriterSpawn {
Self::spawn_internal(conn, hnsw, capacity, None, None, None, None, None, None, None)
}
/// Spawn with a snapshot directory wired up. The daemon main calls this
/// path so `WriteCommand::SaveSnapshot` can reach disk.
pub fn spawn_with_snapshot_dir(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
) -> WriterSpawn {
Self::spawn_internal(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
None,
None,
None,
None,
None,
None,
)
}
/// Spawn with both snapshot dir + cached embedder_id. The daemon
/// main calls this so every `remember` also INSERTs into the
/// `embeddings` table for durability + future `solo reembed`.
pub fn spawn_full(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
) -> WriterSpawn {
Self::spawn_internal(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
Some(embedder_id),
None,
None,
None,
None,
None,
)
}
/// Spawn with snapshot dir + embedder_id + the active embedder. Use
/// this from any path that may invoke `WriteCommand::Reembed` — i.e.
/// the `solo reembed` one-shot. Captures `Handle::current()` to bridge
/// the async embedder API onto the writer's blocking thread.
///
/// **Requires a multi-thread tokio runtime.** Panics if called outside
/// any runtime context. On a `current_thread` runtime it would NOT
/// panic, but `handle_reembed`'s `runtime.block_on(embedder.embed(...))`
/// from the writer thread would deadlock — the runtime's only worker
/// would be the test's outer thread, already blocked awaiting the
/// reembed reply. Production callers run inside `#[tokio::main]`
/// (multi-thread by default); tests use `rt_multi(N)` with N >= 1
/// worker independent of the test's calling thread.
pub fn spawn_full_with_embedder(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
embedder: Arc<dyn Embedder>,
) -> WriterSpawn {
Self::spawn_full_with_embedder_and_optional_steward(
conn,
hnsw,
snapshot_dir,
embedder_id,
embedder,
None,
)
}
/// The full surface: snapshot + embedder + steward. Use this from
/// the `solo consolidate` one-shot path or from a prod daemon
/// that ships with a real `LlmClient` configured. The steward's
/// `Arc<dyn LlmClient>` powers `handle_consolidate`'s abstraction
/// step (Y.3.3); without a steward, consolidate runs the
/// clustering pass only.
pub fn spawn_full_with_embedder_and_optional_steward(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
embedder: Arc<dyn Embedder>,
steward: Option<Arc<solo_steward::Steward>>,
) -> WriterSpawn {
let handle = Handle::current();
Self::spawn_internal(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
Some(embedder_id),
Some(embedder),
Some(handle),
steward,
None,
None,
)
}
/// Like [`Self::spawn_full_with_embedder_and_optional_steward`] but
/// also captures `key` so the writer can serve `WriteCommand::Backup`.
/// The daemon (and one-shot paths that want HTTP-side backup) use
/// this variant; pure-test spawn paths can use the no-key variant.
pub fn spawn_full_with_key_and_optional_steward(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
embedder: Arc<dyn Embedder>,
steward: Option<Arc<solo_steward::Steward>>,
key: KeyMaterial,
) -> WriterSpawn {
let handle = Handle::current();
Self::spawn_internal(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
Some(embedder_id),
Some(embedder),
Some(handle),
steward,
Some(key),
None,
)
}
/// Variant of [`Self::spawn_full_with_key_and_optional_steward`] that
/// takes an explicit `runtime_handle` rather than calling
/// `Handle::current()`. v0.8.0 P2: `TenantHandle::open` is sync (the
/// registry's lazy-load path is `async fn` but calls it via
/// `spawn_blocking`), so we cannot rely on a current runtime; the
/// caller passes the handle in.
pub fn spawn_full_with_key_steward_and_runtime(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
embedder: Arc<dyn Embedder>,
steward: Option<Arc<solo_steward::Steward>>,
key: KeyMaterial,
runtime_handle: Handle,
) -> WriterSpawn {
Self::spawn_internal(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
Some(embedder_id),
Some(embedder),
Some(runtime_handle),
steward,
Some(key),
None,
)
}
/// v0.8.0 P5: variant of [`Self::spawn_full_with_key_steward_and_runtime`]
/// that also threads in a pre-built `RedactionRegistry`. Used by
/// `TenantHandle::open` so the per-data-dir `[redaction]` config
/// reaches the writer-actor.
#[allow(clippy::too_many_arguments)]
pub fn spawn_full_with_redactor(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
embedder: Arc<dyn Embedder>,
steward: Option<Arc<solo_steward::Steward>>,
key: KeyMaterial,
runtime_handle: Handle,
redactor: Arc<crate::redaction::RedactionRegistry>,
) -> WriterSpawn {
Self::spawn_internal(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
Some(embedder_id),
Some(embedder),
Some(runtime_handle),
steward,
Some(key),
Some(redactor),
)
}
/// v0.8.1 P3: variant of [`Self::spawn_full_with_redactor`] that
/// also captures the cached per-tenant `quota_bytes` and `db_path`
/// so the writer-actor's `handle_remember` / `handle_ingest_document`
/// can enforce the quota before INSERT. `quota_bytes = None` means
/// unlimited (default for tenants without a quota set); enforcement
/// short-circuits in one branch.
#[allow(clippy::too_many_arguments)]
pub fn spawn_full_with_quota(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
embedder: Arc<dyn Embedder>,
steward: Option<Arc<solo_steward::Steward>>,
key: KeyMaterial,
runtime_handle: Handle,
redactor: Arc<crate::redaction::RedactionRegistry>,
quota_bytes: Option<u64>,
db_path: PathBuf,
) -> WriterSpawn {
Self::spawn_internal_full(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
Some(embedder_id),
Some(embedder),
Some(runtime_handle),
steward,
Some(key),
Some(redactor),
quota_bytes,
Some(db_path),
None,
None,
None,
None,
)
}
/// v0.9.0 P4a: variant of [`Self::spawn_full_with_quota`] that also
/// threads the per-tenant `steward_slot` so the writer-actor's
/// consolidate path can observe late-bound sampling-backed
/// Stewards (populated by the MCP-initialize hook after writer
/// spawn). Called from [`crate::tenants::handle::TenantHandle::
/// open`] — every other spawn path stays on `spawn_full_with_quota`
/// and falls back to `self.steward` in [`Self::current_steward`].
///
/// Per plan §4 P4a: "WriterActor reads `tenant.steward_slot()` per
/// command (or per consolidate-tick), falling back to `self.steward`
/// if the slot is None." The slot-read is cheap
/// (`steward_slot.try_read().clone()` returns
/// `Option<Arc<Steward>>`; the clone is an Arc-bump). For the
/// sampling backend specifically, `self.steward` is `None` at spawn
/// (the factory builds a no-op); the slot read picks up the
/// Steward once the MCP session is initialized.
#[allow(clippy::too_many_arguments)]
pub fn spawn_full_with_quota_and_slot(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
embedder: Arc<dyn Embedder>,
steward: Option<Arc<solo_steward::Steward>>,
key: KeyMaterial,
runtime_handle: Handle,
redactor: Arc<crate::redaction::RedactionRegistry>,
quota_bytes: Option<u64>,
db_path: PathBuf,
steward_slot: Arc<
AsyncRwLock<Option<Arc<solo_steward::Steward>>>,
>,
triples_batch_signal: Option<Arc<crate::triples_batch::TriplesBatchSignal>>,
) -> WriterSpawn {
Self::spawn_internal_full(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
Some(embedder_id),
Some(embedder),
Some(runtime_handle),
steward,
Some(key),
Some(redactor),
quota_bytes,
Some(db_path),
Some(steward_slot),
triples_batch_signal,
None,
None,
)
}
/// v0.10.0: variant of [`Self::spawn_full_with_quota_and_slot`] that
/// also threads the per-tenant `broadcast::Sender<InvalidateEvent>`
/// + the tenant id string so the writer-actor can fan out
/// post-commit invalidations to `GET /v1/graph/stream` SSE
/// subscribers. Called from [`crate::tenants::handle::TenantHandle::
/// open`] (the prod entry point); test paths can use any of the
/// older spawn variants and skip invalidation broadcasting.
///
/// Invariant (lesson #30): the broadcast `send` happens AFTER the
/// writer-actor's commit returns `Ok`. Rolled-back writes MUST NOT
/// produce an event. Implementation lives in each mutation handler's
/// dispatch wrapper next to the audit-emit (success path) /
/// emit_audit_best_effort (failure path) call.
#[allow(clippy::too_many_arguments)]
pub fn spawn_full_with_invalidate(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
snapshot_dir: PathBuf,
embedder_id: i64,
embedder: Arc<dyn Embedder>,
steward: Option<Arc<solo_steward::Steward>>,
key: KeyMaterial,
runtime_handle: Handle,
redactor: Arc<crate::redaction::RedactionRegistry>,
quota_bytes: Option<u64>,
db_path: PathBuf,
steward_slot: Arc<
AsyncRwLock<Option<Arc<solo_steward::Steward>>>,
>,
triples_batch_signal: Option<Arc<crate::triples_batch::TriplesBatchSignal>>,
invalidate_tx: broadcast::Sender<InvalidateEvent>,
invalidate_tenant_id: String,
) -> WriterSpawn {
Self::spawn_internal_full(
conn,
hnsw,
DEFAULT_CHANNEL_CAPACITY,
Some(snapshot_dir),
Some(embedder_id),
Some(embedder),
Some(runtime_handle),
steward,
Some(key),
Some(redactor),
quota_bytes,
Some(db_path),
Some(steward_slot),
triples_batch_signal,
Some(invalidate_tx),
Some(invalidate_tenant_id),
)
}
#[allow(clippy::too_many_arguments)]
fn spawn_internal(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
capacity: usize,
snapshot_dir: Option<PathBuf>,
embedder_id: Option<i64>,
embedder: Option<Arc<dyn Embedder>>,
runtime_handle: Option<Handle>,
steward: Option<Arc<solo_steward::Steward>>,
key: Option<KeyMaterial>,
redactor: Option<Arc<crate::redaction::RedactionRegistry>>,
) -> WriterSpawn {
Self::spawn_internal_full(
conn,
hnsw,
capacity,
snapshot_dir,
embedder_id,
embedder,
runtime_handle,
steward,
key,
redactor,
None,
None,
None,
None,
None,
None,
)
}
/// v0.8.1 P3: full internal spawn that also threads `quota_bytes` +
/// `db_path` for the writer-actor's quota-enforcement path. Older
/// `spawn_internal` calls delegate here with `None` for both,
/// preserving the existing test-spawn paths' "no quota check"
/// behavior.
///
/// v0.10.0: also threads the optional
/// `broadcast::Sender<InvalidateEvent>` + `invalidate_tenant_id`
/// so the writer-actor can fan out post-commit invalidations to
/// `GET /v1/graph/stream` SSE subscribers. The pair is `(None, None)`
/// for spawn paths that don't drive the SSE surface.
#[allow(clippy::too_many_arguments)]
fn spawn_internal_full(
conn: Connection,
hnsw: Arc<dyn VectorIndex + Send + Sync>,
capacity: usize,
snapshot_dir: Option<PathBuf>,
embedder_id: Option<i64>,
embedder: Option<Arc<dyn Embedder>>,
runtime_handle: Option<Handle>,
steward: Option<Arc<solo_steward::Steward>>,
key: Option<KeyMaterial>,
redactor: Option<Arc<crate::redaction::RedactionRegistry>>,
quota_bytes: Option<u64>,
db_path: Option<PathBuf>,
steward_slot: Option<
Arc<AsyncRwLock<Option<Arc<solo_steward::Steward>>>>,
>,
triples_batch_signal: Option<Arc<crate::triples_batch::TriplesBatchSignal>>,
invalidate_tx: Option<broadcast::Sender<InvalidateEvent>>,
invalidate_tenant_id: Option<String>,
) -> WriterSpawn {
let (tx, rx) = mpsc::channel(capacity);
let redactor = redactor.unwrap_or_else(|| {
// Disabled registry: writer's redaction path no-ops via the
// early `is_enabled` check.
Arc::new(
crate::redaction::RedactionRegistry::from_config(
&crate::config::RedactionConfig::default(),
)
.expect("default RedactionConfig must build a disabled registry"),
)
});
// Pair invalidate_tx with invalidate_tenant_id — both must be
// Some or both None. Drop one silently if only one was supplied
// (test path defensively; prod always supplies both).
let (invalidate_tx, invalidate_tenant_id) =
match (invalidate_tx, invalidate_tenant_id) {
(Some(tx), Some(tid)) => (Some(tx), Some(tid)),
_ => (None, None),
};
let actor = Self {
conn,
hnsw,
rx,
snapshot_dir,
embedder_id,
embedder,
runtime_handle,
steward,
steward_slot,
triples_batch_signal,
key,
redactor,
quota_bytes,
db_path,
invalidate_tx,
invalidate_tenant_id,
};
let join = std::thread::Builder::new()
.name("solo-writer".into())
.spawn(move || actor.run())
.expect("spawn solo-writer thread");
WriterSpawn {
handle: WriteHandle { tx },
join,
}
}
fn run(mut self) {
while let Some(cmd) = self.rx.blocking_recv() {
self.dispatch(cmd);
}
self.shutdown();
}
/// v0.9.0 P4a: resolve the "active" Steward for this writer-actor at
/// command-time. Prefers the lazily-populated [`Self::steward_slot`]
/// over the eagerly-captured [`Self::steward`].
///
/// Read priority — slot, then `self.steward`:
///
/// * **Slot populated** (sampling backend mid-life, or any
/// factory-driven static backend): `try_read` succeeds
/// uncontested; observable Steward is the one written by the
/// MCP-initialize hook (P2's `populate_sampling_steward`).
/// * **Slot populated but contended** (rare — only happens during
/// the brief window where the MCP-initialize hook is writing):
/// `try_read` fails. Fall back to `self.steward` rather than
/// blocking the writer thread; the next consolidate tick will
/// observe the populated slot.
/// * **Slot empty AND `self.steward` populated**: a v0.8.x-style
/// caller wired the eager Steward without using the slot.
/// Return `self.steward`.
/// * **Slot empty AND `self.steward` empty**: no LLM backend
/// configured; consolidate runs the cheap clustering pass only
/// (the existing v0.2-era posture).
///
/// **Deadlock check** (lesson #30 + plan §6 read-side discipline):
/// the slot uses `tokio::sync::RwLock`. Calling `try_read` from the
/// writer thread (a synchronous OS thread, NOT a tokio worker)
/// would normally panic — `tokio::sync::RwLock::try_read` is safe
/// for sync callers but the wider `try_read().await` form is not.
/// We use the sync `try_read` shape, which returns
/// `Result<RwLockReadGuard, TryLockError>` and never blocks.
fn current_steward(&self) -> Option<Arc<solo_steward::Steward>> {
if let Some(slot) = self.steward_slot.as_ref() {
// try_read is the sync variant — never blocks, returns an
// error if a writer holds the lock. We do not retry; the
// brief contended-write window (the MCP-initialize hook)
// is so short that the next consolidate tick observes the
// populated slot.
if let Ok(guard) = slot.try_read() {
if let Some(s) = guard.as_ref() {
return Some(Arc::clone(s));
}
}
}
self.steward.clone()
}
fn dispatch(&mut self, cmd: WriteCommand) {
match cmd {
WriteCommand::Remember {
episode,
embedding,
audit_principal,
reply,
} => self.dispatch_remember(episode, embedding, audit_principal, reply),
WriteCommand::RememberBatch {
items,
audit_principal,
reply,
} => self.dispatch_remember_batch(items, audit_principal, reply),
WriteCommand::Forget {
memory_id,
reason,
audit_principal,
reply,
} => {
let result =
self.handle_forget(memory_id, reason, audit_principal.clone());
// v0.8.0 P4: success-path audit is inside the tx. Error
// path: best-effort emit here (the tx already aborted).
let durable_ok = result.is_ok();
if let Err(ref e) = result {
self.emit_audit_best_effort(
AuditOperation::MemoryForget,
Some(memory_id.to_string()),
AuditResult::Error,
audit_principal,
Some(serde_json::json!({ "error": e.to_string() })),
);
}
let _ = reply.send(result);
// v0.10.0: post-commit invalidation (lesson #30).
if durable_ok {
self.emit_invalidate(
AuditOperation::MemoryForget.as_str(),
"episode",
);
}
}
WriteCommand::Update {
memory_id,
content,
embedding,
audit_principal,
reply,
} => {
self.dispatch_update(memory_id, content, embedding, audit_principal, reply);
}
WriteCommand::IngestDocument {
path,
chunk_config,
audit_principal,
reply,
} => {
self.dispatch_ingest_document(path, chunk_config, audit_principal, reply);
}
WriteCommand::ForgetDocument {
doc_id,
audit_principal,
reply,
} => {
let result =
self.handle_forget_document(doc_id, audit_principal.clone());
let durable_ok = result.is_ok();
if let Err(ref e) = result {
self.emit_audit_best_effort(
AuditOperation::MemoryForgetDocument,
Some(doc_id.to_string()),
AuditResult::Error,
audit_principal,
Some(serde_json::json!({ "error": e.to_string() })),
);
}
let _ = reply.send(result);
// v0.10.0: post-commit invalidation (lesson #30).
if durable_ok {
self.emit_invalidate(
AuditOperation::MemoryForgetDocument.as_str(),
"document",
);
}
}
WriteCommand::Consolidate {
scope,
audit_principal,
reply,
} => {
let result = self.handle_consolidate(scope, audit_principal);
let durable_ok = result.is_ok();
let _ = reply.send(result);
// v0.10.0: post-commit invalidation (lesson #30).
// Consolidate affects clusters; the abstraction +
// triples cascade fires on its own batch path.
if durable_ok {
self.emit_invalidate(
AuditOperation::MemoryConsolidate.as_str(),
"cluster",
);
}
}
WriteCommand::Reembed {
scope,
audit_principal,
reply,
} => {
let result = self.handle_reembed(scope, audit_principal);
let durable_ok = result.is_ok();
let _ = reply.send(result);
// v0.10.0: post-commit invalidation (lesson #30).
// Reembed changes episode vectors so semantic
// neighbors shift — surface as an episode kind.
if durable_ok {
self.emit_invalidate(
AuditOperation::MemoryReembed.as_str(),
"episode",
);
}
}
WriteCommand::SaveSnapshot { reply } => {
let _ = reply.send(self.handle_save_snapshot());
}
WriteCommand::Backup { dest_path, reply } => {
let _ = reply.send(self.handle_backup(&dest_path));
}
WriteCommand::NormalizeSubjects {
aliases,
dry_run,
audit_principal,
reply,
} => {
let result = self.handle_normalize_subjects(
aliases,
dry_run,
audit_principal,
);
let durable_ok = result.is_ok() && !dry_run;
let _ = reply.send(result);
// v0.10.0: post-commit invalidation (lesson #30). Skip
// the dry-run path — by construction it ROLLs back.
if durable_ok {
self.emit_invalidate(
AuditOperation::MemoryNormalizeSubjects.as_str(),
"triple",
);
}
}
WriteCommand::EmitLlmSamplingAudit { event, reply } => {
let _ = reply.send(self.handle_emit_llm_sampling_audit(event));
}
WriteCommand::ResolveContradiction {
a_id,
b_id,
kind,
status,
resolution_note,
winning_triple_id,
audit_principal,
reply,
} => {
let result = self.handle_resolve_contradiction(
a_id,
b_id,
kind,
status,
resolution_note,
winning_triple_id,
audit_principal,
);
let durable_ok = result.is_ok();
let _ = reply.send(result);
// Post-commit invalidation: contradictions are derived data
// surfaced by `memory_contradictions` + the graph view.
if durable_ok {
self.emit_invalidate(
AuditOperation::MemoryContradictionResolve.as_str(),
"contradiction",
);
}
}
WriteCommand::AttachAbstractionBatch {
items,
episode_count,
duration_ms,
clusters_deferred,
audit_principal,
reply,
} => {
let result = self.handle_attach_abstraction_batch(
items,
episode_count,
duration_ms,
clusters_deferred,
audit_principal,
);
let durable_ok = result.is_ok();
let _ = reply.send(result);
// v0.10.0: post-commit invalidation (lesson #30).
// Abstractions + triples both attach to a cluster —
// surface as a cluster kind. Subscribers refetch the
// cluster-kind page on this event.
if durable_ok {
self.emit_invalidate(
AuditOperation::MemoryTriplesExtract.as_str(),
"cluster",
);
}
}
}
}
/// v0.9.0 P2: insert one `AuditOperation::LlmSamplingCall` row in
/// a dedicated sync tx on the writer's connection.
///
/// Returns `Ok(())` on a successful INSERT + COMMIT; surfaces every
/// SQLite-layer failure to the caller via `Err(_)`. The caller is
/// `SamplingLlmClient::complete()`, which propagates the error to
/// the LLM-using subsystem (Steward abstraction / contradiction
/// path) — a failed audit insert means the sampling call's only
/// persisted trace is missing, which is operator-visible.
///
/// The transaction is `BEGIN IMMEDIATE` so the writer-actor's
/// other handlers (which use the same connection) don't race with
/// the audit insert.
fn handle_emit_llm_sampling_audit(&mut self, event: AuditEvent) -> Result<()> {
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| {
Error::storage(format!(
"BEGIN IMMEDIATE for llm.sampling_call audit: {e}"
))
})?;
insert_audit_row_in_tx(&tx, &event)?;
tx.commit().map_err(|e| {
Error::storage(format!("COMMIT llm.sampling_call audit: {e}"))
})?;
Ok(())
}
/// Dev-log 0152 H1: contradiction resolution routed through the
/// writer-actor (was previously executed via the reader pool, racing
/// with the writer-actor on multiple connections and emitting the
/// audit row outside the tx).
///
/// One BEGIN IMMEDIATE tx wraps the UPDATE + audit row. If the audit
/// INSERT fails, the UPDATE rolls back — strict ACID.
#[allow(clippy::too_many_arguments)]
fn handle_resolve_contradiction(
&mut self,
a_id: String,
b_id: String,
kind: String,
status: String,
resolution_note: Option<String>,
winning_triple_id: Option<String>,
audit_principal: Option<String>,
) -> Result<ResolveContradictionReport> {
let status = status.trim().to_string();
if !matches!(status.as_str(), "unresolved" | "resolved" | "reopened") {
return Err(Error::invalid_input(
"contradiction status must be unresolved, resolved, or reopened",
));
}
let note = resolution_note
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let winning = winning_triple_id
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let resolved_at_ms = if status == "resolved" {
Some(chrono::Utc::now().timestamp_millis())
} else {
None
};
let now_ms = chrono::Utc::now().timestamp_millis();
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| {
Error::storage(format!(
"BEGIN IMMEDIATE for resolve_contradiction: {e}"
))
})?;
let changed = tx
.execute(
"UPDATE contradictions
SET status = ?4,
resolved_at_ms = ?5,
resolution_note = ?6,
winning_triple_id = ?7
WHERE a_memory_id = ?1
AND b_memory_id = ?2
AND kind = ?3",
rusqlite::params![a_id, b_id, kind, status, resolved_at_ms, note, winning],
)
.map_err(|e| Error::storage(format!("UPDATE contradictions: {e}")))?;
if changed == 0 {
// Roll back the empty tx implicitly (drop) — nothing to audit.
return Err(Error::not_found("contradiction not found"));
}
// Audit row inside the SAME tx — UPDATE rolls back if INSERT fails.
let target = format!("{a_id}:{b_id}:{kind}");
insert_audit_row_in_tx(
&tx,
&AuditEvent {
ts_ms: now_ms,
principal_subject: audit_principal,
operation: AuditOperation::MemoryContradictionResolve,
target_id: Some(target),
result: AuditResult::Ok,
details: None,
},
)?;
tx.commit()
.map_err(|e| Error::storage(format!("COMMIT resolve_contradiction: {e}")))?;
Ok(ResolveContradictionReport {
a_id,
b_id,
kind,
status,
resolved_at_ms,
resolution_note: note,
winning_triple_id: winning,
})
}
/// v0.9.0 P4c: persist a batch of `(cluster_id, abstraction)`
/// pairs in a single transaction + emit ONE
/// `AuditOperation::MemoryTriplesExtract` audit row carrying the
/// batch's aggregate counts.
///
/// One `BEGIN IMMEDIATE` tx wraps all the per-cluster INSERTs +
/// the audit emit.
///
/// **v0.9.0 P4-revision (P4 audit M2)**: each cluster's
/// DELETE-stale + INSERT-new pair is wrapped in a per-cluster
/// `SAVEPOINT`. On per-cluster INSERT failure we ROLLBACK TO
/// SAVEPOINT, which undoes that cluster's DELETE — preserving the
/// stale abstraction rather than orphaning the cluster with no
/// abstraction at all. RELEASE SAVEPOINT on success folds the
/// per-cluster work back into the outer tx.
///
/// Audit emit is SYNC inside the same outer tx (lesson #30): if
/// the audit INSERT fails, the entire batch tx aborts — the audit
/// row IS the only persisted record of the batch.
fn handle_attach_abstraction_batch(
&mut self,
items: Vec<(MemoryId, solo_core::SemanticAbstraction)>,
episode_count: usize,
duration_ms: u64,
clusters_deferred: usize,
audit_principal: Option<String>,
) -> Result<AttachAbstractionBatchReport> {
// Validate input shape (defensive). Each tuple's `MemoryId`
// MUST equal the embedded abstraction's `cluster_id` — the
// caller (daemon-side batch path) constructs them as a pair.
for (cluster_id, abstraction) in &items {
if abstraction.cluster_id != *cluster_id {
return Err(Error::Other(format!(
"AttachAbstractionBatch: cluster_id mismatch on tuple \
(got {} but abstraction.cluster_id is {})",
cluster_id, abstraction.cluster_id
)));
}
}
let now_ms = chrono::Utc::now().timestamp_millis();
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| {
Error::storage(format!(
"BEGIN IMMEDIATE for attach_abstraction_batch: {e}"
))
})?;
let mut report = AttachAbstractionBatchReport::default();
for (idx, (cluster_id, abstraction)) in items.iter().enumerate() {
let prov_json = match serde_json::to_string(&abstraction.provenance) {
Ok(s) => s,
Err(e) => {
tracing::warn!(
cluster_id = %cluster_id,
error = %e,
"attach_abstraction_batch: serialize provenance failed; skipping cluster"
);
report.clusters_failed += 1;
continue;
}
};
// v0.9.0 P4-revision (P4 audit M2): wrap each cluster's
// DELETE-stale + INSERT-new in a SAVEPOINT so a failed
// INSERT can ROLLBACK TO the savepoint and undo its OWN
// DELETE. Pre-revision, the per-cluster DELETE happened
// unconditionally inside the outer tx; if the per-cluster
// INSERT then failed, the outer tx still committed and the
// cluster's stale abstraction was destroyed without
// replacement. Now each cluster is atomic — either the
// savepoint releases (replacement persisted) or it rolls
// back (old abstraction kept; cluster booked as failed).
//
// Naming: SAVEPOINT identifiers are SQL identifiers; we
// use `cluster_<idx>` (the position in `items`) so two
// clusters in the same batch never collide. The
// `cluster_id` itself is a UUID-shaped MemoryId — not
// SQL-safe to use directly as an identifier. The idx
// approach is collision-free + grep-friendly.
let sp_name = format!("cluster_{idx}");
if let Err(e) = tx.execute_batch(&format!("SAVEPOINT {sp_name};")) {
tracing::warn!(
cluster_id = %cluster_id,
error = %e,
"attach_abstraction_batch: open SAVEPOINT failed; skipping cluster"
);
report.clusters_failed += 1;
continue;
}
let per_cluster_res = (|| -> rusqlite::Result<()> {
// Drop any stale abstraction + its cascaded triples for
// this cluster — idempotent re-runs after a partial
// earlier batch don't double-INSERT.
tx.execute(
"DELETE FROM semantic_abstractions WHERE cluster_id = ?",
params![cluster_id.to_string()],
)?;
tx.execute(
"DELETE FROM triples WHERE cluster_id = ?",
params![cluster_id.to_string()],
)?;
tx.execute(
"INSERT INTO semantic_abstractions
(abstraction_id, cluster_id, content, provenance_json,
confidence, created_at_ms)
VALUES (?, ?, ?, ?, ?, ?)",
params![
abstraction.abstraction_id.to_string(),
abstraction.cluster_id.to_string(),
abstraction.content,
prov_json,
abstraction.confidence.0,
now_ms,
],
)?;
for triple in &abstraction.triples {
let tprov = serde_json::to_string(&triple.provenance)
.unwrap_or_else(|_| "{}".to_string());
let object_kind_str = match triple.object_kind {
solo_core::TripleObjectKind::Entity => "entity",
solo_core::TripleObjectKind::Literal => "literal",
};
let source_eid = resolve_source_episode_id_in_tx(
&tx,
&triple.provenance,
);
tx.execute(
"INSERT INTO triples
(triple_id, subject_id, predicate, object_id,
object_kind, valid_from_ms, valid_to_ms,
confidence, provenance_json,
created_at_ms, updated_at_ms, cluster_id,
source_episode_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![
triple.triple_id.to_string(),
triple.subject_id,
triple.predicate,
triple.object_id,
object_kind_str,
triple.valid_from_ms,
triple.valid_to_ms,
triple.confidence.0,
tprov,
now_ms,
now_ms,
cluster_id.to_string(),
source_eid,
],
)?;
}
Ok(())
})();
match per_cluster_res {
Ok(()) => {
// RELEASE the savepoint — the per-cluster
// write is now part of the outer transaction.
if let Err(e) =
tx.execute_batch(&format!("RELEASE SAVEPOINT {sp_name};"))
{
// RELEASE failure is exceptional (e.g. DB
// gone, disk full). Treat the cluster as
// failed and try to ROLLBACK to clean up.
tracing::warn!(
cluster_id = %cluster_id,
error = %e,
"attach_abstraction_batch: RELEASE SAVEPOINT failed; cluster booked as failed"
);
let _ = tx.execute_batch(&format!(
"ROLLBACK TO SAVEPOINT {sp_name}; RELEASE SAVEPOINT {sp_name};"
));
report.clusters_failed += 1;
continue;
}
report.abstractions_built += 1;
report.triples_extracted += abstraction.triples.len();
}
Err(e) => {
// ROLLBACK TO undoes everything since the
// SAVEPOINT (including the DELETE). RELEASE
// afterwards pops the savepoint off the stack.
// Both must succeed or the savepoint stack would
// leak — but if they fail we log and continue
// (the outer tx still rolls back on Err return
// from this fn; here we want to PRESERVE the
// other clusters' SUCCESSFUL writes).
tracing::warn!(
cluster_id = %cluster_id,
error = %e,
"attach_abstraction_batch: per-cluster work failed; ROLLBACK TO SAVEPOINT"
);
if let Err(rb_err) = tx.execute_batch(&format!(
"ROLLBACK TO SAVEPOINT {sp_name}; RELEASE SAVEPOINT {sp_name};"
)) {
// Savepoint stack is now in an unknown state.
// Bail out of the whole batch — the outer tx
// will roll back when we Err return.
return Err(Error::storage(format!(
"ROLLBACK TO SAVEPOINT for cluster {cluster_id} \
failed (rb_err={rb_err}; original cluster err={e}); \
aborting entire batch"
)));
}
report.clusters_failed += 1;
}
}
}
// v0.10.1 (m5): surface the caller's per-cluster-timeout
// tally on the returned report so the daemon's tracing line
// shows clusters_deferred alongside the SQL-level counters.
report.clusters_deferred = clusters_deferred;
// Audit emit sync inside the same tx (lesson #30). If it
// fails, the whole batch rolls back — the audit row IS the
// persisted record of the batch.
let audit_event = AuditEvent {
ts_ms: now_ms,
principal_subject: audit_principal,
operation: AuditOperation::MemoryTriplesExtract,
target_id: None,
result: AuditResult::Ok,
details: Some(serde_json::json!({
"episode_count": episode_count,
"cluster_count": items.len(),
"abstractions_built": report.abstractions_built,
"triples_extracted": report.triples_extracted,
"clusters_failed": report.clusters_failed,
"clusters_deferred": clusters_deferred,
"duration_ms": duration_ms,
})),
};
insert_audit_row_in_tx(&tx, &audit_event)?;
tx.commit().map_err(|e| {
Error::storage(format!(
"COMMIT attach_abstraction_batch: {e}"
))
})?;
Ok(report)
}
fn dispatch_remember(
&mut self,
episode: Episode,
embedding: Embedding,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<MemoryId>>,
) {
let memory_id = episode.memory_id;
let result =
self.handle_remember_durable(episode, embedding, audit_principal.clone());
let durable_ok = result.is_ok();
// v0.8.0 P4: error-path audit emit. Success-path audit is inside
// the write tx (handle_remember_durable). On failure, the tx
// aborted so we record best-effort here.
if let Err(ref e) = result {
self.emit_audit_best_effort(
AuditOperation::MemoryRemember,
Some(memory_id.to_string()),
AuditResult::Error,
audit_principal,
Some(serde_json::json!({ "error": e.to_string() })),
);
}
let _ = reply.send(result);
// v0.10.0: fan out an `InvalidateEvent` on success. Lesson #30:
// AFTER commit, never before. `durable_ok == false` means the
// tx rolled back and no row landed; no event.
if durable_ok {
self.emit_invalidate(AuditOperation::MemoryRemember.as_str(), "episode");
}
if durable_ok {
// v0.9.0 P4-revision (P4 audit M1): note the new episode for
// the count-based trigger. Fires `notify_one` once the
// counter crosses `trigger_episode_count` so the daemon's
// `triples_batch_timer` can short-circuit the next batch
// run without waiting for the time-interval tick. No-op
// when the signal isn't wired (v0.8.x spawn variants).
if let Some(sig) = self.triples_batch_signal.as_ref() {
sig.note_episode_remembered();
}
if let Err(e) = self.conn.execute(
"DELETE FROM pending_index WHERE memory_id = ?",
params![memory_id.to_string()],
) {
tracing::warn!(
error = %e,
%memory_id,
"pending_index drain failed; will replay on next startup"
);
}
}
}
fn dispatch_update(
&mut self,
memory_id: MemoryId,
content: String,
embedding: Embedding,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<MemoryUpdateReport>>,
) {
let result =
self.handle_update_durable(memory_id, content, embedding, audit_principal.clone());
let durable_ok = result.is_ok();
if let Err(ref e) = result {
self.emit_audit_best_effort(
AuditOperation::MemoryUpdate,
Some(memory_id.to_string()),
AuditResult::Error,
audit_principal,
Some(serde_json::json!({ "error": e.to_string() })),
);
}
let memory_id_for_drain = result.as_ref().ok().map(|r| r.memory_id);
let _ = reply.send(result);
if durable_ok {
self.emit_invalidate(AuditOperation::MemoryUpdate.as_str(), "episode");
if let Some(mid) = memory_id_for_drain {
if let Err(e) = self.conn.execute(
"DELETE FROM pending_index WHERE kind = 'episode' AND memory_id = ?",
params![mid.to_string()],
) {
tracing::warn!(
error = %e,
%mid,
"pending_index drain failed (update); will replay on next startup"
);
}
}
}
}
fn handle_update_durable(
&mut self,
memory_id: MemoryId,
content: String,
embedding: Embedding,
audit_principal: Option<String>,
) -> Result<MemoryUpdateReport> {
embedding.validate()?;
let f32_slice = embedding.as_f32_slice().ok_or_else(|| {
Error::embedder("HNSW expects F32 embeddings; convert dtype upstream")
})?;
let content = content.trim();
if content.is_empty() {
return Err(Error::invalid_input(
"updated memory content must not be empty",
));
}
let redaction = self.redactor.redact(content);
let redacted_content: &str = redaction.text.as_ref();
let memory_id_s = memory_id.to_string();
let now_ms = chrono::Utc::now().timestamp_millis();
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| Error::storage(format!("BEGIN IMMEDIATE for update: {e}")))?;
let existing: Option<(i64, String)> = tx
.query_row(
"SELECT rowid, status FROM episodes WHERE memory_id = ?1",
params![&memory_id_s],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()
.map_err(|e| Error::storage(format!("SELECT episode for update: {e}")))?;
let (rowid, status) =
existing.ok_or_else(|| Error::not_found("memory not found"))?;
if status != "active" {
return Err(Error::conflict("cannot update a non-active memory"));
}
tx.execute(
"UPDATE episodes
SET content = ?2,
updated_at_ms = ?3
WHERE memory_id = ?1",
params![&memory_id_s, redacted_content, now_ms],
)
.map_err(|e| Error::storage(format!("UPDATE episode: {e}")))?;
if let Some(eid) = self.embedder_id {
let dtype_str = match embedding.dtype {
solo_core::EmbeddingDtype::F32 => "f32",
solo_core::EmbeddingDtype::F16 => "f16",
solo_core::EmbeddingDtype::I8 => "i8",
solo_core::EmbeddingDtype::Binary => "binary",
};
tx.execute(
"INSERT INTO embeddings (memory_id, embedder_id, dtype, dim, vector, created_at_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
ON CONFLICT(memory_id, embedder_id)
DO UPDATE SET dtype = excluded.dtype,
dim = excluded.dim,
vector = excluded.vector,
created_at_ms = excluded.created_at_ms",
params![
&memory_id_s,
eid,
dtype_str,
embedding.dim as i64,
&embedding.data[..],
now_ms
],
)
.map_err(|e| Error::storage(format!("UPSERT embedding: {e}")))?;
}
tx.execute(
"INSERT INTO pending_index (kind, memory_id, embedding, embedding_dim, enqueued_at)
VALUES ('episode', ?1, ?2, ?3, ?4)
ON CONFLICT(memory_id)
DO UPDATE SET kind = 'episode',
chunk_id = NULL,
embedding = excluded.embedding,
embedding_dim = excluded.embedding_dim,
enqueued_at = excluded.enqueued_at",
params![&memory_id_s, &embedding.data[..], embedding.dim as i64, now_ms],
)
.map_err(|e| Error::storage(format!("UPSERT pending_index: {e}")))?;
if !redaction.matches.is_empty() {
insert_audit_row_in_tx(
&tx,
&redaction_audit_event(
now_ms,
audit_principal.clone(),
Some(memory_id.to_string()),
&redaction.matches,
),
)?;
}
insert_audit_row_in_tx(
&tx,
&AuditEvent {
ts_ms: now_ms,
principal_subject: audit_principal,
operation: AuditOperation::MemoryUpdate,
target_id: Some(memory_id.to_string()),
result: AuditResult::Ok,
details: None,
},
)?;
tx.commit()
.map_err(|e| Error::storage(format!("COMMIT update: {e}")))?;
self.hnsw.add(episode_hnsw_id(rowid), f32_slice)?;
Ok(MemoryUpdateReport {
memory_id,
rowid,
content: redacted_content.to_string(),
updated_at_ms: now_ms,
})
}
fn handle_remember_durable(
&mut self,
episode: Episode,
embedding: Embedding,
audit_principal: Option<String>,
) -> Result<MemoryId> {
embedding.validate()?;
let memory_id = episode.memory_id;
// v0.8.1 P3: quota enforcement. Estimated growth is a
// conservative upper bound on the bytes about to land on disk —
// we prefer over-counting to under-counting (the brief is
// explicit on this). One episode row plus one embeddings row
// plus one pending_index row plus a per-row SQLite page-and-FTS
// overhead. The check short-circuits when quota_bytes is None
// (the common case for v0.8.0 tenants).
let estimated_growth: u64 = (episode.content.len() as u64)
.saturating_add(embedding.data.len() as u64)
// Per-row SQLite overhead (3 INSERTs across episodes +
// embeddings + pending_index) — conservative, since FTS5
// also incurs trigger-driven writes. 2 KiB total covers
// each row's metadata + FTS portion comfortably.
.saturating_add(2048);
match check_quota(
self.quota_bytes,
self.db_path.as_deref(),
estimated_growth,
) {
QuotaDecision::Unlimited | QuotaDecision::Allowed { .. } => {}
QuotaDecision::Exceeded {
current_size,
estimated_growth,
quota,
} => {
// Reject the write. The dispatch caller's error-path
// audit emit covers the "forbidden" audit row — we
// surface the structured error here. The error-message
// text is the operator-visible payload; the audit row
// gets `details_json` carrying the same numbers.
let err = QuotaExceededError {
current_size,
estimated_growth,
quota,
};
// v0.8.1 P3: emit the `forbidden` audit row before
// returning. Unlike `Error` results (which dispatch
// handles via emit_audit_best_effort), `Forbidden` is a
// policy outcome — the audit row IS the only record
// because no tx ran. Use the synchronous path so the
// row lands before we return.
self.emit_audit_best_effort(
AuditOperation::MemoryRemember,
Some(memory_id.to_string()),
AuditResult::Forbidden,
audit_principal,
Some(err.to_details_json()),
);
return Err(Error::forbidden(err.to_string()));
}
}
// v0.8.0 P5: redact PII from the content BEFORE INSERT. The
// unredacted text never lands on disk. The Remember path's
// embedding was computed by the caller (pre-writer); if the
// operator has redaction enabled, the on-disk text and embedding
// diverge by the redaction-substitution. This is the documented
// trade-off: for `ingest_document` the embedding is computed
// inside the writer after redaction (consistent); for Remember
// it isn't because the caller controls embedding. Operators who
// need strict text↔embedding consistency under redaction should
// either (a) redact upstream of `remember`, or (b) prefer
// ingestion via `ingest_document`.
let redaction = self.redactor.redact(&episode.content);
let redacted_content: &str = redaction.text.as_ref();
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| Error::storage(format!("BEGIN IMMEDIATE for remember: {e}")))?;
let now_ms = chrono::Utc::now().timestamp_millis();
let encoding_ctx = serde_json::to_string(&episode.encoding_context)
.map_err(|e| Error::storage(format!("serialize encoding_context: {e}")))?;
let provenance_json = match &episode.provenance {
Some(p) => Some(
serde_json::to_string(p)
.map_err(|e| Error::storage(format!("serialize provenance: {e}")))?,
),
None => None,
};
let tier_str = match episode.tier {
Tier::Hot => "hot",
Tier::Warm => "warm",
Tier::Cold => "cold",
};
tx.execute(
"INSERT INTO episodes (
memory_id, ts_ms, source_type, source_id, content,
encoding_context_json, provenance_json, confidence,
strength, salience, tier, created_at_ms, updated_at_ms,
principal_subject
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![
memory_id.to_string(),
episode.ts_ms,
episode.source_type,
episode.source_id,
redacted_content,
encoding_ctx,
provenance_json,
episode.confidence.0,
episode.strength,
episode.salience,
tier_str,
now_ms,
now_ms,
audit_principal.as_deref(),
],
)
.map_err(|e| Error::storage(format!("INSERT episode: {e}")))?;
let rowid = tx.last_insert_rowid();
// Persist the embedding to the `embeddings` table when
// we have a cached embedder_id. Without this row, `solo
// reembed` (post-v0.1) wouldn't know what vector this episode
// had under the previous model, and HNSW rebuild from SQL
// (also post-v0.1) couldn't repopulate the graph.
//
// Skipped when embedder_id is None — only happens in unit-test
// setups that didn't run the embedder-registry resolution
// step. The pending_index INSERT below still happens, so
// recovery on restart still works for tests that exercise
// the replay path.
if let Some(eid) = self.embedder_id {
let dtype_str = match embedding.dtype {
solo_core::EmbeddingDtype::F32 => "f32",
solo_core::EmbeddingDtype::F16 => "f16",
solo_core::EmbeddingDtype::I8 => "i8",
solo_core::EmbeddingDtype::Binary => "binary",
};
tx.execute(
"INSERT INTO embeddings (
memory_id, embedder_id, dtype, dim, vector, created_at_ms
) VALUES (?, ?, ?, ?, ?, ?)",
params![
memory_id.to_string(),
eid,
dtype_str,
embedding.dim as i64,
&embedding.data[..],
now_ms,
],
)
.map_err(|e| Error::storage(format!("INSERT embeddings: {e}")))?;
}
tx.execute(
"INSERT INTO pending_index (
memory_id, embedding, embedding_dim, enqueued_at
) VALUES (?, ?, ?, ?)",
params![
memory_id.to_string(),
&embedding.data[..],
embedding.dim as i64,
now_ms,
],
)
.map_err(|e| Error::storage(format!("INSERT pending_index: {e}")))?;
// v0.8.0 P5: emit a single `redaction.applied` audit row when
// one or more patterns fired. `details_json` carries pattern-
// name match counts only — never the matched substring. The
// test `audit_row_does_not_contain_original_pii` enforces this.
if !redaction.matches.is_empty() {
insert_audit_row_in_tx(
&tx,
&redaction_audit_event(
now_ms,
audit_principal.clone(),
Some(memory_id.to_string()),
&redaction.matches,
),
)?;
}
// v0.8.0 P4: synchronous audit emit inside the same tx. If this
// INSERT fails the surrounding tx rolls back via the `?` operator
// returning before COMMIT — strict ACID for the audited write.
insert_audit_row_in_tx(
&tx,
&AuditEvent {
ts_ms: now_ms,
principal_subject: audit_principal,
operation: AuditOperation::MemoryRemember,
target_id: Some(memory_id.to_string()),
result: AuditResult::Ok,
details: None,
},
)?;
tx.commit()
.map_err(|e| Error::storage(format!("COMMIT remember: {e}")))?;
let f32_slice = embedding.as_f32_slice().ok_or_else(|| {
Error::embedder("HNSW expects F32 embeddings; convert dtype upstream")
})?;
// Encode the rowid in the shared HNSW namespace (high bit clear
// for episodes). See `crate::hnsw_id` for the encoding rationale.
self.hnsw.add(episode_hnsw_id(rowid), f32_slice)?;
Ok(memory_id)
}
/// v0.9.2: dispatch for [`WriteCommand::RememberBatch`]. Mirrors
/// [`Self::dispatch_remember`] but operates over `Vec<(Episode,
/// Embedding)>` and surfaces a single `MemoryRememberBatch` audit
/// row (success or error) plus one invalidate fan-out per batch
/// (not per item).
fn dispatch_remember_batch(
&mut self,
items: Vec<(Episode, Embedding)>,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<Vec<MemoryId>>>,
) {
let item_count = items.len();
let result = self.handle_remember_batch_durable(items, audit_principal.clone());
// Dev-log 0152 H3: the handler now returns the per-item HNSW
// success mask alongside the memory ids. Items whose HNSW add
// failed are NOT drained from `pending_index` — they replay on
// next startup. SQL state for every item is already committed,
// so callers see the full memory_id list even when one item's
// HNSW add tripped (no silent partial success on retry).
let (forwarded, drain_ids): (Result<Vec<MemoryId>>, Vec<MemoryId>) = match result {
Ok((ids, hnsw_ok_mask)) => {
let drain: Vec<MemoryId> = ids
.iter()
.zip(hnsw_ok_mask.iter().copied())
.filter_map(|(mid, ok)| if ok { Some(*mid) } else { None })
.collect();
(Ok(ids), drain)
}
Err(e) => (Err(e), Vec::new()),
};
let durable_ok = forwarded.is_ok();
// Error-path audit emit (the in-tx success-path audit row is inside
// `handle_remember_batch_durable`). Quota/InvalidInput paths emit
// their own audit rows inside the handler.
if let Err(ref e) = forwarded {
self.emit_audit_best_effort(
AuditOperation::MemoryRememberBatch,
None,
AuditResult::Error,
audit_principal,
Some(serde_json::json!({
"error": e.to_string(),
"item_count": item_count,
})),
);
}
let _ = reply.send(forwarded);
if durable_ok {
// One invalidate per batch, not per item. Subscribers refetch
// the episode page once and pick up all N rows.
self.emit_invalidate(AuditOperation::MemoryRememberBatch.as_str(), "episode");
// v0.9.0 P4: triples-batch trigger. Each remembered episode
// increments the counter; the daemon's `triples_batch_timer`
// short-circuits when the counter crosses its threshold.
if let Some(sig) = self.triples_batch_signal.as_ref() {
for _ in 0..item_count {
sig.note_episode_remembered();
}
}
// Drain `pending_index` only for items whose HNSW add
// succeeded. Items that failed HNSW stay in pending_index
// so the next-startup replay can finish the job.
for mid in &drain_ids {
if let Err(e) = self.conn.execute(
"DELETE FROM pending_index WHERE memory_id = ?",
params![mid.to_string()],
) {
tracing::warn!(
error = %e,
%mid,
"pending_index drain failed (batch); will replay on next startup"
);
}
}
}
}
/// v0.9.2: durable batched-remember.
///
/// Pipeline (mirrors `handle_remember_durable` but folded over N items):
///
/// 1. Validate batch size against [`MAX_REMEMBER_BATCH_SIZE`] and
/// non-emptiness.
/// 2. Validate every embedding (dim, dtype, finiteness).
/// 3. Sum estimated growth across items and check quota ONCE for
/// the whole batch. Forbidden → `forbidden` audit row + early
/// return (no tx opened).
/// 4. `BEGIN IMMEDIATE`.
/// 5. For each item: redact PII → INSERT episode → INSERT embedding
/// (if embedder_id wired) → INSERT pending_index → per-item
/// redaction audit row when matches fired. Capture rowids.
/// 6. ONE batch-level audit row inside the tx
/// (`AuditOperation::MemoryRememberBatch`, `details.item_count`).
/// 7. `COMMIT`.
/// 8. `hnsw.add` per item using captured rowids. A mid-batch
/// failure aborts the rest and returns Err; the `pending_index`
/// outbox preserves the un-added rows for next-startup replay.
/// Dev-log 0152 H3: returns `(memory_ids, hnsw_ok_mask)` so the
/// dispatcher can drain `pending_index` for only the items whose
/// HNSW add succeeded. Items where HNSW add failed are kept in the
/// outbox for next-startup replay.
fn handle_remember_batch_durable(
&mut self,
items: Vec<(Episode, Embedding)>,
audit_principal: Option<String>,
) -> Result<(Vec<MemoryId>, Vec<bool>)> {
// 1. Batch-size validation.
if items.is_empty() {
return Err(Error::invalid_input(
"memory_remember_batch: items must not be empty".to_string(),
));
}
if items.len() > MAX_REMEMBER_BATCH_SIZE {
return Err(Error::invalid_input(format!(
"memory_remember_batch: {} items exceeds MAX_REMEMBER_BATCH_SIZE = {}",
items.len(),
MAX_REMEMBER_BATCH_SIZE,
)));
}
// 2. Embedding shape validation. We do this up front so a malformed
// item in slot 7 fails before slot 1 hits SQLite.
for (_, embedding) in &items {
embedding.validate()?;
}
// 3. Quota for the whole batch.
let mut total_growth: u64 = 0;
for (episode, embedding) in &items {
total_growth = total_growth.saturating_add(
(episode.content.len() as u64)
.saturating_add(embedding.data.len() as u64)
.saturating_add(2048),
);
}
match check_quota(self.quota_bytes, self.db_path.as_deref(), total_growth) {
QuotaDecision::Unlimited | QuotaDecision::Allowed { .. } => {}
QuotaDecision::Exceeded {
current_size,
estimated_growth,
quota,
} => {
let err = QuotaExceededError {
current_size,
estimated_growth,
quota,
};
self.emit_audit_best_effort(
AuditOperation::MemoryRememberBatch,
None,
AuditResult::Forbidden,
audit_principal,
Some(err.to_details_json()),
);
return Err(Error::forbidden(err.to_string()));
}
}
// 4. BEGIN IMMEDIATE — the whole batch's INSERTs land atomically.
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| Error::storage(format!("BEGIN IMMEDIATE for remember_batch: {e}")))?;
let now_ms = chrono::Utc::now().timestamp_millis();
let mut memory_ids: Vec<MemoryId> = Vec::with_capacity(items.len());
let mut rowids: Vec<i64> = Vec::with_capacity(items.len());
// 5. Per-item INSERTs.
for (episode, embedding) in &items {
let memory_id = episode.memory_id;
// Redact PII before INSERT. Same trade-off as single Remember:
// the on-disk text and the (pre-computed) embedding may diverge
// by the redaction substitution.
let redaction = self.redactor.redact(&episode.content);
let redacted_content: &str = redaction.text.as_ref();
let encoding_ctx = serde_json::to_string(&episode.encoding_context)
.map_err(|e| Error::storage(format!("serialize encoding_context: {e}")))?;
let provenance_json = match &episode.provenance {
Some(p) => Some(
serde_json::to_string(p)
.map_err(|e| Error::storage(format!("serialize provenance: {e}")))?,
),
None => None,
};
let tier_str = match episode.tier {
Tier::Hot => "hot",
Tier::Warm => "warm",
Tier::Cold => "cold",
};
tx.execute(
"INSERT INTO episodes (
memory_id, ts_ms, source_type, source_id, content,
encoding_context_json, provenance_json, confidence,
strength, salience, tier, created_at_ms, updated_at_ms,
principal_subject
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![
memory_id.to_string(),
episode.ts_ms,
episode.source_type,
episode.source_id,
redacted_content,
encoding_ctx,
provenance_json,
episode.confidence.0,
episode.strength,
episode.salience,
tier_str,
now_ms,
now_ms,
audit_principal.as_deref(),
],
)
.map_err(|e| Error::storage(format!("INSERT episode (batch): {e}")))?;
let rowid = tx.last_insert_rowid();
if let Some(eid) = self.embedder_id {
let dtype_str = match embedding.dtype {
solo_core::EmbeddingDtype::F32 => "f32",
solo_core::EmbeddingDtype::F16 => "f16",
solo_core::EmbeddingDtype::I8 => "i8",
solo_core::EmbeddingDtype::Binary => "binary",
};
tx.execute(
"INSERT INTO embeddings (
memory_id, embedder_id, dtype, dim, vector, created_at_ms
) VALUES (?, ?, ?, ?, ?, ?)",
params![
memory_id.to_string(),
eid,
dtype_str,
embedding.dim as i64,
&embedding.data[..],
now_ms,
],
)
.map_err(|e| Error::storage(format!("INSERT embeddings (batch): {e}")))?;
}
tx.execute(
"INSERT INTO pending_index (
memory_id, embedding, embedding_dim, enqueued_at
) VALUES (?, ?, ?, ?)",
params![
memory_id.to_string(),
&embedding.data[..],
embedding.dim as i64,
now_ms,
],
)
.map_err(|e| Error::storage(format!("INSERT pending_index (batch): {e}")))?;
// Per-item redaction audit row when patterns fired. Same shape
// as single Remember — `details_json` carries pattern-name
// match counts only.
if !redaction.matches.is_empty() {
insert_audit_row_in_tx(
&tx,
&redaction_audit_event(
now_ms,
audit_principal.clone(),
Some(memory_id.to_string()),
&redaction.matches,
),
)?;
}
memory_ids.push(memory_id);
rowids.push(rowid);
}
// 6. ONE batch-level audit row inside the same tx (the dev-log
// 0120 §3 Decision G invariant: one batch = one audit row).
insert_audit_row_in_tx(
&tx,
&AuditEvent {
ts_ms: now_ms,
principal_subject: audit_principal,
operation: AuditOperation::MemoryRememberBatch,
target_id: None,
result: AuditResult::Ok,
details: Some(serde_json::json!({
"item_count": items.len(),
})),
},
)?;
// 7. COMMIT.
tx.commit()
.map_err(|e| Error::storage(format!("COMMIT remember_batch: {e}")))?;
// 8. HNSW.add per item. Dev-log 0152 H3: log-and-continue on
// failure rather than short-circuiting the rest of the batch.
// Items whose HNSW add fails stay in `pending_index` so the
// next-startup replay picks them up. The caller (dispatch)
// uses the returned `hnsw_ok_mask` to decide which items to
// drain. SQL state for every item is already committed, so
// callers always see the full `memory_id` list and won't
// duplicate on retry.
let mut hnsw_ok_mask: Vec<bool> = Vec::with_capacity(items.len());
for ((episode, embedding), rowid) in items.iter().zip(rowids.iter()) {
let f32_slice = match embedding.as_f32_slice() {
Some(s) => s,
None => {
tracing::warn!(
memory_id = %episode.memory_id,
"remember_batch: embedding not F32 — HNSW add skipped; pending_index row left for replay"
);
hnsw_ok_mask.push(false);
continue;
}
};
match self.hnsw.add(episode_hnsw_id(*rowid), f32_slice) {
Ok(()) => hnsw_ok_mask.push(true),
Err(e) => {
tracing::warn!(
error = %e,
memory_id = %episode.memory_id,
"remember_batch: hnsw.add failed; pending_index row left for replay"
);
hnsw_ok_mask.push(false);
}
}
}
Ok((memory_ids, hnsw_ok_mask))
}
fn handle_forget(
&mut self,
memory_id: MemoryId,
reason: String,
audit_principal: Option<String>,
) -> Result<()> {
// Soft-delete: set status='forgotten' on the episode. Per ADR-0003
// Forget reply timing semantics, the HNSW vector is NOT removed
// from the underlying graph — recall paths exclude
// `status='forgotten'` rows by SQL filter, and the architecture
// preserves silent traces for forensics + consolidation.
//
// BUT: we DO mark the rowid in the in-memory tombstone set
// (`HnswIndex::tombstones`). Without this, `index.len()` keeps
// counting the forgotten vector and `detect_drift` spuriously
// warns at runtime. Post-restart `rebuild_tombstones_from_sql`
// does the same thing; runtime tombstoning matches that behaviour.
//
// The `reason` parameter is logged but not persisted. A future
// schema (memory_revisions or forget_log) can record it; v0.1
// surfaces it through tracing only.
//
// v0.8.0 P4: forget is wrapped in a single tx that includes the
// audit row, so the audit emit is atomic with the soft-delete.
let now_ms = chrono::Utc::now().timestamp_millis();
let id_str = memory_id.to_string();
// Look up the rowid first so we can tombstone the HNSW even on
// the already-forgotten / not-found paths. The query is cheap
// (UNIQUE index on memory_id). Reads don't need to live inside
// the tx — they're advisory.
let rowid: Option<i64> = self
.conn
.query_row(
"SELECT rowid FROM episodes WHERE memory_id = ?",
params![&id_str],
|r| r.get::<_, i64>(0),
)
.optional()
.map_err(|e| Error::storage(format!("lookup rowid for forget: {e}")))?;
let Some(rowid) = rowid else {
return Err(Error::not_found(format!(
"memory_id {memory_id} not found in episodes"
)));
};
// BEGIN IMMEDIATE tx wraps the UPDATE + audit row insert. If the
// audit row fails, the UPDATE rolls back — strict ACID.
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| Error::storage(format!("BEGIN IMMEDIATE for forget: {e}")))?;
let updated = tx
.execute(
"UPDATE episodes
SET status = 'forgotten', updated_at_ms = ?
WHERE memory_id = ? AND status <> 'forgotten'",
params![now_ms, &id_str],
)
.map_err(|e| Error::storage(format!("UPDATE episodes for forget: {e}")))?;
insert_audit_row_in_tx(
&tx,
&AuditEvent {
ts_ms: now_ms,
principal_subject: audit_principal,
operation: AuditOperation::MemoryForget,
target_id: Some(id_str.clone()),
result: AuditResult::Ok,
details: Some(serde_json::json!({ "reason": reason })),
},
)?;
tx.commit()
.map_err(|e| Error::storage(format!("COMMIT forget: {e}")))?;
// Tombstone the HNSW. Idempotent for already-tombstoned rowids
// (HashSet::insert just no-ops). The encoded id MUST match the
// one passed at insert time (see `dispatch_remember`).
if let Err(e) = self.hnsw.remove(episode_hnsw_id(rowid)) {
tracing::warn!(
error = %e,
%memory_id,
"hnsw.remove during forget failed (non-fatal; SQL filter still hides the row)"
);
}
if updated == 0 {
// Already forgotten → idempotent success.
tracing::debug!(%memory_id, "forget called on already-forgotten episode (idempotent)");
return Ok(());
}
tracing::info!(%memory_id, %reason, "episode soft-deleted (status=forgotten)");
Ok(())
}
// --------------------------------------------------------------------
// v0.7.0 — document ingest + forget
//
// Same outbox discipline as `dispatch_remember`: the SQL transaction
// commits BEFORE we touch HNSW, the reply goes BEFORE we drain the
// pending_index outbox. If hnsw.add fails the row stays in
// pending_index and replay picks it up next startup; if the DELETE
// drain fails the row stays and replay is idempotent.
//
// See `docs/dev-log/0083-v0.7.0-implementation-plan.md` §2 P3.
// --------------------------------------------------------------------
/// Mirror of `dispatch_remember`: send the reply (durable + HNSW-
/// resident report) BEFORE draining the pending_index outbox rows.
/// Drain failure logs + leaves the rows for next-startup replay.
fn dispatch_ingest_document(
&mut self,
path: std::path::PathBuf,
chunk_config: crate::document::ChunkConfig,
audit_principal: Option<String>,
reply: oneshot::Sender<Result<IngestReport>>,
) {
// Capture the chunk_ids inserted so we can drain only those rows
// (NOT a blanket `DELETE FROM pending_index WHERE kind='chunk'`,
// which would clobber concurrent ingests' in-flight rows).
let (result, drained_chunks) = self.handle_ingest_document_durable(
path,
chunk_config,
audit_principal.clone(),
);
let durable_ok = result.is_ok();
// v0.8.0 P4: error-path audit emit. Success + dedup paths emit
// inside their respective tx / read-only paths.
if let Err(ref e) = result {
self.emit_audit_best_effort(
AuditOperation::MemoryIngestDocument,
None,
AuditResult::Error,
audit_principal,
Some(serde_json::json!({ "error": e.to_string() })),
);
}
let _ = reply.send(result);
// v0.10.0: post-commit invalidation (lesson #30). Both the
// first-ingest and dedup-shortcircuit paths are `durable_ok`;
// both leave the documents listing consistent and warrant a
// refetch (a deduped doc is still a "document exists" signal
// for clients that didn't have it cached).
if durable_ok {
self.emit_invalidate(
AuditOperation::MemoryIngestDocument.as_str(),
"document",
);
}
if durable_ok && !drained_chunks.is_empty() {
for chunk_id in &drained_chunks {
if let Err(e) = self.conn.execute(
"DELETE FROM pending_index WHERE kind = 'chunk' AND chunk_id = ?",
params![chunk_id.to_string()],
) {
tracing::warn!(
error = %e,
%chunk_id,
"pending_index drain (chunk) failed; will replay on next startup"
);
}
}
}
}
/// The body of `IngestDocument`. Returns the report plus the list of
/// chunk_ids whose pending_index rows want draining (empty on the
/// dedup short-circuit and on any error).
///
/// Pipeline:
/// 1. Parse the file (off-tx).
/// 2. Chunk the text (off-tx).
/// 3. Compute content_hash; check `documents.content_hash` for dedup.
/// 4. Embed all chunks via `embedder.embed_batch` (off-tx).
/// 5. BEGIN IMMEDIATE.
/// 6. INSERT documents row.
/// 7. For each chunk: INSERT document_chunks → INSERT chunk_embeddings
/// → INSERT pending_index (kind='chunk').
/// 8. COMMIT.
/// 9. hnsw.add(chunk_rowid, embedding) for each chunk.
/// 10. Caller drains pending_index rows.
fn handle_ingest_document_durable(
&mut self,
path: std::path::PathBuf,
chunk_config: crate::document::ChunkConfig,
audit_principal: Option<String>,
) -> (Result<IngestReport>, Vec<solo_core::ChunkId>) {
// -------- Step 0: SOLO_INGEST_MAX_BYTES guardrail --------
//
// Read the file's size on disk and reject before paying any parse /
// chunk / embed cost when it exceeds the configured cap. The cap is
// a per-file precheck so the writer never holds an oversized
// document in RAM. `SOLO_INGEST_MAX_BYTES=0` disables the cap
// entirely; an unparseable env var falls back to the default with
// a single WARN line.
//
// We deliberately consult `std::fs::metadata(path).len()` rather
// than reading the file twice — `parse_file` will read it again
// immediately after, and the OS page cache makes the second read
// free. Using `metadata().len()` for the precheck also means we
// can reject a multi-GB PDF without ever asking `pdf-extract` to
// allocate.
let file_size: u64 = match std::fs::metadata(&path) {
Ok(meta) => {
let size = meta.len();
if let Some(cap) = resolve_ingest_max_bytes() {
if size > cap {
return (
Err(Error::storage(format!(
"ingest_document: file {} is {size} bytes, exceeds \
SOLO_INGEST_MAX_BYTES cap of {cap} bytes. Set \
SOLO_INGEST_MAX_BYTES=<larger> to override, or \
SOLO_INGEST_MAX_BYTES=0 to disable the cap.",
path.display()
))),
Vec::new(),
);
}
}
size
}
Err(e) => {
return (
Err(Error::storage(format!(
"ingest_document: stat {}: {e}",
path.display()
))),
Vec::new(),
);
}
};
// -------- Step 0.5: per-tenant quota_bytes precheck (v0.8.1 P3) --------
//
// Use the file_size as a conservative growth estimate. Chunks +
// chunk_embeddings + pending_index rows together expand the
// on-disk DB by roughly the parsed text size plus embedding
// overhead (~4 bytes per dim per chunk). 2x file_size gives a
// generous-but-bounded over-count, preferring to surprise
// operators with reject-early rather than reject-mid-ingest.
let ingest_growth_estimate: u64 = file_size.saturating_mul(2);
match check_quota(
self.quota_bytes,
self.db_path.as_deref(),
ingest_growth_estimate,
) {
QuotaDecision::Unlimited | QuotaDecision::Allowed { .. } => {}
QuotaDecision::Exceeded {
current_size,
estimated_growth,
quota,
} => {
let err = QuotaExceededError {
current_size,
estimated_growth,
quota,
};
self.emit_audit_best_effort(
AuditOperation::MemoryIngestDocument,
Some(path.display().to_string()),
AuditResult::Forbidden,
audit_principal,
Some(err.to_details_json()),
);
return (Err(Error::forbidden(err.to_string())), Vec::new());
}
}
// -------- Steps 1 + 2: parse + chunk (pure, off-tx) --------
let parsed = match crate::document::parse_file(&path) {
Ok(p) => p,
Err(e) => {
return (
Err(Error::storage(format!(
"ingest_document: parse {}: {e}",
path.display()
))),
Vec::new(),
);
}
};
let chunks = crate::document::chunk_text(&parsed.text, &chunk_config);
// -------- Step 3: content_hash + dedup pre-check --------
let content_hash = {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(parsed.text.as_bytes());
hex::encode(hasher.finalize())
};
let existing_doc: Option<String> = match self
.conn
.query_row(
"SELECT doc_id FROM documents WHERE content_hash = ? LIMIT 1",
params![&content_hash],
|r| r.get::<_, String>(0),
)
.optional()
{
Ok(v) => v,
Err(e) => {
return (
Err(Error::storage(format!(
"ingest_document: dedup lookup: {e}"
))),
Vec::new(),
);
}
};
if let Some(doc_id_s) = existing_doc {
let doc_id = match solo_core::DocumentId::from_str(&doc_id_s) {
Ok(id) => id,
Err(e) => {
return (
Err(Error::storage(format!(
"ingest_document: parse existing doc_id `{doc_id_s}`: {e}"
))),
Vec::new(),
);
}
};
tracing::info!(
%doc_id,
content_hash = %content_hash,
"ingest_document: dedup hit; returning existing doc_id"
);
// v0.8.0 P4: best-effort audit emit for the dedup short-circuit
// path. No tx of our own to embed it in — the dedup check was
// a read-only lookup. The micro-tx inside `emit_audit_best_effort`
// serializes correctly with any concurrent writer activity.
self.emit_audit_best_effort(
AuditOperation::MemoryIngestDocument,
Some(doc_id.to_string()),
AuditResult::Ok,
audit_principal.clone(),
Some(serde_json::json!({ "deduped": true })),
);
return (
Ok(IngestReport {
doc_id,
chunks_persisted: 0,
bytes_ingested: parsed.byte_size,
deduped: true,
}),
Vec::new(),
);
}
// Need an embedder + runtime to embed chunks. Pure dedup hit above
// doesn't need either — every other path does.
let embedder = match self.embedder.clone() {
Some(e) => e,
None => {
return (
Err(Error::Other(
"ingest_document: writer has no embedder \
(use spawn_full_with_embedder)"
.into(),
)),
Vec::new(),
);
}
};
let runtime = match self.runtime_handle.clone() {
Some(r) => r,
None => {
return (
Err(Error::Other(
"ingest_document: writer has no runtime handle \
(use spawn_full_with_embedder)"
.into(),
)),
Vec::new(),
);
}
};
let embedder_id = match self.embedder_id {
Some(id) => id,
None => {
return (
Err(Error::Other(
"ingest_document: writer has no embedder_id \
(use spawn_full_with_embedder)"
.into(),
)),
Vec::new(),
);
}
};
// Empty document (e.g. only-whitespace would have returned
// ParseError::Empty already, but defensive): nothing to embed.
if chunks.is_empty() {
return (
Err(Error::storage(
"ingest_document: parser returned text but chunker produced 0 chunks",
)),
Vec::new(),
);
}
// -------- Step 3.5: PII redaction (v0.8.0 P5) --------
// Redact each chunk's content BEFORE embedding so the embedding
// matches what lands on disk. Aggregate match counts across all
// chunks into ONE `redaction.applied` audit row per ingest
// (don't spam N rows for N chunks of the same document).
let mut redacted_chunks: Vec<crate::document::ChunkSpec> = Vec::with_capacity(chunks.len());
let mut redaction_match_counts: std::collections::HashMap<String, u32> =
std::collections::HashMap::new();
for spec in &chunks {
let result = self.redactor.redact(&spec.content);
for m in &result.matches {
*redaction_match_counts.entry(m.pattern_name.clone()).or_insert(0) += m.count;
}
let new_content = match result.text {
std::borrow::Cow::Borrowed(_) => spec.content.clone(),
std::borrow::Cow::Owned(s) => s,
};
redacted_chunks.push(crate::document::ChunkSpec {
content: new_content,
token_count: spec.token_count,
start_offset: spec.start_offset,
end_offset: spec.end_offset,
});
}
let chunks = redacted_chunks;
// -------- Step 4: embed batch BEFORE the transaction --------
// Embed-before-tx is the same risk-of-stale-tx pattern called out in
// ADR-0003 §"Reembed batch ordering" — if the embedder fails or
// hangs, no SQL state has changed and the writer is still free to
// serve other commands.
let texts: Vec<&str> = chunks.iter().map(|c| c.content.as_str()).collect();
let embeddings = match runtime.block_on(embedder.embed_batch(&texts)) {
Ok(v) => v,
Err(e) => {
return (
Err(Error::storage(format!(
"ingest_document: embed_batch failed: {e}"
))),
Vec::new(),
);
}
};
if embeddings.len() != chunks.len() {
return (
Err(Error::storage(format!(
"ingest_document: embed_batch returned {} embeddings for {} chunks",
embeddings.len(),
chunks.len()
))),
Vec::new(),
);
}
// Validate every embedding's (dtype, dim, data.len()) before SQL.
for (i, emb) in embeddings.iter().enumerate() {
if let Err(e) = emb.validate() {
return (
Err(Error::storage(format!(
"ingest_document: chunk {i} embedding invalid: {e}"
))),
Vec::new(),
);
}
}
// Cache the dtype string for INSERT INTO chunk_embeddings.
let dtype_str = match embedder.dtype() {
solo_core::EmbeddingDtype::F32 => "f32",
solo_core::EmbeddingDtype::F16 => "f16",
solo_core::EmbeddingDtype::I8 => "i8",
solo_core::EmbeddingDtype::Binary => "binary",
};
// -------- Step 5: allocate ids + open transaction --------
let doc_id = solo_core::DocumentId::new();
let now_ms = chrono::Utc::now().timestamp_millis();
let modified_at_ms: Option<i64> = std::fs::metadata(&path)
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_millis() as i64);
// Title heuristic: first markdown-style heading (`# ...`) on the
// first 64 lines, else the file stem. Filename is more useful than
// "(untitled)" in the typical case.
let title: String = derive_document_title(&parsed.text, &path);
let source: String = path.to_string_lossy().to_string();
let chunk_count = chunks.len() as u32;
// Collect chunk_ids + their assigned rowids for the post-COMMIT
// hnsw.add + drain. We have to pull rowid out of `last_insert_rowid`
// inside the tx; collect the (chunk_id, rowid, embedding) tuples
// for use AFTER the commit.
let mut chunk_records: Vec<(solo_core::ChunkId, i64, solo_core::Embedding)> =
Vec::with_capacity(chunks.len());
let tx = match self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
{
Ok(t) => t,
Err(e) => {
return (
Err(Error::storage(format!(
"ingest_document: BEGIN IMMEDIATE: {e}"
))),
Vec::new(),
);
}
};
// -------- Step 6: INSERT documents row --------
if let Err(e) = tx.execute(
"INSERT INTO documents (
doc_id, source, title, mime_type,
ingested_at_ms, modified_at_ms, status,
chunk_count, content_hash, byte_size
) VALUES (?, ?, ?, ?, ?, ?, 'active', ?, ?, ?)",
params![
doc_id.to_string(),
source,
title,
parsed.mime_type,
now_ms,
modified_at_ms,
chunk_count as i64,
content_hash,
parsed.byte_size as i64,
],
) {
return (
Err(Error::storage(format!(
"ingest_document: INSERT documents: {e}"
))),
Vec::new(),
);
}
// -------- Step 7: INSERT chunk + embedding + pending_index rows --------
for (idx, (spec, embedding)) in chunks.iter().zip(embeddings.iter()).enumerate() {
let chunk_id = solo_core::ChunkId::new();
if let Err(e) = tx.execute(
"INSERT INTO document_chunks (
chunk_id, doc_id, chunk_index, content,
token_count, start_offset, end_offset, created_at_ms,
ingested_by_principal
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![
chunk_id.to_string(),
doc_id.to_string(),
idx as i64,
spec.content,
spec.token_count as i64,
spec.start_offset as i64,
spec.end_offset as i64,
now_ms,
audit_principal.as_deref(),
],
) {
return (
Err(Error::storage(format!(
"ingest_document: INSERT document_chunks (idx {idx}): {e}"
))),
Vec::new(),
);
}
let rowid = tx.last_insert_rowid();
if let Err(e) = tx.execute(
"INSERT INTO chunk_embeddings (
chunk_id, embedder_id, dtype, dim, vector, created_at_ms
) VALUES (?, ?, ?, ?, ?, ?)",
params![
chunk_id.to_string(),
embedder_id,
dtype_str,
embedding.dim as i64,
&embedding.data[..],
now_ms,
],
) {
return (
Err(Error::storage(format!(
"ingest_document: INSERT chunk_embeddings (idx {idx}): {e}"
))),
Vec::new(),
);
}
if let Err(e) = tx.execute(
"INSERT INTO pending_index (
kind, chunk_id, embedding, embedding_dim, enqueued_at
) VALUES ('chunk', ?, ?, ?, ?)",
params![
chunk_id.to_string(),
&embedding.data[..],
embedding.dim as i64,
now_ms,
],
) {
return (
Err(Error::storage(format!(
"ingest_document: INSERT pending_index (idx {idx}): {e}"
))),
Vec::new(),
);
}
chunk_records.push((chunk_id, rowid, embedding.clone()));
}
// -------- Step 7.4: redaction audit emit (v0.8.0 P5) --------
// ONE row aggregating every chunk's matches across the document.
if !redaction_match_counts.is_empty() {
let aggregated: Vec<crate::redaction::RedactionMatch> = redaction_match_counts
.iter()
.map(|(name, count)| crate::redaction::RedactionMatch {
pattern_name: name.clone(),
count: *count,
})
.collect();
if let Err(e) = insert_audit_row_in_tx(
&tx,
&redaction_audit_event(
now_ms,
audit_principal.clone(),
Some(doc_id.to_string()),
&aggregated,
),
) {
return (Err(e), Vec::new());
}
}
// -------- Step 7.5: synchronous audit emit inside tx --------
// v0.8.0 P4. If this fails the surrounding tx aborts via the
// early return below — strict ACID for the audited write.
if let Err(e) = insert_audit_row_in_tx(
&tx,
&AuditEvent {
ts_ms: now_ms,
principal_subject: audit_principal.clone(),
operation: AuditOperation::MemoryIngestDocument,
target_id: Some(doc_id.to_string()),
result: AuditResult::Ok,
details: Some(serde_json::json!({
"chunks_persisted": chunk_count,
"bytes_ingested": parsed.byte_size,
})),
},
) {
return (Err(e), Vec::new());
}
// -------- Step 8: COMMIT --------
if let Err(e) = tx.commit() {
return (
Err(Error::storage(format!(
"ingest_document: COMMIT: {e}"
))),
Vec::new(),
);
}
// -------- Step 9: hnsw.add per chunk --------
// Failure here is non-fatal — the row in pending_index will replay
// on next startup. We log and continue so partial-success-with-
// recoverable-replay matches the steady-state ordering of
// dispatch_remember.
let mut drained: Vec<solo_core::ChunkId> = Vec::with_capacity(chunk_records.len());
for (chunk_id, rowid, embedding) in &chunk_records {
let f32_slice = match embedding.as_f32_slice() {
Some(s) => s,
None => {
tracing::warn!(
%chunk_id,
"ingest_document: chunk embedding is not F32; HNSW add skipped \
(pending_index row will be replayed)"
);
continue;
}
};
// Chunks encode their rowid with the chunk bit set so they
// share the HNSW namespace with episodes without collision.
// See `crate::hnsw_id` for the encoding rationale.
match self.hnsw.add(chunk_hnsw_id(*rowid), f32_slice) {
Ok(_) => drained.push(*chunk_id),
Err(e) => {
tracing::warn!(
%chunk_id,
error = %e,
"ingest_document: hnsw.add failed; pending_index row left for replay"
);
}
}
}
tracing::info!(
%doc_id,
chunks = chunk_records.len(),
indexed = drained.len(),
bytes = parsed.byte_size,
"ingest_document complete"
);
(
Ok(IngestReport {
doc_id,
chunks_persisted: chunk_count,
bytes_ingested: parsed.byte_size,
deduped: false,
}),
drained,
)
}
/// Soft-delete a document. See [`WriteCommand::ForgetDocument`]:
///
/// 1. UPDATE documents SET status='forgotten' WHERE doc_id = ?
/// → 0 rows == Err::NotFound
/// 2. SELECT every chunk's rowid for this document.
/// 3. COMMIT (single-statement UPDATE is effectively atomic).
/// 4. hnsw.remove(rowid) for each chunk — tombstones the in-memory
/// bitmap so `index.len()` accounting stays clean. Failures here
/// are logged + skipped; the SQL `status='forgotten'` filter is
/// the source of truth for queries anyway.
///
/// Idempotent: re-forgetting an already-forgotten doc UPDATEs zero
/// rows but still returns Ok (chunks_tombstoned reflects the chunks
/// found by the SELECT; on second call those are the same chunks
/// whose rowids are already tombstoned — `hnsw.remove` is a HashSet
/// insert so no-ops on re-entry). Returning NotFound only when the
/// doc_id was never in the table.
fn handle_forget_document(
&mut self,
doc_id: solo_core::DocumentId,
audit_principal: Option<String>,
) -> Result<ForgetDocumentReport> {
let id_str = doc_id.to_string();
// Confirm the doc exists; this is also the NotFound check.
let exists: Option<String> = self
.conn
.query_row(
"SELECT status FROM documents WHERE doc_id = ?",
params![&id_str],
|r| r.get::<_, String>(0),
)
.optional()
.map_err(|e| {
Error::storage(format!("forget_document: lookup status: {e}"))
})?;
let Some(prior_status) = exists else {
return Err(Error::not_found(format!(
"doc_id {doc_id} not found in documents"
)));
};
// v0.8.0 P4: wrap the UPDATE + audit row in a tx for ACID.
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| {
Error::storage(format!("forget_document: BEGIN IMMEDIATE: {e}"))
})?;
// UPDATE to forgotten. Idempotent — UPDATEs zero rows when already
// forgotten but we still proceed to tombstone the HNSW.
tx.execute(
"UPDATE documents
SET status = 'forgotten'
WHERE doc_id = ? AND status <> 'forgotten'",
params![&id_str],
)
.map_err(|e| {
Error::storage(format!("forget_document: UPDATE status: {e}"))
})?;
// Synchronous audit row inside the same tx.
insert_audit_row_in_tx(
&tx,
&AuditEvent {
ts_ms: chrono::Utc::now().timestamp_millis(),
principal_subject: audit_principal,
operation: AuditOperation::MemoryForgetDocument,
target_id: Some(id_str.clone()),
result: AuditResult::Ok,
details: None,
},
)?;
tx.commit().map_err(|e| {
Error::storage(format!("forget_document: COMMIT: {e}"))
})?;
// Collect chunk rowids for HNSW tombstone (outside tx — read-only).
let mut stmt = self
.conn
.prepare("SELECT rowid FROM document_chunks WHERE doc_id = ?")
.map_err(|e| {
Error::storage(format!(
"forget_document: prepare chunk-rowid select: {e}"
))
})?;
// Dev-log 0152 M4 (corrected by 0154 audit): propagate per-row
// decode errors instead of silently swallowing via
// `filter_map(|r| r.ok())`. A missed chunk rowid means a missed
// HNSW tombstone — exactly the drift H4's startup rebuild is
// supposed to prevent. Note: the soft-delete UPDATE has ALREADY
// committed at this point (tx.commit() above); propagating the
// decode error here means the caller sees Err while the SQL
// forget is durable. The startup rebuild (H4) covers the missed
// tombstone on next restart, so caller-side retry isn't needed
// for correctness — the error is informational about a bad row.
let rowids: Vec<i64> = stmt
.query_map(params![&id_str], |r| r.get::<_, i64>(0))
.map_err(|e| {
Error::storage(format!(
"forget_document: query chunk rowids: {e}"
))
})?
.collect::<std::result::Result<Vec<i64>, rusqlite::Error>>()
.map_err(|e| {
Error::storage(format!(
"forget_document: decode chunk rowid row: {e}"
))
})?;
let chunks_tombstoned = rowids.len() as u32;
for rowid in rowids {
// The encoded id MUST match the one passed at ingest time
// (see `dispatch_ingest_document`).
if let Err(e) = self.hnsw.remove(chunk_hnsw_id(rowid)) {
tracing::warn!(
rowid,
%doc_id,
error = %e,
"forget_document: hnsw.remove failed (non-fatal; SQL filter still hides chunk)"
);
}
}
if prior_status == "forgotten" {
tracing::debug!(
%doc_id,
"forget_document called on already-forgotten doc (idempotent)"
);
} else {
tracing::info!(
%doc_id,
chunks_tombstoned,
"document soft-deleted (status=forgotten)"
);
}
Ok(ForgetDocumentReport {
doc_id,
chunks_tombstoned,
})
}
fn handle_consolidate(
&mut self,
scope: ConsolidationScope,
audit_principal: Option<String>,
) -> Result<ConsolidationReport> {
// Dev-log 0152 H2: refuse-or-warn when the active embedder is
// the StubEmbedder (32-dim BLAKE3 hash). Cluster membership
// groups episodes by textual hash proximity, not semantic
// similarity — the downstream LLM abstractions look plausible
// but the data backing them is garbage.
//
// The unit-test surface uses the stub extensively, so the guard
// is a loud `tracing::error!` plus a one-shot per-process
// counter rather than a hard refusal. Production operators wire
// log aggregation; the error-level event will trip alerting.
// To get a hard refusal, set SOLO_REFUSE_STUB_EMBEDDER=1.
if let Some(embedder) = self.embedder.as_ref() {
if embedder.name() == crate::embedder::STUB_EMBEDDER_NAME {
if std::env::var_os("SOLO_REFUSE_STUB_EMBEDDER").is_some() {
return Err(Error::invalid_input(
"consolidation refused: StubEmbedder produces \
non-semantic vectors. Set SOLO_EMBEDDER=bundled \
or =ollama, or unset SOLO_REFUSE_STUB_EMBEDDER to \
downgrade this to a warning."
.to_string(),
));
}
tracing::error!(
"consolidation running with StubEmbedder — cluster \
membership is BLAKE3-hash proximity, not semantic. \
Configure SOLO_EMBEDDER=bundled or =ollama for real \
vectors. Set SOLO_REFUSE_STUB_EMBEDDER=1 to make this \
a hard error."
);
}
}
// v0.2.0 implements only the SWS-equivalent clustering pass.
// Abstraction + contradiction-detection (Y.3+) require the
// LLM client; both fields stay 0 in the report.
//
// Discipline mirrors `handle_reembed`: validate state, build
// candidates from SQL, run the pure-deterministic algorithm,
// persist the output in one transaction. Mid-run failures
// bubble up — there's nothing to "skip and continue" inside
// the storage step (we either commit all clusters or none).
let result = self.handle_consolidate_impl(scope);
// v0.8.0 P4: best-effort audit emit after consolidate completes.
// Consolidate spans multiple sub-txes (cluster persist, abstractions,
// contradictions), so we can't embed the audit row inside a single
// tx atomic with "the consolidate". Recording after the fact with
// the result-summary in details is the pragmatic choice.
match &result {
Ok(report) => self.emit_audit_best_effort(
AuditOperation::MemoryConsolidate,
None,
AuditResult::Ok,
audit_principal,
Some(serde_json::json!({
"episodes_seen": report.episodes_seen,
"clusters_built": report.clusters_built,
"abstractions_built": report.abstractions_built,
"triples_built": report.triples_built,
"contradictions_found": report.contradictions_found,
})),
),
Err(e) => self.emit_audit_best_effort(
AuditOperation::MemoryConsolidate,
None,
AuditResult::Error,
audit_principal,
Some(serde_json::json!({ "error": e.to_string() })),
),
}
result
}
/// Body of `handle_consolidate` — the audit-emit wrapper is in
/// `handle_consolidate` so this function stays focused on the
/// consolidation pipeline.
fn handle_consolidate_impl(
&mut self,
scope: ConsolidationScope,
) -> Result<ConsolidationReport> {
let current_id = self.embedder_id.ok_or_else(|| {
Error::Other(
"consolidate: writer has no current embedder_id (use spawn_full_with_embedder)"
.into(),
)
})?;
// v0.9.0 P4a: resolve the active Steward ONCE per consolidate
// tick. Snapshot the Arc here so the merge-plan gate and the
// abstraction loop observe the same Steward identity even if a
// concurrent MCP-initialize-hook write overwrites the slot
// mid-consolidate.
let active_steward: Option<Arc<solo_steward::Steward>> =
self.current_steward();
// Optional time window. Computed BEFORE the SELECT so a slow
// `now_ms` clock doesn't drift candidate selection.
let now_ms = chrono::Utc::now().timestamp_millis();
let cutoff_ms: Option<i64> = scope.window_days.and_then(|days| {
const MS_PER_DAY: i64 = 86_400_000;
days.checked_mul(MS_PER_DAY).map(|w| now_ms - w)
});
// Build candidates: (Episode, Embedding) tuples for active+hot
// rows whose embedding row matches the current embedder. The
// shape mirrors what `solo_steward::cluster::cluster_episodes`
// expects, but we only populate the fields the algorithm reads
// (memory_id, ts_ms) plus those that round-trip cheaply via SQL
// (content). The defaulted fields (provenance, encoding_context,
// confidence/strength/salience, source_id) are not used by the
// SWS pass; Y.3's REM pass will need them and we'll widen this
// SELECT then.
// Idempotency: exclude memories that are already part of a
// cluster. Without this, re-running consolidate on the same
// data set creates duplicate clusters with different UUID v7
// cluster_ids — same shape but two rows per memory in
// `cluster_episodes`, plus wasted LLM `abstract_cluster` calls
// in Y.3. Trade-off: a memory can never be re-clustered once
// it's been placed; cluster-merging across consolidation
// windows is a v0.3 feature ("re-consolidation"). For v0.2.0,
// first-write wins.
let candidates: Vec<(Episode, Embedding)> = {
let (sql, params): (&str, Vec<rusqlite::types::Value>) = match cutoff_ms {
Some(cutoff) => (
"SELECT e.memory_id, e.ts_ms, e.source_type, e.content,
e.confidence, e.strength, e.salience,
em.dtype, em.dim, em.vector
FROM episodes e
JOIN embeddings em ON em.memory_id = e.memory_id
WHERE em.embedder_id = ?1
AND e.status = 'active'
AND e.tier = 'hot'
AND e.ts_ms >= ?2
AND e.memory_id NOT IN (SELECT memory_id FROM cluster_episodes)
ORDER BY e.ts_ms, e.rowid",
vec![current_id.into(), cutoff.into()],
),
None => (
"SELECT e.memory_id, e.ts_ms, e.source_type, e.content,
e.confidence, e.strength, e.salience,
em.dtype, em.dim, em.vector
FROM episodes e
JOIN embeddings em ON em.memory_id = e.memory_id
WHERE em.embedder_id = ?1
AND e.status = 'active'
AND e.tier = 'hot'
AND e.memory_id NOT IN (SELECT memory_id FROM cluster_episodes)
ORDER BY e.ts_ms, e.rowid",
vec![current_id.into()],
),
};
let mut stmt = self
.conn
.prepare(sql)
.map_err(|e| Error::storage(format!("prepare consolidate select: {e}")))?;
let rows = stmt
.query_map(params_from_iter(¶ms), |r| {
let memory_id: String = r.get(0)?;
let ts_ms: i64 = r.get(1)?;
let source_type: String = r.get(2)?;
let content: String = r.get(3)?;
let confidence_f: f32 = r.get(4)?;
let strength: f32 = r.get(5)?;
let salience: f32 = r.get(6)?;
let dtype_str: String = r.get(7)?;
let dim: i64 = r.get(8)?;
let vector: Vec<u8> = r.get(9)?;
Ok((
memory_id,
ts_ms,
source_type,
content,
confidence_f,
strength,
salience,
dtype_str,
dim,
vector,
))
})
.map_err(|e| Error::storage(format!("query_map consolidate: {e}")))?;
let mut out = Vec::new();
for row in rows {
let (memory_id, ts_ms, source_type, content, conf, strength, salience, dtype_str, dim, vector) =
row.map_err(|e| {
Error::storage(format!("consolidate row decode: {e}"))
})?;
let mid = MemoryId::from_str(&memory_id).map_err(|e| {
Error::storage(format!("parse memory_id `{memory_id}`: {e}"))
})?;
let dtype = match dtype_str.as_str() {
"f32" => solo_core::EmbeddingDtype::F32,
"f16" => solo_core::EmbeddingDtype::F16,
"i8" => solo_core::EmbeddingDtype::I8,
"binary" => solo_core::EmbeddingDtype::Binary,
other => {
return Err(Error::storage(format!(
"unknown embeddings.dtype value `{other}`"
)));
}
};
let embedding = Embedding {
dtype,
dim: dim as usize,
data: vector,
};
let confidence = solo_core::Confidence::new(conf).map_err(|e| {
Error::storage(format!("invalid confidence in episodes row: {e}"))
})?;
let episode = Episode {
memory_id: mid,
ts_ms,
source_type,
source_id: None, // not selected; Y.3 will widen
content,
encoding_context: solo_core::EncodingContext::default(),
provenance: None,
confidence,
strength,
salience,
tier: Tier::Hot,
};
out.push((episode, embedding));
}
out
};
let mut report = ConsolidationReport {
episodes_seen: candidates.len(),
..ConsolidationReport::default()
};
if candidates.is_empty() && !scope.force_merge {
tracing::info!(seen = 0, "consolidate: no candidates");
return Ok(report);
}
if candidates.is_empty() {
tracing::info!(
seen = 0,
"consolidate: no candidates, but force_merge set; falling through to merge + regen"
);
}
// Run the pure-deterministic clustering. Threshold + min-size
// resolve from the `Steward`'s captured config when one is
// wired (v0.11.1: this picks up the daemon/CLI's
// `[steward]` TOML + `SOLO_CLUSTER_*` env layering — see
// `StewardConfig::from_settings_then_env`). When no steward is
// attached at all (pure-storage test paths, daemons that never
// wired an LLM AND have no steward_slot population), fall back
// to env-only parsing so the threshold pair is still operator-
// controllable via env on those paths.
//
// The chosen `config` governs uniformly:
// - this clustering pass (new candidates),
// - the in-run `merge_clusters_by_centroid` call below,
// - the existing-vs-existing `plan_existing_merges` further
// down — all three read this same `config`.
//
// The `count_existing_merge_candidates` doctor path takes the
// same resolved config as a parameter — see `merge_candidates`'s
// "Sync requirement" docstring for the SQL+threshold pair.
let config = match active_steward.as_ref() {
Some(s) => s.config().clone(),
None => solo_steward::StewardConfig::from_env()?,
};
let mut clusters = solo_steward::cluster::cluster_episodes(&candidates, &config)?;
// Re-consolidation pass: fold clusters whose centroids are
// above threshold into a single survivor. v0.3 MVP scope is
// **just-built only** — the merge sees only the clusters
// produced by this run, not pre-existing ones in the DB.
// That closes the cross-UTC-day-bucket case (conversations
// straddling midnight produce two same-themed clusters in
// the per-day bucketing). Cross-run merge requires fetching
// existing clusters + abstraction-regeneration plumbing —
// separate iteration.
let absorbed =
solo_steward::cluster::merge_clusters_by_centroid(&mut clusters, &config)?;
report.clusters_merged = absorbed;
if absorbed > 0 {
tracing::info!(
absorbed,
survivors = clusters.len(),
"consolidate: centroid merge collapsed cross-bucket clusters"
);
}
report.clusters_built = clusters.len();
report.episodes_clustered = clusters.iter().map(|c| c.episode_ids.len()).sum();
if clusters.is_empty() {
tracing::info!(
seen = report.episodes_seen,
"consolidate: no new clusters formed; falling through to merge + regen"
);
// No early-return: the existing-vs-existing merge pass
// and the regen pass downstream operate on pre-existing
// DB clusters and can fire even when this run produced
// no fresh clusters (e.g. drift catch-up). The absorb
// pass naturally no-ops on an empty `clusters` Vec.
}
// -------- Cross-run absorb pass --------
//
// For each freshly-built cluster, decide whether it should
// fold into a pre-existing DB cluster with a similar
// centroid (within `cluster_cosine_threshold`). If so:
// - the new cluster gets NO row in `clusters`;
// - its `cluster_episodes` rows link under the existing
// cluster's id;
// - the existing cluster's centroid + coherence refresh
// to the post-absorb weighted mean;
// - the existing cluster's `semantic_abstractions` row is
// DELETED (with cascaded triples) so the next triples-batch
// tick regenerates against the post-absorb episode set.
// Dev-log 0152 M6: previously left in place, which meant
// the abstraction described a stale (pre-absorb) cluster
// forever — the `fetch_clusters_without_abstractions`
// query never picked it up because it still had a row.
//
// The expected_dim for the existing-cluster fetch comes from
// the first candidate's embedding (every candidate uses the
// current embedder's dim, enforced by the SELECT above).
// expected_dim is normally read off the first candidate's
// embedding; with `force_merge` and an empty candidate set
// there's no candidate to read from, so fall back to the
// current embedder's row in the `embedders` table.
let expected_dim = if let Some(c) = candidates.first() {
c.1.dim
} else {
self.conn
.query_row(
"SELECT dim FROM embedders WHERE embedder_id = ?",
params![current_id],
|r| r.get::<_, i64>(0),
)
.map(|d| d as usize)
.map_err(|e| {
Error::storage(format!(
"consolidate force_merge: lookup dim for embedder_id {current_id}: {e}"
))
})?
};
let existing_summaries =
self.fetch_existing_cluster_summaries(cutoff_ms, expected_dim)?;
let absorb_plan = if existing_summaries.is_empty() {
solo_steward::cluster::AbsorbPlan::default()
} else {
solo_steward::cluster::absorb_into_existing(
&clusters,
&existing_summaries,
&config,
)?
};
report.clusters_absorbed = absorb_plan.absorptions.len();
if !absorb_plan.absorptions.is_empty() {
tracing::info!(
absorbed = absorb_plan.absorptions.len(),
existing_modified = absorb_plan.modified_existing_ids().len(),
"consolidate: cross-run absorb folded clusters into existing"
);
}
// Build a quick map: new_cluster_id → AbsorbedCluster, for
// O(1) lookup during the persistence loop.
let absorbed_by_new: std::collections::HashMap<
MemoryId,
&solo_steward::cluster::AbsorbedCluster,
> = absorb_plan
.absorptions
.iter()
.map(|a| (a.new_cluster_id, a))
.collect();
// `clusters_built` should reflect the count of brand-new
// clusters that actually got persisted (non-absorbed). Update
// now that we know the absorb count.
report.clusters_built = clusters.len() - absorb_plan.absorptions.len();
// Persist all clusters in ONE transaction. If any insert fails,
// rollback — partial state would leave dangling cluster_episodes
// referencing nonexistent clusters.
let txn = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| Error::storage(format!("BEGIN consolidate: {e}")))?;
for cluster in &clusters {
// Cross-run absorb: if this freshly-built cluster was
// matched to an existing DB cluster, link its episodes
// under that existing cluster_id and skip the INSERT
// into `clusters`. The existing cluster's centroid +
// coherence refresh happens after this loop in a single
// batched UPDATE step.
if let Some(absorbed) = absorbed_by_new.get(&cluster.cluster_id) {
let target_id_s = absorbed.existing_cluster_id.to_string();
for memid in &cluster.episode_ids {
txn.execute(
"INSERT INTO cluster_episodes (cluster_id, memory_id) VALUES (?, ?)",
params![target_id_s, memid.to_string()],
)
.map_err(|e| {
Error::storage(format!("INSERT cluster_episodes (absorbed): {e}"))
})?;
}
continue;
}
let centroid_dtype: Option<&'static str> = cluster.centroid.as_ref().map(|e| {
match e.dtype {
solo_core::EmbeddingDtype::F32 => "f32",
solo_core::EmbeddingDtype::F16 => "f16",
solo_core::EmbeddingDtype::I8 => "i8",
solo_core::EmbeddingDtype::Binary => "binary",
}
});
let centroid_dim: Option<i64> =
cluster.centroid.as_ref().map(|e| e.dim as i64);
let centroid_blob: Option<&[u8]> =
cluster.centroid.as_ref().map(|e| e.data.as_slice());
txn.execute(
"INSERT INTO clusters (cluster_id, centroid, centroid_dtype, centroid_dim, coherence, created_at_ms)
VALUES (?, ?, ?, ?, ?, ?)",
params![
cluster.cluster_id.to_string(),
centroid_blob,
centroid_dtype,
centroid_dim,
cluster.coherence as f64,
now_ms,
],
)
.map_err(|e| Error::storage(format!("INSERT cluster: {e}")))?;
for memid in &cluster.episode_ids {
txn.execute(
"INSERT INTO cluster_episodes (cluster_id, memory_id) VALUES (?, ?)",
params![cluster.cluster_id.to_string(), memid.to_string()],
)
.map_err(|e| Error::storage(format!("INSERT cluster_episodes: {e}")))?;
}
}
// After the new INSERTs, refresh each modified existing
// cluster's centroid + coherence to the post-absorb values.
// Order: deterministic (sorted by cluster_id) so multi-
// existing absorb runs commit in stable order.
let mut modified_existing: Vec<&solo_steward::cluster::AbsorbedCluster> =
absorb_plan.absorptions.iter().collect();
modified_existing.sort_by(|a, b| a.existing_cluster_id.cmp(&b.existing_cluster_id));
// Only the LAST absorption into a given existing cluster
// carries the final centroid + coherence (the working state
// accumulates step-wise inside `absorb_into_existing`).
// Deduplicate to keep the most recent per existing_cluster_id.
let mut last_per_existing: std::collections::HashMap<
MemoryId,
&solo_steward::cluster::AbsorbedCluster,
> = std::collections::HashMap::new();
for a in &absorb_plan.absorptions {
last_per_existing.insert(a.existing_cluster_id, a);
}
let mut existing_ids_sorted: Vec<MemoryId> =
last_per_existing.keys().copied().collect();
existing_ids_sorted.sort();
for existing_id in existing_ids_sorted {
let absorbed = last_per_existing[&existing_id];
txn.execute(
"UPDATE clusters
SET centroid = ?, centroid_dtype = ?, centroid_dim = ?, coherence = ?
WHERE cluster_id = ?",
params![
absorbed.merged_centroid.data.as_slice(),
"f32",
absorbed.merged_centroid.dim as i64,
absorbed.merged_coherence as f64,
existing_id.to_string(),
],
)
.map_err(|e| Error::storage(format!("UPDATE existing cluster centroid: {e}")))?;
// Dev-log 0152 M6: drop the stale abstraction + cascaded
// triples so the cluster shows up in the next triples-batch
// tick's `fetch_clusters_without_abstractions` query and
// gets regenerated against the post-absorb episode set.
// Without this delete, the existing semantic_abstractions
// row describes a smaller (pre-absorb) cluster indefinitely
// and the triples it generated stay orphaned to the old
// membership.
txn.execute(
"DELETE FROM semantic_abstractions WHERE cluster_id = ?",
params![existing_id.to_string()],
)
.map_err(|e| {
Error::storage(format!(
"DELETE stale abstraction on absorb (cluster {existing_id}): {e}"
))
})?;
txn.execute(
"DELETE FROM triples WHERE cluster_id = ?",
params![existing_id.to_string()],
)
.map_err(|e| {
Error::storage(format!(
"DELETE stale triples on absorb (cluster {existing_id}): {e}"
))
})?;
}
txn.commit()
.map_err(|e| Error::storage(format!("COMMIT consolidate: {e}")))?;
// -------- Existing-vs-existing merge pass --------
//
// Independent of cross-run absorb: detects pre-existing
// clusters whose centroids have drifted close enough to
// coalesce. Runs AFTER absorb so post-absorb centroid
// updates feed in (an absorbed-into existing cluster might
// now be similar to another pre-existing cluster).
//
// For each MergeOp in the plan:
// 1. UPDATE cluster_episodes SET cluster_id = survivor
// WHERE cluster_id IN (loser_ids) — episodes move.
// 2. UPDATE clusters SET centroid + coherence on the
// survivor.
// 3. DELETE FROM clusters WHERE cluster_id IN (loser_ids)
// — cascades drop loser's `cluster_episodes` (now
// empty), `semantic_abstractions`, and `triples`.
//
// Survivor's own stale `semantic_abstractions` + `triples`
// are NOT dropped here — the regen pass below handles them
// identically to absorb-modified survivors.
//
// Skipped if no LLM steward is wired (the regen pass that
// would replace the dropped abstractions only runs with a
// steward; running merge without regen would leave
// survivors in a stale-abstraction state with no recovery
// until the next consolidate). Without a steward the
// existing v0.2-era posture (stale-but-readable
// abstractions) is preserved.
let merge_plan: solo_steward::cluster::MergePlan =
if active_steward.is_some() {
let existing_full =
self.fetch_existing_clusters_full(cutoff_ms, expected_dim)?;
if existing_full.len() < 2 {
solo_steward::cluster::MergePlan::default()
} else {
solo_steward::cluster::plan_existing_merges(
&existing_full,
&config,
)?
}
} else {
solo_steward::cluster::MergePlan::default()
};
report.existing_clusters_merged = merge_plan.absorbed();
if !merge_plan.merges.is_empty() {
tracing::info!(
merges = merge_plan.merges.len(),
absorbed = merge_plan.absorbed(),
"consolidate: existing-vs-existing merge applied"
);
let merge_txn = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| {
Error::storage(format!("BEGIN existing-merge txn: {e}"))
})?;
for op in &merge_plan.merges {
let survivor_str = op.survivor_id.to_string();
// 1. Move episodes from each loser to the survivor.
for loser_id in &op.loser_ids {
merge_txn
.execute(
"UPDATE cluster_episodes
SET cluster_id = ?1
WHERE cluster_id = ?2",
params![survivor_str, loser_id.to_string()],
)
.map_err(|e| {
Error::storage(format!(
"UPDATE cluster_episodes (existing-merge): {e}"
))
})?;
}
// 2. Refresh survivor's centroid + coherence.
merge_txn
.execute(
"UPDATE clusters
SET centroid = ?, centroid_dtype = ?, centroid_dim = ?, coherence = ?
WHERE cluster_id = ?",
params![
op.merged_centroid.data.as_slice(),
"f32",
op.merged_centroid.dim as i64,
op.merged_coherence as f64,
survivor_str,
],
)
.map_err(|e| {
Error::storage(format!(
"UPDATE clusters (existing-merge): {e}"
))
})?;
// 3. DELETE losers — cascades clean their
// `cluster_episodes` (already empty),
// `semantic_abstractions`, and `triples`.
for loser_id in &op.loser_ids {
merge_txn
.execute(
"DELETE FROM clusters WHERE cluster_id = ?",
params![loser_id.to_string()],
)
.map_err(|e| {
Error::storage(format!(
"DELETE clusters (existing-merge): {e}"
))
})?;
}
}
merge_txn
.commit()
.map_err(|e| Error::storage(format!("COMMIT existing-merge: {e}")))?;
}
// -------- v0.9.0 P4b: LLM-driven steps deferred to background batch --------
//
// The v0.8.x writer-actor ran THREE LLM-touching passes inline
// here, blocking the writer thread on `rt.block_on(...)`:
//
// 1. Y.3.3 abstraction loop — `block_on(steward.abstract_cluster)`
// for every new cluster, persisting abstractions + triples.
// 2. Re-abstraction regen — same call for every absorb /
// merge-modified existing cluster.
// 3. Y.4.2 contradiction sweep —
// `block_on(steward.detect_contradiction)` for every
// new-triple pair.
//
// v0.9.0 P4 moves all three to the daemon-side consolidate
// timer (see `crates/solo-cli/src/commands/daemon.rs::
// triples_batch_timer` + `Steward::extract_triples_batch`).
// Rationale (plan §4 P4b):
//
// * `WriteCommand::Consolidate` returns FAST: cluster
// persistence is bounded SQL work; no LLM hop on the
// writer thread.
// * Background batching coalesces N per-cluster LLM calls
// into ⌈N/M⌉ for the sampling backend (P4c's
// `SamplingCoordinator`) — N approval prompts in Claude
// Desktop collapse to one per batch window.
// * `tenant.steward_slot()` is the source of truth (read
// by `self.current_steward()` above); the slot stays
// `Some(_)` for static backends from `TenantHandle::open`
// and gets populated mid-life for the sampling backend
// at MCP-`initialize` time.
//
// The cluster + cluster_episodes INSERTs above ALREADY landed
// when we got here; recall queries see the new clusters
// immediately. Their abstractions + triples land on the
// next consolidate-timer batch tick (`[triples]
// trigger_interval_secs` default 3600s, or
// `trigger_episode_count` default 50 — whichever fires
// first). Documented as "Known behaviour change" in the
// v0.9.0 release notes per plan §3 Decision 2.
//
// `active_steward` resolution above stays for the merge_plan
// gate — that's pure-Rust steward.cluster algorithms, no
// LLM call. The merge-persistence work (lines 2944-3018) ran
// unchanged.
//
// Tests pinning this (in `tests::p4b_no_inline_llm_pins`):
// * `consolidate_command_returns_quickly_without_blocking_on_llm`
// * `triples_extraction_does_not_happen_in_writer_actor_command_path`
let _writer_actor_no_longer_does_llm_inline =
(active_steward.is_some(), self.runtime_handle.is_some());
tracing::info!(
seen = report.episodes_seen,
clusters = report.clusters_built,
episodes_clustered = report.episodes_clustered,
abstractions = report.abstractions_built,
triples = report.triples_built,
contradictions = report.contradictions_found,
"consolidate complete"
);
Ok(report)
}
/// Fetch every triple that shares `(subject_id, predicate)` with
/// the new triple, excluding the new run's batch (passed via
/// `exclude`). Used by `handle_consolidate`'s contradiction sweep
/// to narrow LLM-judge candidates to plausible pairs only.
///
/// Returns reassembled `Triple` structs. Provenance is parsed
/// from the row's `provenance_json` column; on parse failure we
/// substitute a placeholder `Provenance` (the triple is still
/// usable for contradiction detection — the rule filter doesn't
/// touch provenance, and the LLM judge prompt doesn't include
/// it either).
fn fetch_triples_for_pair(
&self,
subject_id: &str,
predicate: &str,
exclude: &std::collections::HashSet<MemoryId>,
) -> Result<Vec<solo_core::Triple>> {
let mut stmt = self
.conn
.prepare(
"SELECT triple_id, object_id, object_kind, valid_from_ms, valid_to_ms,
confidence, provenance_json
FROM triples
WHERE subject_id = ?1 AND predicate = ?2
AND status = 'active'",
)
.map_err(|e| Error::storage(format!("prepare fetch_triples_for_pair: {e}")))?;
let rows = stmt
.query_map(params![subject_id, predicate], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
r.get::<_, i64>(3)?,
r.get::<_, Option<i64>>(4)?,
r.get::<_, f32>(5)?,
r.get::<_, String>(6)?,
))
})
.map_err(|e| Error::storage(format!("query_map triples: {e}")))?;
let mut out = Vec::new();
for row in rows {
let (triple_id_s, object_id, object_kind_s, valid_from_ms, valid_to_ms, conf, prov_s) =
row.map_err(|e| Error::storage(format!("triples row decode: {e}")))?;
let triple_id = MemoryId::from_str(&triple_id_s).map_err(|e| {
Error::storage(format!("parse triple_id `{triple_id_s}`: {e}"))
})?;
if exclude.contains(&triple_id) {
continue;
}
let object_kind = match object_kind_s.as_str() {
"entity" => solo_core::TripleObjectKind::Entity,
"literal" => solo_core::TripleObjectKind::Literal,
other => {
return Err(Error::storage(format!(
"unknown object_kind value `{other}` in triples row"
)));
}
};
let confidence = solo_core::Confidence::new(conf).map_err(|e| {
Error::storage(format!("invalid confidence in triples row: {e}"))
})?;
let provenance: solo_core::Provenance = serde_json::from_str(&prov_s)
.unwrap_or_else(|_| solo_core::Provenance {
derived_from: vec![],
derivation: "(unparseable)".into(),
by: "(unknown)".into(),
at_ms: 0,
});
out.push(solo_core::Triple {
triple_id,
subject_id: subject_id.to_string(),
predicate: predicate.to_string(),
object_id,
object_kind,
valid_from_ms,
valid_to_ms,
confidence,
provenance,
});
}
Ok(out)
}
/// Fetch compact summaries of every existing cluster within the
/// consolidate window. Used by `handle_consolidate`'s cross-run
/// absorb pass to decide which freshly-built clusters fold into
/// pre-existing DB clusters with similar centroids.
///
/// Filters:
///
/// - `cutoff_ms`: when `Some(ms)`, restrict to clusters with
/// `created_at_ms >= ms` (matches the candidate-episode
/// window). When `None`, all clusters in the table.
/// - Centroid must be present (non-null) and dim must equal
/// `expected_dim` — clusters built under a different
/// embedder are skipped (their centroids live in a
/// different vector space and absorb-cosine would be
/// meaningless).
///
/// Returns one row per surviving cluster with its centroid +
/// coherence + episode count. The episode_count is computed via
/// a correlated `COUNT(*)` against `cluster_episodes` — cheap
/// thanks to `idx_cluster_episodes_memory` (well, technically
/// thanks to the `(cluster_id, memory_id)` PRIMARY KEY ordering).
fn fetch_existing_cluster_summaries(
&self,
cutoff_ms: Option<i64>,
expected_dim: usize,
) -> Result<Vec<solo_steward::cluster::ExistingClusterSummary>> {
let (sql, params): (&str, Vec<rusqlite::types::Value>) = match cutoff_ms {
Some(cutoff) => (
"SELECT c.cluster_id, c.centroid, c.centroid_dtype, c.centroid_dim,
c.coherence,
(SELECT COUNT(*) FROM cluster_episodes ce
WHERE ce.cluster_id = c.cluster_id) AS episode_count
FROM clusters c
WHERE c.centroid IS NOT NULL
AND c.centroid_dtype = 'f32'
AND c.centroid_dim = ?1
AND c.created_at_ms >= ?2
ORDER BY c.cluster_id",
vec![(expected_dim as i64).into(), cutoff.into()],
),
None => (
"SELECT c.cluster_id, c.centroid, c.centroid_dtype, c.centroid_dim,
c.coherence,
(SELECT COUNT(*) FROM cluster_episodes ce
WHERE ce.cluster_id = c.cluster_id) AS episode_count
FROM clusters c
WHERE c.centroid IS NOT NULL
AND c.centroid_dtype = 'f32'
AND c.centroid_dim = ?1
ORDER BY c.cluster_id",
vec![(expected_dim as i64).into()],
),
};
let mut stmt = self
.conn
.prepare(sql)
.map_err(|e| Error::storage(format!("prepare existing-cluster summaries: {e}")))?;
let rows = stmt
.query_map(params_from_iter(¶ms), |r| {
Ok((
r.get::<_, String>(0)?, // cluster_id
r.get::<_, Vec<u8>>(1)?, // centroid blob
r.get::<_, String>(2)?, // centroid_dtype
r.get::<_, i64>(3)?, // centroid_dim
r.get::<_, f32>(4)?, // coherence
r.get::<_, i64>(5)?, // episode_count
))
})
.map_err(|e| Error::storage(format!("query_map existing clusters: {e}")))?;
let mut out: Vec<solo_steward::cluster::ExistingClusterSummary> = Vec::new();
for row in rows {
let (cid_s, centroid_bytes, dtype_s, dim_i, coherence, count_i) =
row.map_err(|e| Error::storage(format!("cluster row decode: {e}")))?;
// Defensive: SQL's WHERE already filtered to f32 +
// expected_dim; trust but verify the row contents.
if dtype_s != "f32" || (dim_i as usize) != expected_dim {
continue;
}
let cluster_id = match MemoryId::from_str(&cid_s) {
Ok(id) => id,
Err(e) => {
tracing::warn!(
cluster_id = %cid_s,
error = %e,
"skipping cluster with unparseable cluster_id"
);
continue;
}
};
let centroid = solo_core::Embedding {
dtype: solo_core::EmbeddingDtype::F32,
dim: dim_i as usize,
data: centroid_bytes,
};
// count_i is the exact integer from COUNT(*); negatives
// can't happen, but `as usize` saturates safely on the
// off-chance of an i64 overflow case.
let episode_count = count_i.max(0) as usize;
// Skip clusters with zero episodes (orphaned rows
// shouldn't exist thanks to ON DELETE CASCADE, but
// guarding here keeps absorb math defensible).
if episode_count == 0 {
continue;
}
out.push(solo_steward::cluster::ExistingClusterSummary {
cluster_id,
centroid,
coherence,
episode_count,
});
}
Ok(out)
}
/// Load every existing cluster as a full [`Cluster`] struct
/// (centroid + coherence + complete `episode_ids` Vec). Used by
/// the existing-vs-existing merge pass to feed
/// `solo_steward::cluster::plan_existing_merges`.
///
/// One SELECT joins `clusters` with `cluster_episodes`; rows are
/// aggregated by `cluster_id`. Filters mirror
/// `fetch_existing_cluster_summaries` (centroid present, dtype +
/// dim match the current embedder, optional `created_at_ms` cutoff).
/// Clusters with zero linked episodes are skipped — those are
/// orphan rows that shouldn't exist post-CASCADE invariants.
fn fetch_existing_clusters_full(
&self,
cutoff_ms: Option<i64>,
expected_dim: usize,
) -> Result<Vec<solo_core::Cluster>> {
let (sql, params): (&str, Vec<rusqlite::types::Value>) = match cutoff_ms {
Some(cutoff) => (
"SELECT c.cluster_id, c.centroid, c.centroid_dtype, c.centroid_dim,
c.coherence, ce.memory_id
FROM clusters c
JOIN cluster_episodes ce ON ce.cluster_id = c.cluster_id
WHERE c.centroid IS NOT NULL
AND c.centroid_dtype = 'f32'
AND c.centroid_dim = ?1
AND c.created_at_ms >= ?2
ORDER BY c.cluster_id, ce.memory_id",
vec![(expected_dim as i64).into(), cutoff.into()],
),
None => (
"SELECT c.cluster_id, c.centroid, c.centroid_dtype, c.centroid_dim,
c.coherence, ce.memory_id
FROM clusters c
JOIN cluster_episodes ce ON ce.cluster_id = c.cluster_id
WHERE c.centroid IS NOT NULL
AND c.centroid_dtype = 'f32'
AND c.centroid_dim = ?1
ORDER BY c.cluster_id, ce.memory_id",
vec![(expected_dim as i64).into()],
),
};
let mut stmt = self
.conn
.prepare(sql)
.map_err(|e| Error::storage(format!("prepare existing clusters full: {e}")))?;
let rows = stmt
.query_map(params_from_iter(¶ms), |r| {
Ok((
r.get::<_, String>(0)?, // cluster_id
r.get::<_, Vec<u8>>(1)?, // centroid bytes
r.get::<_, String>(2)?, // dtype
r.get::<_, i64>(3)?, // dim
r.get::<_, f32>(4)?, // coherence
r.get::<_, String>(5)?, // memory_id
))
})
.map_err(|e| Error::storage(format!("query_map clusters full: {e}")))?;
// Aggregate. Rows are ORDER BY cluster_id so we can build
// the output as a single pass.
let mut out: Vec<solo_core::Cluster> = Vec::new();
for row in rows {
let (cid_s, centroid_bytes, dtype_s, dim_i, coherence, memid_s) =
row.map_err(|e| Error::storage(format!("clusters full row decode: {e}")))?;
if dtype_s != "f32" || (dim_i as usize) != expected_dim {
continue;
}
let cluster_id = match MemoryId::from_str(&cid_s) {
Ok(id) => id,
Err(e) => {
tracing::warn!(
cluster_id = %cid_s,
error = %e,
"skipping cluster with unparseable cluster_id"
);
continue;
}
};
let memory_id = match MemoryId::from_str(&memid_s) {
Ok(id) => id,
Err(e) => {
tracing::warn!(
memory_id = %memid_s,
error = %e,
"skipping cluster_episodes row with unparseable memory_id"
);
continue;
}
};
// Append to the in-progress cluster (last entry in
// `out`) when cluster_id matches; otherwise start a new
// entry.
if out.last().map(|c| c.cluster_id) == Some(cluster_id) {
out.last_mut().unwrap().episode_ids.push(memory_id);
} else {
let centroid = solo_core::Embedding {
dtype: solo_core::EmbeddingDtype::F32,
dim: dim_i as usize,
data: centroid_bytes,
};
out.push(solo_core::Cluster {
cluster_id,
episode_ids: vec![memory_id],
centroid: Some(centroid),
coherence,
});
}
}
// Drop empty clusters (defensive — shouldn't happen given
// the JOIN requires at least one cluster_episodes row).
out.retain(|c| !c.episode_ids.is_empty());
Ok(out)
}
/// Load full [`Episode`] structs for every memory_id linked to
/// `cluster_id` via `cluster_episodes`. Used by the absorb→regen
/// path to feed `steward.abstract_cluster` for a cluster whose
/// stale abstraction needs replacing.
///
/// Filters: `episodes.status = 'active'` (forgotten episodes
/// can't drive a fresh abstraction; they get skipped). The
/// SELECT mirrors `handle_consolidate`'s candidate fetch but
/// without the `embedder_id` filter — the regen pass operates
/// on the cluster's full historical episode set, regardless of
/// which embedder produced their vectors.
///
/// Returns episodes ordered by `(ts_ms, rowid)` for
/// deterministic prompts.
fn fetch_episodes_for_cluster(
&self,
cluster_id: &MemoryId,
) -> Result<Vec<Episode>> {
let mut stmt = self
.conn
.prepare(
"SELECT e.memory_id, e.ts_ms, e.source_type, e.source_id,
e.content, e.encoding_context_json, e.provenance_json,
e.confidence, e.strength, e.salience, e.tier
FROM episodes e
JOIN cluster_episodes ce ON ce.memory_id = e.memory_id
WHERE ce.cluster_id = ?1
AND e.status = 'active'
ORDER BY e.ts_ms, e.rowid",
)
.map_err(|e| {
Error::storage(format!("prepare fetch_episodes_for_cluster: {e}"))
})?;
let rows = stmt
.query_map(params![cluster_id.to_string()], |r| {
Ok((
r.get::<_, String>(0)?, // memory_id
r.get::<_, i64>(1)?, // ts_ms
r.get::<_, String>(2)?, // source_type
r.get::<_, Option<String>>(3)?, // source_id
r.get::<_, String>(4)?, // content
r.get::<_, String>(5)?, // encoding_context_json
r.get::<_, Option<String>>(6)?, // provenance_json
r.get::<_, f32>(7)?, // confidence
r.get::<_, f32>(8)?, // strength
r.get::<_, f32>(9)?, // salience
r.get::<_, String>(10)?, // tier
))
})
.map_err(|e| Error::storage(format!("query_map cluster episodes: {e}")))?;
let mut out: Vec<Episode> = Vec::new();
for row in rows {
let (
mid_s,
ts_ms,
source_type,
source_id,
content,
ctx_json,
prov_json,
conf,
strength,
salience,
tier_s,
) = row.map_err(|e| Error::storage(format!("episode row decode: {e}")))?;
let mid = MemoryId::from_str(&mid_s)
.map_err(|e| Error::storage(format!("parse memory_id `{mid_s}`: {e}")))?;
let confidence = solo_core::Confidence::new(conf).map_err(|e| {
Error::storage(format!("invalid confidence in episode row: {e}"))
})?;
let encoding_context: solo_core::EncodingContext =
serde_json::from_str(&ctx_json).unwrap_or_default();
let provenance: Option<solo_core::Provenance> = prov_json
.as_deref()
.and_then(|s| serde_json::from_str(s).ok());
let tier = match tier_s.as_str() {
"hot" => Tier::Hot,
"warm" => Tier::Warm,
"cold" => Tier::Cold,
other => {
return Err(Error::storage(format!(
"unknown tier value `{other}` in episodes row"
)));
}
};
out.push(Episode {
memory_id: mid,
ts_ms,
source_type,
source_id,
content,
encoding_context,
provenance,
confidence,
strength,
salience,
tier,
});
}
Ok(out)
}
fn handle_reembed(
&mut self,
scope: ReembedScope,
audit_principal: Option<String>,
) -> Result<ReembedReport> {
let result = self.handle_reembed_impl(scope);
// v0.8.0 P4: best-effort audit emit after reembed completes.
// Reembed spans many sub-batches; recording one summary row at
// the end is the pragmatic shape.
match &result {
Ok(report) => self.emit_audit_best_effort(
AuditOperation::MemoryReembed,
None,
AuditResult::Ok,
audit_principal,
Some(serde_json::json!({
"rows_seen": report.rows_seen,
"rows_reembedded": report.rows_reembedded,
"rows_failed": report.rows_failed,
"rows_gc_deleted": report.rows_gc_deleted,
"dry_run": report.dry_run,
})),
),
Err(e) => self.emit_audit_best_effort(
AuditOperation::MemoryReembed,
None,
AuditResult::Error,
audit_principal,
Some(serde_json::json!({ "error": e.to_string() })),
),
}
result
}
fn handle_reembed_impl(&mut self, scope: ReembedScope) -> Result<ReembedReport> {
// Reembed needs the writer to have been spawned with the active
// embedder + a runtime handle (see `spawn_full_with_embedder`).
// The plain `spawn_full` constructor leaves these `None`, which
// is the correct posture for daemon paths that don't dispatch
// Reembed. A clean error here beats a panic.
let current_id = self.embedder_id.ok_or_else(|| {
Error::Other(
"reembed: writer has no current embedder_id (use spawn_full_with_embedder)"
.into(),
)
})?;
let embedder = self.embedder.clone().ok_or_else(|| {
Error::Other(
"reembed: writer has no embedder (use spawn_full_with_embedder)".into(),
)
})?;
let runtime = self.runtime_handle.clone().ok_or_else(|| {
Error::Other(
"reembed: writer has no runtime handle (use spawn_full_with_embedder)"
.into(),
)
})?;
// Optional `from` filter → resolve to embedder_id once. Refuse if
// the user asked to migrate from "current to current" (nothing
// would happen) or if the from-embedder isn't registered.
let from_id: Option<i64> = match &scope.from {
None => None,
Some((name, version)) => {
let id: Option<i64> = self
.conn
.query_row(
"SELECT embedder_id FROM embedders WHERE name = ? AND version = ?",
params![name, version],
|r| r.get::<_, i64>(0),
)
.optional()
.map_err(|e| Error::storage(format!("lookup from embedder: {e}")))?;
match id {
Some(id) if id == current_id => {
return Err(Error::Other(format!(
"reembed: from-embedder ({name}, {version}) IS the current \
embedder; nothing to do"
)));
}
Some(id) => Some(id),
None => {
return Err(Error::not_found(format!(
"reembed: from-embedder ({name}, {version}) not registered \
in `embedders` table"
)));
}
}
}
};
// Build the candidate set. DISTINCT — a memory may have multiple
// stale rows (if the user has rolled through more than one prior
// embedder); we only want to embed each content once.
let candidates: Vec<(String, String)> = {
let (sql, bound_id): (&str, i64) = match from_id {
None => (
"SELECT DISTINCT e.memory_id, e.content
FROM episodes e
JOIN embeddings em ON em.memory_id = e.memory_id
WHERE em.embedder_id != ?1
AND e.status = 'active'
ORDER BY e.rowid",
current_id,
),
Some(fid) => (
"SELECT DISTINCT e.memory_id, e.content
FROM episodes e
JOIN embeddings em ON em.memory_id = e.memory_id
WHERE em.embedder_id = ?1
AND e.status = 'active'
ORDER BY e.rowid",
fid,
),
};
let mut stmt = self
.conn
.prepare(sql)
.map_err(|e| Error::storage(format!("prepare reembed select: {e}")))?;
let rows = stmt
.query_map(params![bound_id], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
})
.map_err(|e| Error::storage(format!("query_map reembed: {e}")))?;
let mut out = Vec::new();
for row in rows {
out.push(
row.map_err(|e| Error::storage(format!("reembed row decode: {e}")))?,
);
}
out
};
let mut report = ReembedReport {
rows_seen: candidates.len(),
rows_reembedded: 0,
rows_failed: 0,
rows_gc_deleted: 0,
dry_run: scope.dry_run,
};
if scope.dry_run {
tracing::info!(
seen = report.rows_seen,
"reembed --dry-run: would re-embed N memories"
);
return Ok(report);
}
// Cache the dtype string for the current embedder once.
let dtype_str = match embedder.dtype() {
solo_core::EmbeddingDtype::F32 => "f32",
solo_core::EmbeddingDtype::F16 => "f16",
solo_core::EmbeddingDtype::I8 => "i8",
solo_core::EmbeddingDtype::Binary => "binary",
};
let now_ms = chrono::Utc::now().timestamp_millis();
// Per-memory loop. Embed (async, off the writer thread via the
// captured runtime handle), then atomically apply the SQL changes
// for that memory. A failure on one memory does NOT abort the
// run — partial progress is fine because the next reembed pass
// picks up wherever we left off (the SELECT re-evaluates the
// candidate set at start). The per-memory transaction means a
// mid-run crash cannot leave a memory with two `current`
// embedding rows or with the new row but missing the GC.
for (memory_id, content) in candidates {
let embedding_res = runtime.block_on(embedder.embed(&content));
let new_embedding = match embedding_res {
Ok(emb) => emb,
Err(e) => {
tracing::warn!(%memory_id, error = %e, "reembed: embedder failed");
report.rows_failed += 1;
continue;
}
};
if let Err(e) = new_embedding.validate() {
tracing::warn!(%memory_id, error = %e, "reembed: embedding validate failed");
report.rows_failed += 1;
continue;
}
let txn = match self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
{
Ok(t) => t,
Err(e) => {
tracing::warn!(%memory_id, error = %e, "reembed: BEGIN failed");
report.rows_failed += 1;
continue;
}
};
// INSERT ... ON CONFLICT(memory_id, embedder_id) DO UPDATE.
// If a partial earlier reembed already wrote the current row
// for this memory, refresh it with the freshly-computed
// vector. (Same content + same embedder = same vector, so
// this is a no-op semantically; we still bump created_at_ms.)
let insert_res = txn.execute(
"INSERT INTO embeddings (memory_id, embedder_id, dtype, dim, vector, created_at_ms)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(memory_id, embedder_id) DO UPDATE SET
dtype = excluded.dtype,
dim = excluded.dim,
vector = excluded.vector,
created_at_ms = excluded.created_at_ms",
params![
memory_id,
current_id,
dtype_str,
new_embedding.dim as i64,
&new_embedding.data[..],
now_ms,
],
);
if let Err(e) = insert_res {
tracing::warn!(%memory_id, error = %e, "reembed: INSERT failed");
report.rows_failed += 1;
continue;
}
let gc_count = if scope.gc {
match txn.execute(
"DELETE FROM embeddings
WHERE memory_id = ? AND embedder_id != ?",
params![memory_id, current_id],
) {
Ok(n) => n,
Err(e) => {
tracing::warn!(%memory_id, error = %e, "reembed: GC DELETE failed");
report.rows_failed += 1;
continue;
}
}
} else {
0
};
if let Err(e) = txn.commit() {
tracing::warn!(%memory_id, error = %e, "reembed: COMMIT failed");
report.rows_failed += 1;
continue;
}
report.rows_reembedded += 1;
report.rows_gc_deleted += gc_count;
}
tracing::info!(
seen = report.rows_seen,
reembedded = report.rows_reembedded,
failed = report.rows_failed,
gc_deleted = report.rows_gc_deleted,
"reembed complete"
);
Ok(report)
}
/// Implementation of `WriteCommand::NormalizeSubjects`.
///
/// One transaction wraps every `(from, to)` pair so the entire
/// backfill is atomic. For each pair: run the symmetric
/// `subject_id` and `object_id` UPDATEs, accumulate row counts.
/// In `dry_run` mode the transaction is `ROLLBACK`ed at the end;
/// otherwise it commits.
///
/// SQL uses parameterized statements (`?1`, `?2`) — alias strings
/// never reach SQL via `format!`, so this is injection-safe even
/// for adversarial alias values.
///
/// A single triple where `subject_id == object_id == from` is
/// counted as one subject row + one object row (count of 2 against
/// that triple), matching what SQLite's `changes()` reports for the
/// two separate UPDATEs.
fn handle_normalize_subjects(
&mut self,
aliases: Vec<(String, String)>,
dry_run: bool,
audit_principal: Option<String>,
) -> Result<NormalizeReport> {
let mut report = NormalizeReport {
aliases_processed: aliases.len(),
subject_rows_updated: 0,
object_rows_updated: 0,
dry_run,
};
// Empty alias list: nothing to do, no transaction needed.
// Mirrors the "zero candidates" short-circuit in handle_reembed.
if aliases.is_empty() {
tracing::info!(dry_run, "normalize_subjects: empty alias list, no-op");
// v0.8.0 P4: still record the audit row even for the no-op.
self.emit_audit_best_effort(
AuditOperation::MemoryNormalizeSubjects,
None,
AuditResult::Ok,
audit_principal,
Some(serde_json::json!({
"aliases_processed": 0,
"dry_run": dry_run,
})),
);
return Ok(report);
}
let tx = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate)
.map_err(|e| {
Error::storage(format!("BEGIN IMMEDIATE for normalize_subjects: {e}"))
})?;
for (from, to) in &aliases {
let subj_rows = tx
.execute(
"UPDATE triples SET subject_id = ?1, updated_at_ms = ?3 \
WHERE subject_id = ?2",
params![to, from, chrono::Utc::now().timestamp_millis()],
)
.map_err(|e| {
Error::storage(format!(
"normalize_subjects: UPDATE subject_id ({from} -> {to}): {e}"
))
})?;
let obj_rows = tx
.execute(
"UPDATE triples SET object_id = ?1, updated_at_ms = ?3 \
WHERE object_id = ?2",
params![to, from, chrono::Utc::now().timestamp_millis()],
)
.map_err(|e| {
Error::storage(format!(
"normalize_subjects: UPDATE object_id ({from} -> {to}): {e}"
))
})?;
report.subject_rows_updated += subj_rows;
report.object_rows_updated += obj_rows;
}
if dry_run {
// Dry-run: rollback the UPDATE; emit a best-effort audit row
// OUTSIDE the rolled-back tx. We want the audit trail to
// record the dry-run invocation even though no data changed.
tx.rollback().map_err(|e| {
Error::storage(format!(
"normalize_subjects: ROLLBACK after dry-run: {e}"
))
})?;
tracing::info!(
aliases_processed = report.aliases_processed,
subject_rows = report.subject_rows_updated,
object_rows = report.object_rows_updated,
"normalize_subjects --dry-run: rolled back (would have updated N rows)"
);
self.emit_audit_best_effort(
AuditOperation::MemoryNormalizeSubjects,
None,
AuditResult::Ok,
audit_principal,
Some(serde_json::json!({
"aliases_processed": report.aliases_processed,
"subject_rows_updated": report.subject_rows_updated,
"object_rows_updated": report.object_rows_updated,
"dry_run": true,
})),
);
} else {
// Non-dry: synchronous audit emit INSIDE the same tx so the
// audit row is atomic with the actual rewrite.
insert_audit_row_in_tx(
&tx,
&AuditEvent {
ts_ms: chrono::Utc::now().timestamp_millis(),
principal_subject: audit_principal,
operation: AuditOperation::MemoryNormalizeSubjects,
target_id: None,
result: AuditResult::Ok,
details: Some(serde_json::json!({
"aliases_processed": report.aliases_processed,
"subject_rows_updated": report.subject_rows_updated,
"object_rows_updated": report.object_rows_updated,
"dry_run": false,
})),
},
)?;
tx.commit().map_err(|e| {
Error::storage(format!("normalize_subjects: COMMIT: {e}"))
})?;
tracing::info!(
aliases_processed = report.aliases_processed,
subject_rows = report.subject_rows_updated,
object_rows = report.object_rows_updated,
"normalize_subjects complete"
);
}
Ok(report)
}
fn handle_backup(&mut self, dest_path: &std::path::Path) -> Result<()> {
let key = self.key.as_ref().ok_or_else(|| {
Error::storage(
"backup called but writer has no key material configured. \
Spawn the writer with `spawn_full_with_key_and_optional_steward` \
to enable WriteCommand::Backup.",
)
})?;
// Important: route through the writer's existing source connection
// so the backup runs against live in-flight WAL state via SQLite's
// page-level snapshot. SQLite serialises page reads with concurrent
// writes on the same connection, so this is safe even mid-burst.
backup_from_connection(&self.conn, dest_path, key)
}
fn handle_save_snapshot(&mut self) -> Result<()> {
let dir = self.snapshot_dir.as_ref().ok_or_else(|| {
Error::storage("save_snapshot called but writer has no snapshot_dir configured")
})?;
// Delegates to the impl's `save` (HnswIndex routes to crate::snapshot).
// The trait keeps us implementation-agnostic; the StubVectorIndex used
// in unit tests just bumps a counter.
let save_result = self.hnsw.save(dir);
// Piggyback maintenance pragmas on the snapshot cadence (5 min by
// default). ADR-0003 §O5 / §"Final consolidated action items" #9
// call for hourly `PRAGMA optimize` + idle PASSIVE checkpoint.
// Running them every 5 min instead of hourly is harmless (both are
// cheap when there's nothing to do) and avoids a separate timer
// task. Failures are logged but don't fail the save itself —
// they're maintenance, not durability.
self.run_idle_maintenance();
save_result
}
/// Best-effort PRAGMA optimize + wal_checkpoint(PASSIVE). Safe to call
/// on the writer's connection at any time.
fn run_idle_maintenance(&mut self) {
if let Err(e) = self.conn.execute_batch("PRAGMA optimize") {
tracing::debug!(error = %e, "PRAGMA optimize failed (non-fatal)");
}
if let Err(e) = self.conn.execute_batch("PRAGMA wal_checkpoint(PASSIVE)") {
tracing::debug!(error = %e, "PRAGMA wal_checkpoint(PASSIVE) failed (non-fatal)");
}
}
/// Emit a best-effort audit row outside any surrounding transaction.
/// Used by error paths whose write transaction has already aborted —
/// the audit row records the failure but isn't atomic with it (there
/// was no successful write to be atomic *with*). Logged + swallowed
/// on failure: an audit-table failure must not turn a soft error
/// into a hard one.
///
/// Synchronous emit via the writer's own connection — same
/// SQLCipher session, no extra round-trip. Wraps the INSERT in a
/// micro-tx so it doesn't accidentally inherit autocommit state.
/// v0.10.0: fan out one `InvalidateEvent` on the per-tenant
/// broadcast channel. Called by every mutation handler dispatcher
/// AFTER the writer-actor's commit returns `Ok` (lesson #30:
/// rolled-back writes MUST NOT produce events). Drops silently
/// when:
///
/// * the writer was spawned without an invalidate channel (every
/// pure-storage test path); OR
/// * the broadcast `send` fails because there are zero
/// subscribers (the normal idle state — no solo-web clients
/// connected). `broadcast::Sender::send` returns `Err` only
/// for "no receivers", which we treat as a no-op.
///
/// `reason` is the canonical `AuditOperation::as_str()` form;
/// `kind` is the solo-web node kind ("episode" / "document" /
/// "chunk" / "cluster" / "triple" / "tenant").
fn emit_invalidate(&self, reason: &str, kind: &str) {
let (Some(tx), Some(tenant_id)) =
(&self.invalidate_tx, &self.invalidate_tenant_id)
else {
return;
};
let event = InvalidateEvent {
reason: reason.to_string(),
tenant_id: tenant_id.clone(),
ts_ms: chrono::Utc::now().timestamp_millis(),
kind: kind.to_string(),
};
// `Err` from `send` means zero subscribers — fine, drop it. The
// SSE handler maps `RecvError::Lagged(n)` to a structured
// "missed N events" log on the subscriber side.
let _ = tx.send(event);
}
fn emit_audit_best_effort(
&mut self,
operation: AuditOperation,
target_id: Option<String>,
result: AuditResult,
principal: Option<String>,
details: Option<serde_json::Value>,
) {
let event = AuditEvent {
ts_ms: chrono::Utc::now().timestamp_millis(),
principal_subject: principal,
operation,
target_id,
result,
details,
};
let tx_res = self
.conn
.transaction_with_behavior(TransactionBehavior::Immediate);
let tx = match tx_res {
Ok(t) => t,
Err(e) => {
tracing::warn!(
error = %e,
operation = %operation,
"audit emit: BEGIN IMMEDIATE failed; dropping audit row"
);
return;
}
};
if let Err(e) = insert_audit_row_in_tx(&tx, &event) {
tracing::warn!(
error = %e,
operation = %operation,
"audit emit: INSERT failed; dropping audit row"
);
return;
}
if let Err(e) = tx.commit() {
tracing::warn!(
error = %e,
operation = %operation,
"audit emit: COMMIT failed; dropping audit row"
);
}
}
fn shutdown(&mut self) {
if let Err(e) = self
.conn
.pragma_update(None, "wal_checkpoint", "TRUNCATE")
{
tracing::warn!(error = %e, "wal_checkpoint(TRUNCATE) on shutdown failed");
}
tracing::info!("writer actor shutdown complete");
}
}
/// v0.8.0 P5: build the `redaction.applied` audit event from a list of
/// per-pattern match counts. The details JSON shape is:
///
/// ```json
/// { "matches": [ {"pattern_name": "email", "count": 2}, ... ] }
/// ```
///
/// **No matched substrings here** — the writer's
/// `audit_row_does_not_contain_original_pii` test enforces it by
/// asserting `details_json` doesn't contain the original PII.
fn redaction_audit_event(
ts_ms: i64,
principal_subject: Option<String>,
target_id: Option<String>,
matches: &[crate::redaction::RedactionMatch],
) -> AuditEvent {
let details_matches: Vec<serde_json::Value> = matches
.iter()
.map(|m| {
serde_json::json!({
"pattern_name": m.pattern_name,
"count": m.count,
})
})
.collect();
AuditEvent {
ts_ms,
principal_subject,
operation: AuditOperation::RedactionApplied,
target_id,
result: AuditResult::Ok,
details: Some(serde_json::json!({ "matches": details_matches })),
}
}
/// Pick a `documents.title` from the parsed text + source path. Prefer
/// the first Markdown-style `# heading` line in the first 64 lines of
/// the document; fall back to the file stem; fall back to "(untitled)".
fn derive_document_title(text: &str, path: &std::path::Path) -> String {
for (i, line) in text.lines().enumerate() {
if i >= 64 {
break;
}
let trimmed = line.trim_start();
if let Some(rest) = trimmed.strip_prefix('#') {
// Consume any number of leading #s.
let body = rest.trim_start_matches('#').trim();
if !body.is_empty() {
// Markdown headings can have a trailing # run; strip it.
let clean = body.trim_end_matches('#').trim();
if !clean.is_empty() {
return clean.to_string();
}
}
}
}
path.file_stem()
.and_then(|s| s.to_str())
.map(|s| s.to_string())
.unwrap_or_else(|| "(untitled)".to_string())
}
/// v0.8.1 P3: structured payload for a quota rejection. Carries the
/// concrete numbers the operator needs to act on (current usage,
/// requested growth, configured cap). Stored verbatim in the audit
/// row's `details_json` and rendered into the human-facing error text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct QuotaExceededError {
pub current_size: u64,
pub estimated_growth: u64,
pub quota: u64,
}
impl QuotaExceededError {
/// JSON shape stored in the audit row's `details_json` column.
/// Field names match the `--quota-bytes` CLI flag's vocabulary so
/// operators reading audit logs see a self-consistent term set.
pub fn to_details_json(self) -> serde_json::Value {
serde_json::json!({
"reason": "quota_exceeded",
"current_size": self.current_size,
"estimated_growth": self.estimated_growth,
"quota": self.quota,
})
}
}
impl std::fmt::Display for QuotaExceededError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"tenant quota_bytes={} would be exceeded (current_size={}, estimated_growth={}). \
Increase the quota via `solo tenants set-quota <id> --bytes <N>` or \
`--unlimited`.",
self.quota, self.current_size, self.estimated_growth
)
}
}
/// v0.8.1 P3: outcome of a per-write quota check. The writer-actor's
/// growth-bearing handlers (`handle_remember`, `handle_ingest_document_
/// durable`) consult this before INSERT — when the new payload would
/// push the tenant's on-disk DB size over the configured quota, the
/// write is rejected with a structured error that translates to a
/// `result = 'forbidden'` audit row.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum QuotaDecision {
/// No quota configured (unlimited) — the default for tenants
/// created without `--quota-bytes`. Common case; one branch.
Unlimited,
/// Quota set; current usage + estimated growth fits under the cap.
/// Allow the write to proceed.
Allowed { current_size: u64, quota: u64 },
/// Quota set; current usage + estimated growth would cross the
/// cap. Reject with a structured error. The current_size /
/// estimated_growth / quota tuple lands in the audit row's
/// `details_json` for operator visibility.
Exceeded {
current_size: u64,
estimated_growth: u64,
quota: u64,
},
}
/// v0.8.1 P3: check whether a payload of `estimated_growth` bytes would
/// keep the tenant under its `quota_bytes`. Reads the current on-disk
/// DB size via `metadata().len()` — same shape as the
/// `SOLO_INGEST_MAX_BYTES` precheck in `handle_ingest_document_durable`.
///
/// Returns `QuotaDecision::Unlimited` when no quota is configured (the
/// hot path). The `db_path` argument can be `None` for test spawns that
/// don't go through the production open path; in that case enforcement
/// is conservatively skipped.
///
/// The check is strict `>` (not `>=`): a write that exactly hits the
/// quota is allowed. Operators set quotas with strict upper-bound
/// semantics — `--quota-bytes 1048576` means "don't exceed 1 MiB",
/// not "stop one byte before".
pub(crate) fn check_quota(
quota_bytes: Option<u64>,
db_path: Option<&std::path::Path>,
estimated_growth: u64,
) -> QuotaDecision {
let Some(quota) = quota_bytes else {
return QuotaDecision::Unlimited;
};
let Some(path) = db_path else {
// Test-only spawn path with no db_path. Enforcement skipped
// rather than failing hard — the prod path always wires it.
return QuotaDecision::Unlimited;
};
let current_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
if current_size.saturating_add(estimated_growth) > quota {
QuotaDecision::Exceeded {
current_size,
estimated_growth,
quota,
}
} else {
QuotaDecision::Allowed {
current_size,
quota,
}
}
}
/// v0.8.1 P1: resolve the first `derived_from` memory_id in a triple's
/// provenance to an `episodes.rowid` so the new `source_episode_id` FK
/// can be populated on INSERT. Returns `None` when:
///
/// * the provenance has no `derived_from` entries (the LLM didn't
/// extract a back-reference);
/// * the first `derived_from` memory_id doesn't resolve to a live
/// episode row (forgotten, never persisted, schema drift).
///
/// The caller wires `None` into the INSERT as a NULL `source_episode_id`,
/// which is the documented orphan-by-design shape. The GDPR cascade
/// (`gdpr::forget_principal`) reports null-source triples through
/// `ForgetReport::triples_orphan_null_source` for operator visibility.
fn resolve_source_episode_id(
conn: &rusqlite::Connection,
provenance: &solo_core::Provenance,
) -> Option<i64> {
let first = provenance.derived_from.first()?;
let memory_id_str = first.to_string();
conn.query_row(
"SELECT rowid FROM episodes WHERE memory_id = ?",
params![memory_id_str],
|r| r.get::<_, i64>(0),
)
.optional()
.ok()
.flatten()
}
/// Same as [`resolve_source_episode_id`] but runs inside an active
/// transaction (the writer's INSERT path needs to see uncommitted
/// inserts from the same tx).
fn resolve_source_episode_id_in_tx(
tx: &rusqlite::Transaction<'_>,
provenance: &solo_core::Provenance,
) -> Option<i64> {
let first = provenance.derived_from.first()?;
let memory_id_str = first.to_string();
tx.query_row(
"SELECT rowid FROM episodes WHERE memory_id = ?",
params![memory_id_str],
|r| r.get::<_, i64>(0),
)
.optional()
.ok()
.flatten()
}
#[cfg(test)]
mod tests {
use super::*;
#[allow(unused_imports)]
use crate::test_support::{
StubVectorIndex, disabled_test_redactor, enabled_test_redactor, fixture_episode,
fixture_embedding, open_test_db,
};
use std::time::Duration;
fn rt() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap()
}
#[test]
fn remember_happy_path_round_trip() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(StubVectorIndex::new(4));
let WriterSpawn { handle, join: _ } = WriterActor::spawn(conn, hnsw.clone());
let episode = fixture_episode("test content");
let embedding = fixture_embedding(4);
let mid = rt()
.block_on(handle.remember(episode.clone(), embedding))
.unwrap();
assert_eq!(mid, episode.memory_id);
std::thread::sleep(Duration::from_millis(50));
drop(handle);
std::thread::sleep(Duration::from_millis(50));
assert_eq!(hnsw.add_count(), 1);
let added = hnsw.last_added().unwrap();
assert_eq!(added.0, 1, "rowid should be 1 (first insert)");
assert_eq!(added.1.len(), 4);
}
#[test]
fn dispatch_remember_replies_before_drain() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
let (reply_tx, reply_rx) = oneshot::channel();
let episode = fixture_episode("ordering test");
let embedding = fixture_embedding(4);
actor.dispatch_remember(episode.clone(), embedding, None, reply_tx);
let received = reply_rx.blocking_recv().unwrap();
assert_eq!(received.unwrap(), episode.memory_id);
let n: u32 = actor
.conn
.query_row("SELECT COUNT(*) FROM pending_index", [], |row| row.get(0))
.unwrap();
assert_eq!(n, 0);
}
#[test]
fn forget_unknown_memory_id_returns_not_found() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(StubVectorIndex::new(4));
let WriterSpawn { handle, join: _ } = WriterActor::spawn(conn, hnsw);
let mid = MemoryId::new();
let err = rt()
.block_on(handle.forget(mid, "test".into()))
.unwrap_err();
assert!(err.to_string().contains("not found"), "got: {err}");
}
#[test]
fn forget_marks_status_forgotten() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(StubVectorIndex::new(4));
let WriterSpawn { handle, join: _ } = WriterActor::spawn(conn, hnsw.clone());
let episode = fixture_episode("to be forgotten");
let mid = rt()
.block_on(handle.remember(episode.clone(), fixture_embedding(4)))
.unwrap();
rt().block_on(handle.forget(mid, "no longer relevant".into()))
.unwrap();
// Re-open the file (writer holds the DB connection; test-side reopen
// gets read access via SQLite's WAL).
// We can't peek into the writer's connection, so close everything and
// re-open via open_test_db_at on the underlying path. But open_test_db
// returned us an in-memory tmp; we need a different fixture.
// Simpler: use the StubVectorIndex's add_count to verify the embed
// happened, and trust that the handle.forget Ok return means the
// UPDATE ran. The full SQL roundtrip is exercised by the
// reader.rs::reader_sees_writes_committed_through_writer_actor test
// pattern, which we don't replicate here.
assert_eq!(hnsw.add_count(), 1);
let _ = mid; // ensure we exercised the codepath; status check is in
// the reader-pool test below.
}
#[test]
fn forget_is_idempotent_when_already_forgotten() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(StubVectorIndex::new(4));
let WriterSpawn { handle, join: _ } = WriterActor::spawn(conn, hnsw);
let episode = fixture_episode("forget twice");
let mid = rt()
.block_on(handle.remember(episode, fixture_embedding(4)))
.unwrap();
rt().block_on(handle.forget(mid, "first".into())).unwrap();
// Second call: still Ok (idempotent), no error.
rt().block_on(handle.forget(mid, "second".into())).unwrap();
}
#[test]
fn many_concurrent_writes_serialize_correctly() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(StubVectorIndex::new(4));
let WriterSpawn { handle, join: _ } = WriterActor::spawn(conn, hnsw.clone());
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(4)
.enable_all()
.build()
.unwrap();
let results: Vec<Result<MemoryId>> = runtime.block_on(async {
let mut tasks = Vec::new();
for i in 0..50 {
let h = handle.clone();
let ep = fixture_episode(&format!("write {i}"));
tasks.push(tokio::spawn(async move {
h.remember(ep, fixture_embedding(4)).await
}));
}
let mut out = Vec::new();
for t in tasks {
out.push(t.await.unwrap());
}
out
});
let mut ids = std::collections::HashSet::new();
for r in results {
let mid = r.expect("remember must succeed");
assert!(ids.insert(mid), "memory_ids must be unique");
}
assert_eq!(ids.len(), 50);
assert_eq!(hnsw.add_count(), 50);
}
// -- normalize_subjects -------------------------------------------------
//
// Test pattern: drive the handle_normalize_subjects path **directly** on
// a hand-built WriterActor. The plain `WriterActor::spawn` path owns its
// connection on the writer thread, which would block read-back queries
// in the same process. Direct invocation lets us:
//
// 1. Seed triples via the same connection the actor will mutate.
// 2. Call `handle_normalize_subjects` on `&mut actor`.
// 3. Query `actor.conn` afterwards to assert row contents.
//
// The dispatch arm itself is so thin (one match arm, one method call)
// that exercising the method directly covers the same path the public
// `WriteHandle::normalize_subjects` would take.
/// Helper: seed a triple row with a given subject/object. Returns the
/// triple_id so tests can read it back. `cluster_id` is left NULL —
/// FK is `ON DELETE CASCADE` but NULLs don't reference anything.
fn seed_triple(
conn: &Connection,
triple_id: &str,
subject: &str,
predicate: &str,
object: &str,
object_kind: &str,
) {
let now_ms = chrono::Utc::now().timestamp_millis();
conn.execute(
"INSERT INTO triples (
triple_id, subject_id, predicate, object_id, object_kind,
valid_from_ms, valid_to_ms, confidence, provenance_json,
created_at_ms, updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?)",
params![
triple_id,
subject,
predicate,
object,
object_kind,
now_ms,
0.9_f64,
"{}",
now_ms,
now_ms,
],
)
.expect("seed triple");
}
/// Helper: read back `subject_id` for a known triple_id. Panics if not
/// found — tests should always seed before reading.
fn read_subject(conn: &Connection, triple_id: &str) -> String {
conn.query_row(
"SELECT subject_id FROM triples WHERE triple_id = ?",
params![triple_id],
|r| r.get::<_, String>(0),
)
.expect("read subject_id")
}
/// Helper: read back `object_id` for a known triple_id.
fn read_object(conn: &Connection, triple_id: &str) -> String {
conn.query_row(
"SELECT object_id FROM triples WHERE triple_id = ?",
params![triple_id],
|r| r.get::<_, String>(0),
)
.expect("read object_id")
}
/// Helper: build a `WriterActor` directly (no spawned thread) so tests
/// can call `handle_normalize_subjects` and then query the same
/// connection in the same thread.
fn build_actor_inline(conn: Connection) -> WriterActor {
let (_tx, rx) = mpsc::channel(1);
let hnsw = Arc::new(StubVectorIndex::new(4));
WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
}
}
#[test]
fn normalize_subjects_updates_subject_column() {
let (conn, _tmp) = open_test_db();
seed_triple(&conn, "t1", "alex", "uses", "rust", "literal");
let mut actor = build_actor_inline(conn);
let report = actor
.handle_normalize_subjects(
vec![("alex".into(), "user".into())],
false,
None,
)
.expect("normalize ok");
assert_eq!(report.aliases_processed, 1);
assert_eq!(report.subject_rows_updated, 1);
assert_eq!(report.object_rows_updated, 0);
assert!(!report.dry_run);
assert_eq!(read_subject(&actor.conn, "t1"), "user");
assert_eq!(read_object(&actor.conn, "t1"), "rust");
}
#[test]
fn normalize_subjects_updates_object_column() {
let (conn, _tmp) = open_test_db();
// Object position: someone-uses-alex (object_kind=entity).
seed_triple(&conn, "t1", "bob", "knows", "alex", "entity");
let mut actor = build_actor_inline(conn);
let report = actor
.handle_normalize_subjects(
vec![("alex".into(), "user".into())],
false,
None,
)
.expect("normalize ok");
assert_eq!(report.subject_rows_updated, 0);
assert_eq!(report.object_rows_updated, 1);
assert_eq!(read_subject(&actor.conn, "t1"), "bob");
assert_eq!(read_object(&actor.conn, "t1"), "user");
}
#[test]
fn normalize_subjects_updates_both_when_subject_equals_object() {
// Self-loop: subject == object == "alex". The two UPDATEs both fire
// against the same row — count is 2 (one for each column rewrite),
// matching what SQLite's `changes()` reports per statement.
let (conn, _tmp) = open_test_db();
seed_triple(&conn, "t1", "alex", "is", "alex", "entity");
let mut actor = build_actor_inline(conn);
let report = actor
.handle_normalize_subjects(
vec![("alex".into(), "user".into())],
false,
None,
)
.expect("normalize ok");
assert_eq!(report.subject_rows_updated, 1);
assert_eq!(report.object_rows_updated, 1);
assert_eq!(read_subject(&actor.conn, "t1"), "user");
assert_eq!(read_object(&actor.conn, "t1"), "user");
}
#[test]
fn normalize_subjects_dry_run_rolls_back() {
let (conn, _tmp) = open_test_db();
seed_triple(&conn, "t1", "alex", "uses", "rust", "literal");
seed_triple(&conn, "t2", "bob", "knows", "alex", "entity");
let mut actor = build_actor_inline(conn);
let report = actor
.handle_normalize_subjects(
vec![("alex".into(), "user".into())],
true,
None,
)
.expect("dry-run normalize ok");
// Counts reflect would-have-been-updated:
assert!(report.dry_run);
assert_eq!(report.subject_rows_updated, 1);
assert_eq!(report.object_rows_updated, 1);
// But the rows are unchanged — transaction rolled back.
assert_eq!(read_subject(&actor.conn, "t1"), "alex");
assert_eq!(read_object(&actor.conn, "t1"), "rust");
assert_eq!(read_subject(&actor.conn, "t2"), "bob");
assert_eq!(read_object(&actor.conn, "t2"), "alex");
}
#[test]
fn normalize_subjects_multiple_aliases() {
let (conn, _tmp) = open_test_db();
seed_triple(&conn, "t1", "alex", "uses", "rust", "literal");
seed_triple(&conn, "t2", "bob", "uses", "python", "literal");
seed_triple(&conn, "t3", "charlie", "knows", "alex", "entity");
let mut actor = build_actor_inline(conn);
let report = actor
.handle_normalize_subjects(
vec![
("alex".into(), "user".into()),
("bob".into(), "user".into()),
],
false,
None,
)
.expect("normalize ok");
assert_eq!(report.aliases_processed, 2);
// t1.subject (alex→user) + t2.subject (bob→user) = 2 subject rows
assert_eq!(report.subject_rows_updated, 2);
// t3.object (alex→user) = 1 object row
assert_eq!(report.object_rows_updated, 1);
assert_eq!(read_subject(&actor.conn, "t1"), "user");
assert_eq!(read_subject(&actor.conn, "t2"), "user");
assert_eq!(read_object(&actor.conn, "t3"), "user");
// charlie (subject of t3) was not in the alias map.
assert_eq!(read_subject(&actor.conn, "t3"), "charlie");
}
#[test]
fn normalize_subjects_no_match_returns_zero_counts() {
let (conn, _tmp) = open_test_db();
seed_triple(&conn, "t1", "alex", "uses", "rust", "literal");
let mut actor = build_actor_inline(conn);
let report = actor
.handle_normalize_subjects(
vec![("nobody".into(), "user".into())],
false,
None,
)
.expect("normalize ok");
assert_eq!(report.aliases_processed, 1);
assert_eq!(report.subject_rows_updated, 0);
assert_eq!(report.object_rows_updated, 0);
// Existing rows untouched.
assert_eq!(read_subject(&actor.conn, "t1"), "alex");
}
#[test]
fn normalize_subjects_empty_alias_list_is_noop() {
let (conn, _tmp) = open_test_db();
seed_triple(&conn, "t1", "alex", "uses", "rust", "literal");
let mut actor = build_actor_inline(conn);
let report = actor
.handle_normalize_subjects(vec![], false, None)
.expect("normalize ok");
assert_eq!(report.aliases_processed, 0);
assert_eq!(report.subject_rows_updated, 0);
assert_eq!(report.object_rows_updated, 0);
assert_eq!(read_subject(&actor.conn, "t1"), "alex");
}
#[test]
fn normalize_subjects_via_handle_round_trip() {
// End-to-end: dispatch through `WriteHandle::normalize_subjects`
// so we cover the variant + dispatch arm + handle method together.
let (conn, tmp) = open_test_db();
seed_triple(&conn, "t1", "alex", "uses", "rust", "literal");
seed_triple(&conn, "t2", "bob", "knows", "alex", "entity");
// Drop the seed connection so the writer's connection (opened from
// the same path) has exclusive write access. We re-open at the end
// to verify.
drop(conn);
let conn = crate::test_support::open_test_db_at(&tmp.path().join("test.db"));
let hnsw = Arc::new(StubVectorIndex::new(4));
let WriterSpawn { handle, join } = WriterActor::spawn(conn, hnsw);
let report = rt()
.block_on(handle.normalize_subjects(
vec![("alex".into(), "user".into())],
false,
))
.expect("normalize via handle");
assert_eq!(report.subject_rows_updated, 1);
assert_eq!(report.object_rows_updated, 1);
drop(handle);
join.join().expect("writer thread joins");
// Verify via a fresh read connection (writer's connection is now
// closed because the actor's thread exited).
let conn = crate::test_support::open_test_db_at(&tmp.path().join("test.db"));
let subj: String = conn
.query_row(
"SELECT subject_id FROM triples WHERE triple_id = 't1'",
[],
|r| r.get(0),
)
.unwrap();
let obj: String = conn
.query_row(
"SELECT object_id FROM triples WHERE triple_id = 't2'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(subj, "user");
assert_eq!(obj, "user");
}
// ====================================================================
// v0.7.0 P3 — IngestDocument + ForgetDocument + recovery replay
//
// Test pattern: each test builds a WriterActor directly with a real
// StubEmbedder + a fresh tokio runtime handle (the writer's
// dispatch_ingest_document calls `runtime.block_on(embedder.embed_batch)`,
// so it needs a Handle). For tests that don't call `handle.ingest_document`
// on a separate writer thread, we drive the handler synchronously via
// `actor.dispatch_ingest_document` after constructing the actor in-place
// — matching the `normalize_subjects` pattern further up.
// ====================================================================
use crate::document::ChunkConfig;
use crate::embedder::StubEmbedder;
use crate::embedder_registry::{EmbedderIdentity, get_or_insert_embedder_id};
use solo_core::{ChunkId, DocumentId, Embedder};
/// Build an actor with a stub embedder wired up + the embedders row
/// registered. Returns the actor plus a kept-alive runtime (drop the
/// returned tuple together).
fn build_ingest_actor(
conn: Connection,
) -> (WriterActor, tokio::runtime::Runtime, Arc<StubVectorIndex>) {
// Use a multi-thread runtime so the writer's block_on doesn't
// deadlock when the calling thread happens to be a worker.
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let handle = runtime.handle().clone();
let embedder: Arc<dyn Embedder> = Arc::new(StubEmbedder::new("stub", "v1", 4));
let identity = EmbedderIdentity::from_embedder(embedder.as_ref());
let embedder_id = get_or_insert_embedder_id(&conn, &identity).unwrap();
let hnsw = Arc::new(StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let actor = WriterActor {
conn,
hnsw: hnsw.clone(),
rx,
snapshot_dir: None,
embedder_id: Some(embedder_id),
embedder: Some(embedder),
runtime_handle: Some(handle),
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
(actor, runtime, hnsw)
}
/// Write a small markdown document under `tmp` and return its path.
fn write_markdown(tmp: &tempfile::TempDir, name: &str, body: &str) -> std::path::PathBuf {
let path = tmp.path().join(name);
std::fs::write(&path, body).expect("write fixture");
path
}
/// Embedder that always returns Err — used for the embed-failure rollback test.
#[derive(Debug)]
struct FailingEmbedder {
dim: usize,
}
#[async_trait::async_trait]
impl Embedder for FailingEmbedder {
fn name(&self) -> &str {
"fail"
}
fn version(&self) -> &str {
"v1"
}
fn dim(&self) -> usize {
self.dim
}
fn dtype(&self) -> solo_core::EmbeddingDtype {
solo_core::EmbeddingDtype::F32
}
async fn embed_batch(
&self,
_texts: &[&str],
) -> Result<Vec<Embedding>> {
Err(solo_core::Error::embedder("forced failure for test"))
}
}
// ----- Ingest tests -----
#[test]
fn ingest_document_persists_doc_and_chunks() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(
&docs_tmp,
"intro.md",
"# Intro\n\nFirst paragraph here.\n\nSecond paragraph here.\n",
);
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path.clone(), ChunkConfig::default(), None, reply_tx);
let report = reply_rx.blocking_recv().unwrap().expect("ingest ok");
assert!(!report.deduped);
assert_eq!(report.chunks_persisted, 1, "tiny doc → one chunk");
assert!(report.bytes_ingested > 0);
// documents row exists with status=active.
let (status, title, chunk_count): (String, String, i64) = actor
.conn
.query_row(
"SELECT status, title, chunk_count FROM documents WHERE doc_id = ?",
params![report.doc_id.to_string()],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.unwrap();
assert_eq!(status, "active");
assert_eq!(title, "Intro", "first markdown heading becomes title");
assert_eq!(chunk_count, 1);
// document_chunks row count matches.
let n_chunks: i64 = actor
.conn
.query_row(
"SELECT COUNT(*) FROM document_chunks WHERE doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(n_chunks, 1);
// chunk_embeddings row count matches.
let n_emb: i64 = actor
.conn
.query_row(
"SELECT COUNT(*) FROM chunk_embeddings ce
JOIN document_chunks dc ON dc.chunk_id = ce.chunk_id
WHERE dc.doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(n_emb, 1);
// HNSW got an add.
assert_eq!(hnsw.add_count(), 1);
}
#[test]
fn ingest_document_pending_index_drains_cleanly() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "doc.md", "# Doc\n\nBody text.\n");
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let _ = reply_rx.blocking_recv().unwrap().expect("ingest ok");
let pending: i64 = actor
.conn
.query_row(
"SELECT COUNT(*) FROM pending_index WHERE kind = 'chunk'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(pending, 0, "pending_index chunk rows fully drained");
}
#[test]
fn ingest_document_is_idempotent_by_content_hash() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "same.md", "# Same\n\nDeterministic body.\n");
// First ingest.
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path.clone(), ChunkConfig::default(), None, reply_tx);
let report1 = reply_rx.blocking_recv().unwrap().unwrap();
assert!(!report1.deduped);
assert_eq!(report1.chunks_persisted, 1);
let hnsw_after_first = hnsw.add_count();
// Re-ingest — dedup, no new chunks, no HNSW add.
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let report2 = reply_rx.blocking_recv().unwrap().unwrap();
assert!(report2.deduped);
assert_eq!(report2.doc_id, report1.doc_id);
assert_eq!(report2.chunks_persisted, 0);
assert_eq!(
hnsw.add_count(),
hnsw_after_first,
"dedup hit must not embed or add to HNSW"
);
// Documents table still has exactly ONE row.
let n_docs: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM documents", [], |r| r.get(0))
.unwrap();
assert_eq!(n_docs, 1);
}
#[test]
fn ingest_document_rolls_back_on_embed_failure() {
// Build the actor manually with FailingEmbedder.
let (conn, _tmp) = open_test_db();
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let handle = runtime.handle().clone();
let embedder: Arc<dyn Embedder> = Arc::new(FailingEmbedder { dim: 4 });
let identity = EmbedderIdentity::from_embedder(embedder.as_ref());
let embedder_id = get_or_insert_embedder_id(&conn, &identity).unwrap();
let hnsw = Arc::new(StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw: hnsw.clone(),
rx,
snapshot_dir: None,
embedder_id: Some(embedder_id),
embedder: Some(embedder),
runtime_handle: Some(handle),
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "fail.md", "# Fail\n\nBody.\n");
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let err = reply_rx.blocking_recv().unwrap().unwrap_err();
assert!(err.to_string().contains("embed_batch"), "got: {err}");
// No documents persisted (embed-before-tx ordering proves no SQL state).
let n_docs: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM documents", [], |r| r.get(0))
.unwrap();
assert_eq!(n_docs, 0);
let n_chunks: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM document_chunks", [], |r| r.get(0))
.unwrap();
assert_eq!(n_chunks, 0);
let n_pending: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM pending_index", [], |r| r.get(0))
.unwrap();
assert_eq!(n_pending, 0);
// HNSW unchanged.
assert_eq!(hnsw.add_count(), 0);
}
#[test]
fn ingest_document_large_document() {
// Force multi-chunk: ~10 paragraphs at ~50 chars each → ~500 chars
// > target=80 → multiple chunks.
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let mut body = String::from("# Header\n\n");
for i in 0..30 {
body.push_str(&format!(
"Paragraph number {i} with several words in it.\n\n"
));
}
let path = write_markdown(&docs_tmp, "big.md", &body);
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(
path,
ChunkConfig {
target_tokens: 80,
overlap_tokens: 10,
},
None,
reply_tx,
);
let report = reply_rx.blocking_recv().unwrap().unwrap();
assert!(
report.chunks_persisted >= 2,
"expected multi-chunk, got {}",
report.chunks_persisted
);
let n_chunks: i64 = actor
.conn
.query_row(
"SELECT COUNT(*) FROM document_chunks WHERE doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(n_chunks as u32, report.chunks_persisted);
assert_eq!(hnsw.add_count() as u32, report.chunks_persisted);
}
#[test]
fn ingest_document_uses_first_heading_as_title() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(
&docs_tmp,
"any_name.md",
"Preamble line without heading.\n\n## Sub Section Title\n\nBody.\n",
);
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let report = reply_rx.blocking_recv().unwrap().unwrap();
let title: String = actor
.conn
.query_row(
"SELECT title FROM documents WHERE doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(
title, "Sub Section Title",
"title comes from first heading line"
);
}
#[test]
fn ingest_document_records_file_mtime() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "mtime.md", "# T\n\nBody.\n");
let fs_mtime_ms = std::fs::metadata(&path)
.unwrap()
.modified()
.unwrap()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_millis() as i64;
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let report = reply_rx.blocking_recv().unwrap().unwrap();
let modified_at_ms: Option<i64> = actor
.conn
.query_row(
"SELECT modified_at_ms FROM documents WHERE doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
let m = modified_at_ms.expect("modified_at_ms must be set when file mtime is readable");
// File-system mtime resolution varies; allow ±2 sec slack.
assert!(
(m - fs_mtime_ms).abs() < 2_000,
"modified_at_ms drift: db={m} fs={fs_mtime_ms}"
);
}
#[test]
fn ingest_document_unsupported_extension_errors_cleanly() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = docs_tmp.path().join("blob.bin");
std::fs::write(&path, b"\x00\x01\x02").unwrap();
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let err = reply_rx.blocking_recv().unwrap().unwrap_err();
assert!(
err.to_string().contains("parse") || err.to_string().contains("extension"),
"unsupported extension should surface as a parse error: {err}"
);
// No SQL or HNSW state changed.
let n_docs: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM documents", [], |r| r.get(0))
.unwrap();
assert_eq!(n_docs, 0);
assert_eq!(hnsw.add_count(), 0);
}
#[test]
fn ingest_document_writes_embedding_dim_correctly() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "dim.md", "# Dim\n\nText.\n");
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let report = reply_rx.blocking_recv().unwrap().unwrap();
let dim: i64 = actor
.conn
.query_row(
"SELECT ce.dim FROM chunk_embeddings ce
JOIN document_chunks dc ON dc.chunk_id = ce.chunk_id
WHERE dc.doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(dim, 4, "stub embedder dim is 4");
let dtype: String = actor
.conn
.query_row(
"SELECT ce.dtype FROM chunk_embeddings ce
JOIN document_chunks dc ON dc.chunk_id = ce.chunk_id
WHERE dc.doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(dtype, "f32");
}
// ----- Forget tests -----
#[test]
fn forget_document_sets_status_forgotten() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "f.md", "# F\n\nBody.\n");
let (tx, rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, tx);
let report = rx.blocking_recv().unwrap().unwrap();
let forget_report = actor.handle_forget_document(report.doc_id, None).unwrap();
assert_eq!(forget_report.doc_id, report.doc_id);
assert_eq!(forget_report.chunks_tombstoned, report.chunks_persisted);
let status: String = actor
.conn
.query_row(
"SELECT status FROM documents WHERE doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(status, "forgotten");
}
#[test]
fn forget_document_tombstones_hnsw_rowids() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "t.md", "# T\n\nBody.\n");
let (tx, rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, tx);
let report = rx.blocking_recv().unwrap().unwrap();
let added_before = hnsw.add_count();
let removed_before = hnsw.remove_count();
let _ = actor.handle_forget_document(report.doc_id, None).unwrap();
// remove_count should be at least the chunks_persisted, since one
// hnsw.remove call per chunk fired.
assert_eq!(
hnsw.remove_count() - removed_before,
report.chunks_persisted as usize
);
assert_eq!(hnsw.add_count(), added_before, "forget must not add");
}
#[test]
fn forget_document_unknown_doc_id_returns_not_found() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let err = actor
.handle_forget_document(DocumentId::new(), None)
.unwrap_err();
assert!(err.to_string().contains("not found"), "got: {err}");
}
#[test]
fn forget_document_idempotent() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "idem.md", "# Idem\n\nBody.\n");
let (tx, rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, tx);
let report = rx.blocking_recv().unwrap().unwrap();
let r1 = actor.handle_forget_document(report.doc_id, None).unwrap();
let r2 = actor.handle_forget_document(report.doc_id, None).unwrap();
assert_eq!(r1.doc_id, r2.doc_id);
assert_eq!(r1.chunks_tombstoned, r2.chunks_tombstoned);
// Still forgotten.
let status: String = actor
.conn
.query_row(
"SELECT status FROM documents WHERE doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(status, "forgotten");
}
#[test]
fn ingest_document_then_forget_then_reingest_same_content_hash_dedups_forgotten_doc() {
// Document chosen behavior: a forgotten doc still wins content-hash
// dedup. Re-ingest returns the SAME (forgotten) doc_id without
// resurrecting it. Operators who want a fresh active doc must
// ingest under a different content (or future `restore` command).
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "fr.md", "# FR\n\nBody.\n");
let (tx, rx) = oneshot::channel();
actor.dispatch_ingest_document(path.clone(), ChunkConfig::default(), None, tx);
let report1 = rx.blocking_recv().unwrap().unwrap();
let _ = actor.handle_forget_document(report1.doc_id, None).unwrap();
let adds_before = hnsw.add_count();
let (tx, rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, tx);
let report2 = rx.blocking_recv().unwrap().unwrap();
assert!(report2.deduped, "forgotten doc still wins dedup");
assert_eq!(report2.doc_id, report1.doc_id);
assert_eq!(report2.chunks_persisted, 0);
assert_eq!(
hnsw.add_count(),
adds_before,
"dedup hit must not add (even though doc is forgotten)"
);
// Doc remains forgotten — re-ingest did NOT resurrect.
let status: String = actor
.conn
.query_row(
"SELECT status FROM documents WHERE doc_id = ?",
params![report1.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(status, "forgotten");
}
// ----- Recovery replay tests -----
/// Helper: insert a `documents` row + N `document_chunks` rows + N
/// `pending_index` (kind='chunk') rows, and return the chunk rowids
/// the test should expect after replay. The pending rows hold the
/// chunks' embeddings; the chunk rows themselves carry no embedding
/// (the chunk_embeddings table is empty in this helper — replay only
/// reads pending_index).
fn seed_pending_chunks(
conn: &Connection,
doc_id: &str,
chunk_dim: usize,
n: usize,
) -> Vec<i64> {
let now_ms = chrono::Utc::now().timestamp_millis();
conn.execute(
"INSERT INTO documents (
doc_id, source, title, mime_type,
ingested_at_ms, modified_at_ms, status,
chunk_count, content_hash, byte_size
) VALUES (?, ?, ?, ?, ?, NULL, 'active', ?, ?, ?)",
params![
doc_id,
"test://source",
"test",
"text/plain",
now_ms,
n as i64,
format!("{doc_id}_hash"),
100i64,
],
)
.unwrap();
let mut rowids = Vec::with_capacity(n);
for i in 0..n {
let chunk_id = ChunkId::new().to_string();
conn.execute(
"INSERT INTO document_chunks (
chunk_id, doc_id, chunk_index, content,
token_count, start_offset, end_offset, created_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
params![
chunk_id,
doc_id,
i as i64,
format!("chunk {i} text"),
3i64,
(i * 10) as i64,
((i + 1) * 10) as i64,
now_ms,
],
)
.unwrap();
let rowid = conn.last_insert_rowid();
rowids.push(rowid);
let zeros = vec![0u8; chunk_dim * 4];
conn.execute(
"INSERT INTO pending_index (
kind, chunk_id, embedding, embedding_dim, enqueued_at
) VALUES ('chunk', ?, ?, ?, ?)",
params![chunk_id, &zeros[..], chunk_dim as i64, now_ms + i as i64],
)
.unwrap();
}
rowids
}
#[test]
fn recovery_replay_handles_chunk_pending_rows() {
let (mut conn, _tmp) = open_test_db();
let rowids = seed_pending_chunks(&conn, "11111111-1111-1111-1111-111111111111", 4, 3);
let stub = StubVectorIndex::new(4);
let report = crate::recovery::replay_pending_index(&mut conn, &stub).unwrap();
assert_eq!(report.rows_seen, 3);
assert_eq!(report.rows_replayed, 3);
assert_eq!(report.rows_failed, 0);
// All chunk rowids landed in HNSW, encoded with the chunk-kind
// discriminator (high bit set) per `crate::hnsw_id`. The raw
// rowids returned by SQL are translated through `chunk_hnsw_id`
// by the recovery replay loop.
let added: std::collections::HashSet<i64> =
stub.entries().iter().map(|(r, _)| *r).collect();
let expected: std::collections::HashSet<i64> = rowids
.iter()
.copied()
.map(crate::hnsw_id::chunk_hnsw_id)
.collect();
assert_eq!(added, expected);
// pending_index is drained.
let n: i64 = conn
.query_row("SELECT COUNT(*) FROM pending_index", [], |r| r.get(0))
.unwrap();
assert_eq!(n, 0);
}
#[test]
fn recovery_replay_handles_mixed_episode_and_chunk_rows() {
let (mut conn, _tmp) = open_test_db();
// Seed 2 episodes (with pending rows).
let now_ms = chrono::Utc::now().timestamp_millis();
let mut episode_rowids = Vec::new();
for content in &["ep_a", "ep_b"] {
let ep = fixture_episode(content);
let mid = ep.memory_id.to_string();
conn.execute(
"INSERT INTO episodes (
memory_id, ts_ms, source_type, source_id, content,
encoding_context_json, provenance_json, confidence,
strength, salience, tier, created_at_ms, updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![
mid,
ep.ts_ms,
ep.source_type,
ep.source_id,
ep.content,
"{}",
Option::<String>::None,
ep.confidence.0,
ep.strength,
ep.salience,
"hot",
now_ms,
now_ms,
],
)
.unwrap();
episode_rowids.push(conn.last_insert_rowid());
conn.execute(
"INSERT INTO pending_index (kind, memory_id, embedding, embedding_dim, enqueued_at)
VALUES ('episode', ?, ?, ?, ?)",
params![mid, &vec![0u8; 16][..], 4i64, now_ms],
)
.unwrap();
}
// Seed 2 chunks (with pending rows).
let chunk_rowids =
seed_pending_chunks(&conn, "22222222-2222-2222-2222-222222222222", 4, 2);
let stub = StubVectorIndex::new(4);
let report = crate::recovery::replay_pending_index(&mut conn, &stub).unwrap();
assert_eq!(report.rows_seen, 4);
assert_eq!(report.rows_replayed, 4);
assert_eq!(report.rows_failed, 0);
// Both classes of rowids landed in HNSW, each encoded with the
// matching kind discriminator. This is the integration-level
// anchor that recovery replay applies the correct encoder
// per-kind: episodes via `episode_hnsw_id` (identity) and
// chunks via `chunk_hnsw_id` (high bit set).
let added: std::collections::HashSet<i64> =
stub.entries().iter().map(|(r, _)| *r).collect();
let mut expected: std::collections::HashSet<i64> = episode_rowids
.iter()
.copied()
.map(crate::hnsw_id::episode_hnsw_id)
.collect();
expected.extend(
chunk_rowids
.iter()
.copied()
.map(crate::hnsw_id::chunk_hnsw_id),
);
assert_eq!(added, expected);
// Critically: episode and chunk ids do NOT collide in the
// HNSW namespace, even when their SQLite rowids happen to share
// values. (In this test the AUTOINCREMENT sequences keep them
// disjoint; the collision-free invariant comes from the
// kind-discriminator encoding, not from rowid disjointness.)
for r in &episode_rowids {
for c in &chunk_rowids {
let ep_id = crate::hnsw_id::episode_hnsw_id(*r);
let chunk_id = crate::hnsw_id::chunk_hnsw_id(*c);
assert_ne!(
ep_id, chunk_id,
"encoded episode and chunk ids must never collide"
);
}
}
let n: i64 = conn
.query_row("SELECT COUNT(*) FROM pending_index", [], |r| r.get(0))
.unwrap();
assert_eq!(n, 0);
}
/// Critical regression test: an episode at `rowid=N` and a chunk at
/// `rowid=N` (same numeric value!) must BOTH be retrievable from the
/// shared HNSW. Without the kind-discriminated encoding, the second
/// add would collide with the first; with `hnsw_rs` 0.3.4's silent-
/// accept behavior the recall path would surface ambiguous results.
///
/// This test simulates the production scenario by forcibly assigning
/// chunk rowid=1 to coincide with episode rowid=1, then verifies
/// that:
/// (1) Both vectors land in HNSW at distinct encoded ids.
/// (2) `recall` (episode side) returns the episode.
/// (3) `doc_search` (chunk side) returns the chunk.
///
/// The simulation is done at the recovery layer rather than via
/// AUTOINCREMENT (which in a fresh DB starts both sequences at 1
/// anyway, so simply remembering one episode + ingesting one
/// chunk reproduces the collision naturally).
#[test]
fn episode_and_chunk_with_same_rowid_coexist_in_hnsw() {
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, hnsw) = build_ingest_actor(conn);
// Step 1: write one episode (assigned rowid=1 by AUTOINCREMENT).
let ep = fixture_episode("episode body");
let now_ms = chrono::Utc::now().timestamp_millis();
// Use `handle_remember`-equivalent path via direct SQL + actor
// dispatch. We hand-roll the SQL so we can assert the assigned
// rowid is 1. (The actor's `dispatch_remember` does the same
// INSERT under the hood.)
let memory_id = ep.memory_id.to_string();
actor
.conn
.execute(
"INSERT INTO episodes (
memory_id, ts_ms, source_type, source_id, content,
encoding_context_json, provenance_json, confidence,
strength, salience, tier, created_at_ms, updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
params![
memory_id,
ep.ts_ms,
ep.source_type,
ep.source_id,
ep.content,
"{}",
Option::<String>::None,
ep.confidence.0,
ep.strength,
ep.salience,
"hot",
now_ms,
now_ms,
],
)
.unwrap();
let episode_rowid = actor.conn.last_insert_rowid();
assert_eq!(episode_rowid, 1, "first episode insert must yield rowid=1");
// Simulate the writer's HNSW add for this episode with a
// distinctive vector.
let ep_vec = vec![1.0f32, 0.0, 0.0, 0.0];
hnsw.add(crate::hnsw_id::episode_hnsw_id(episode_rowid), &ep_vec)
.unwrap();
// Step 2: ingest a document. The first chunk gets
// document_chunks.rowid = 1 (independent AUTOINCREMENT
// sequence per ADR-0003 §shared-HNSW-namespace), colliding
// numerically with the episode above.
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(
&docs_tmp,
"doc.md",
"# Doc\n\nSome chunk content.\n",
);
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let report = reply_rx.blocking_recv().unwrap().expect("ingest ok");
assert_eq!(report.chunks_persisted, 1, "fixture produces one chunk");
// The chunk's rowid should be 1 — same as the episode's.
let chunk_rowid: i64 = actor
.conn
.query_row(
"SELECT rowid FROM document_chunks WHERE doc_id = ?",
params![report.doc_id.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(
chunk_rowid, episode_rowid,
"chunk rowid must collide numerically with episode rowid for this test (both AUTOINCREMENT sequences start at 1)"
);
// Step 3: assert HNSW carries BOTH vectors at DISTINCT encoded ids.
let entries = hnsw.entries();
let encoded_episode_id = crate::hnsw_id::episode_hnsw_id(episode_rowid);
let encoded_chunk_id = crate::hnsw_id::chunk_hnsw_id(chunk_rowid);
assert_ne!(
encoded_episode_id, encoded_chunk_id,
"encoded episode and chunk ids must differ even when raw rowids collide"
);
let ids: std::collections::HashSet<i64> =
entries.iter().map(|(r, _)| *r).collect();
assert!(
ids.contains(&encoded_episode_id),
"HNSW must carry episode at encoded id {encoded_episode_id}; entries: {entries:?}"
);
assert!(
ids.contains(&encoded_chunk_id),
"HNSW must carry chunk at encoded id {encoded_chunk_id}; entries: {entries:?}"
);
// Step 4: decode each entry and confirm kind/rowid round-trip.
for (id, _) in &entries {
let (kind, decoded) = crate::hnsw_id::decode_hnsw_id(*id);
match kind {
crate::hnsw_id::HnswIdKind::Episode => {
assert_eq!(decoded, episode_rowid);
}
crate::hnsw_id::HnswIdKind::Chunk => {
assert_eq!(decoded, chunk_rowid);
}
}
}
}
// ----- v0.7.1: SOLO_INGEST_MAX_BYTES guardrail -----
//
// Process-global env-var manipulation is mutexed against itself; the
// pattern matches `embedder::tests` so a single serialised lock keeps
// parallel cargo-test workers from racing each other through the env.
mod ingest_max_bytes {
use super::*;
use crate::writer::{
DEFAULT_INGEST_MAX_BYTES, SOLO_INGEST_MAX_BYTES_ENV, resolve_ingest_max_bytes,
};
use std::sync::Mutex;
static ENV_LOCK: Mutex<()> = Mutex::new(());
/// Drop-guard that clears `SOLO_INGEST_MAX_BYTES` at end of scope so
/// each test starts from the unset baseline regardless of order.
struct EnvGuard;
impl Drop for EnvGuard {
fn drop(&mut self) {
// SAFETY: caller holds `ENV_LOCK`; no concurrent env access.
unsafe { std::env::remove_var(SOLO_INGEST_MAX_BYTES_ENV) };
}
}
fn fresh_env() -> EnvGuard {
// SAFETY: caller holds `ENV_LOCK`.
unsafe { std::env::remove_var(SOLO_INGEST_MAX_BYTES_ENV) };
EnvGuard
}
#[test]
fn resolve_unset_returns_default() {
let _lock = ENV_LOCK.lock().unwrap();
let _g = fresh_env();
assert_eq!(resolve_ingest_max_bytes(), Some(DEFAULT_INGEST_MAX_BYTES));
}
#[test]
fn resolve_zero_disables_cap() {
let _lock = ENV_LOCK.lock().unwrap();
let _g = fresh_env();
// SAFETY: ENV_LOCK held.
unsafe { std::env::set_var(SOLO_INGEST_MAX_BYTES_ENV, "0") };
assert_eq!(resolve_ingest_max_bytes(), None);
}
#[test]
fn resolve_positive_integer_uses_value() {
let _lock = ENV_LOCK.lock().unwrap();
let _g = fresh_env();
unsafe { std::env::set_var(SOLO_INGEST_MAX_BYTES_ENV, "1024") };
assert_eq!(resolve_ingest_max_bytes(), Some(1024));
}
#[test]
fn resolve_garbage_falls_back_to_default() {
let _lock = ENV_LOCK.lock().unwrap();
let _g = fresh_env();
unsafe { std::env::set_var(SOLO_INGEST_MAX_BYTES_ENV, "not-a-number") };
assert_eq!(resolve_ingest_max_bytes(), Some(DEFAULT_INGEST_MAX_BYTES));
unsafe { std::env::set_var(SOLO_INGEST_MAX_BYTES_ENV, "-1") };
assert_eq!(resolve_ingest_max_bytes(), Some(DEFAULT_INGEST_MAX_BYTES));
unsafe { std::env::set_var(SOLO_INGEST_MAX_BYTES_ENV, " ") };
assert_eq!(resolve_ingest_max_bytes(), Some(DEFAULT_INGEST_MAX_BYTES));
}
#[test]
fn ingest_rejects_oversized_file_with_clear_error() {
let _lock = ENV_LOCK.lock().unwrap();
let _g = fresh_env();
// 100-byte file but cap is 1 byte → reject.
unsafe { std::env::set_var(SOLO_INGEST_MAX_BYTES_ENV, "1") };
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(
&docs_tmp,
"big.md",
"# Big\n\nThis is well over a single byte of content text.\n",
);
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let err = reply_rx.blocking_recv().unwrap().unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("SOLO_INGEST_MAX_BYTES")
&& msg.contains("exceeds")
&& msg.contains("disable"),
"rejection message must call out the env var, threshold, and disable hint; got: {msg}"
);
// Zero SQL state, zero HNSW state.
let n_docs: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM documents", [], |r| r.get(0))
.unwrap();
assert_eq!(n_docs, 0);
assert_eq!(hnsw.add_count(), 0);
}
#[test]
fn ingest_allows_undersized_file_under_custom_cap() {
let _lock = ENV_LOCK.lock().unwrap();
let _g = fresh_env();
// 4 KiB cap; tiny doc is well under.
unsafe { std::env::set_var(SOLO_INGEST_MAX_BYTES_ENV, "4096") };
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
let path = write_markdown(&docs_tmp, "ok.md", "# OK\n\nShort body.\n");
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let report = reply_rx.blocking_recv().unwrap().expect("ingest under cap must succeed");
assert!(!report.deduped);
assert_eq!(report.chunks_persisted, 1);
}
#[test]
fn ingest_with_cap_zero_allows_any_size() {
let _lock = ENV_LOCK.lock().unwrap();
let _g = fresh_env();
// Disable cap entirely.
unsafe { std::env::set_var(SOLO_INGEST_MAX_BYTES_ENV, "0") };
let (conn, _tmp) = open_test_db();
let (mut actor, _rt, _hnsw) = build_ingest_actor(conn);
let docs_tmp = tempfile::TempDir::new().unwrap();
// Ingest succeeds even though body is non-trivial.
let path = write_markdown(
&docs_tmp,
"any.md",
"# Any\n\nWith SOLO_INGEST_MAX_BYTES=0 any size is allowed.\n",
);
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(path, ChunkConfig::default(), None, reply_tx);
let report = reply_rx.blocking_recv().unwrap().expect("cap=0 disables cap");
assert_eq!(report.chunks_persisted, 1);
}
}
// -----------------------------------------------------------------
// v0.8.0 P4 — audit emission tests
//
// Each mutating handler must produce an audit_events row inside the
// writer's SQL transaction. We exercise dispatch_remember +
// handle_forget + dispatch_ingest_document + handle_forget_document
// directly (read-only paths emit via solo-query, tested separately
// in that crate).
// -----------------------------------------------------------------
mod audit_emit_tests {
use super::*;
use crate::audit::AuditOperation;
/// Build an actor with embedder + runtime so ingest works (mirrors
/// `build_ingest_actor`). Returns (actor, runtime, tmp). The
/// caller controls the runtime; the actor's connection is on
/// disk so we can re-open it to inspect the audit table.
fn build_ingest_actor_for_audit() -> (
WriterActor,
tokio::runtime::Runtime,
tempfile::TempDir,
) {
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let tmp = tempfile::TempDir::new().unwrap();
let path = tmp.path().join("test.db");
let conn = crate::test_support::open_test_db_at(&path);
let embedder: Arc<dyn solo_core::Embedder> =
Arc::new(crate::StubEmbedder::new("stub", "v1", 4));
let identity = crate::EmbedderIdentity {
name: "stub".into(),
version: "v1".into(),
dim: 4,
dtype: "f32".into(),
};
let embedder_id =
crate::get_or_insert_embedder_id(&conn, &identity).unwrap();
let hnsw: Arc<dyn solo_core::VectorIndex + Send + Sync> =
Arc::new(crate::test_support::StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: Some(embedder_id),
embedder: Some(embedder),
runtime_handle: Some(runtime.handle().clone()),
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
(actor, runtime, tmp)
}
fn count_audit_rows_for_op(conn: &Connection, op: AuditOperation) -> i64 {
conn.query_row(
"SELECT COUNT(*) FROM audit_events WHERE operation = ?",
params![op.as_str()],
|r| r.get(0),
)
.unwrap()
}
#[test]
fn dispatch_remember_emits_audit_row_with_ok_result() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(crate::test_support::StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
let (reply_tx, reply_rx) = oneshot::channel();
let episode = fixture_episode("audit-remember");
actor.dispatch_remember(
episode.clone(),
fixture_embedding(4),
Some("alice".into()),
reply_tx,
);
assert!(reply_rx.blocking_recv().unwrap().is_ok());
let (op, principal, target, result): (String, Option<String>, Option<String>, String) =
actor
.conn
.query_row(
"SELECT operation, principal_subject, target_id, result \
FROM audit_events ORDER BY audit_id DESC LIMIT 1",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)
.unwrap();
assert_eq!(op, "memory.remember");
assert_eq!(principal.as_deref(), Some("alice"));
assert_eq!(target.as_deref(), Some(episode.memory_id.to_string().as_str()));
assert_eq!(result, "ok");
}
#[test]
fn dispatch_remember_with_none_principal_persists_null() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(crate::test_support::StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
let (reply_tx, reply_rx) = oneshot::channel();
let episode = fixture_episode("audit-remember-noprincipal");
actor.dispatch_remember(
episode.clone(),
fixture_embedding(4),
None,
reply_tx,
);
assert!(reply_rx.blocking_recv().unwrap().is_ok());
let principal: Option<String> = actor
.conn
.query_row(
"SELECT principal_subject FROM audit_events ORDER BY audit_id DESC LIMIT 1",
[],
|r| r.get(0),
)
.unwrap();
assert!(principal.is_none());
}
#[test]
fn handle_forget_emits_audit_row() {
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(crate::test_support::StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
// Need an episode to forget first.
let (reply_tx, reply_rx) = oneshot::channel();
let episode = fixture_episode("to-forget");
actor.dispatch_remember(
episode.clone(),
fixture_embedding(4),
None,
reply_tx,
);
reply_rx.blocking_recv().unwrap().unwrap();
// Pre-condition: 1 remember audit row.
assert_eq!(
count_audit_rows_for_op(&actor.conn, AuditOperation::MemoryRemember),
1
);
actor
.handle_forget(episode.memory_id, "test".into(), Some("bob".into()))
.unwrap();
assert_eq!(
count_audit_rows_for_op(&actor.conn, AuditOperation::MemoryForget),
1
);
// Principal threaded through correctly.
let principal: Option<String> = actor
.conn
.query_row(
"SELECT principal_subject FROM audit_events \
WHERE operation = 'memory.forget' \
ORDER BY audit_id DESC LIMIT 1",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(principal.as_deref(), Some("bob"));
}
#[test]
fn handle_forget_unknown_id_emits_no_success_row_emits_error_row_via_dispatch() {
// This tests that the error path emits an audit row with
// result='error' (via dispatch's `emit_audit_best_effort`).
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(crate::test_support::StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
let unknown = MemoryId::new();
// Use the dispatch surface so error-path audit emit runs.
let cmd = WriteCommand::Forget {
memory_id: unknown,
reason: "test".into(),
audit_principal: Some("carol".into()),
reply: oneshot::channel().0,
};
actor.dispatch(cmd);
let (result, principal): (String, Option<String>) = actor
.conn
.query_row(
"SELECT result, principal_subject FROM audit_events \
WHERE operation = 'memory.forget' \
ORDER BY audit_id DESC LIMIT 1",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert_eq!(result, "error");
assert_eq!(principal.as_deref(), Some("carol"));
}
#[test]
fn handle_forget_document_emits_audit_row() {
let (mut actor, runtime, tmp) = build_ingest_actor_for_audit();
// Ingest a doc first.
let docs_dir = tmp.path().join("docs");
std::fs::create_dir_all(&docs_dir).unwrap();
let path = docs_dir.join("test.md");
std::fs::write(&path, "# audit doc\nsome content").unwrap();
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(
path,
crate::document::ChunkConfig::default(),
None,
reply_tx,
);
let report = reply_rx.blocking_recv().unwrap().unwrap();
// Now forget it with a principal.
let _ = actor
.handle_forget_document(report.doc_id, Some("dora".into()))
.unwrap();
assert_eq!(
count_audit_rows_for_op(&actor.conn, AuditOperation::MemoryForgetDocument),
1
);
let principal: Option<String> = actor
.conn
.query_row(
"SELECT principal_subject FROM audit_events \
WHERE operation = 'memory.forget_document' \
ORDER BY audit_id DESC LIMIT 1",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(principal.as_deref(), Some("dora"));
drop(runtime);
}
#[test]
fn ingest_document_emits_one_audit_row() {
let (mut actor, runtime, tmp) = build_ingest_actor_for_audit();
let docs_dir = tmp.path().join("docs");
std::fs::create_dir_all(&docs_dir).unwrap();
let path = docs_dir.join("ingest.md");
std::fs::write(&path, "# ingested\nbody").unwrap();
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_ingest_document(
path,
crate::document::ChunkConfig::default(),
Some("eve".into()),
reply_tx,
);
let _ = reply_rx.blocking_recv().unwrap().unwrap();
assert_eq!(
count_audit_rows_for_op(&actor.conn, AuditOperation::MemoryIngestDocument),
1
);
let (principal, result): (Option<String>, String) = actor
.conn
.query_row(
"SELECT principal_subject, result FROM audit_events \
WHERE operation = 'memory.ingest_document' \
ORDER BY audit_id DESC LIMIT 1",
[],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.unwrap();
assert_eq!(principal.as_deref(), Some("eve"));
assert_eq!(result, "ok");
drop(runtime);
}
#[test]
fn normalize_subjects_emits_audit_row_inside_tx() {
let (conn, _tmp) = open_test_db();
// Seed a triple.
let now_ms = chrono::Utc::now().timestamp_millis();
conn.execute(
"INSERT INTO triples (
triple_id, subject_id, predicate, object_id, object_kind,
valid_from_ms, valid_to_ms, confidence, provenance_json,
created_at_ms, updated_at_ms
) VALUES (?, 'alex', 'uses', 'rust', 'literal', ?, NULL, 0.9, '{}', ?, ?)",
params![
"00000000-0000-0000-0000-000000000010",
now_ms,
now_ms,
now_ms
],
)
.unwrap();
let hnsw = Arc::new(crate::test_support::StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
let _ = actor
.handle_normalize_subjects(
vec![("alex".into(), "user".into())],
false,
Some("frank".into()),
)
.unwrap();
assert_eq!(
count_audit_rows_for_op(
&actor.conn,
AuditOperation::MemoryNormalizeSubjects,
),
1
);
let principal: Option<String> = actor
.conn
.query_row(
"SELECT principal_subject FROM audit_events \
WHERE operation = 'memory.normalize_subjects' \
ORDER BY audit_id DESC LIMIT 1",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(principal.as_deref(), Some("frank"));
}
}
/// v0.8.0 P5: writer-side redaction tests.
///
/// The redaction registry itself is exhaustively unit-tested in
/// `crate::redaction::registry::tests`; this submodule covers the
/// writer-level wiring — that redaction runs before INSERT, that the
/// audit row records pattern-name counts only (no PII leak), and
/// that on-disk content reflects the redaction.
mod redaction_tests {
use super::*;
use crate::test_support::{enabled_test_redactor, open_test_db};
use std::sync::Arc;
fn build_redacting_actor(conn: Connection) -> (WriterActor, Arc<StubVectorIndex>) {
let hnsw = Arc::new(StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let actor = WriterActor {
conn,
hnsw: hnsw.clone(),
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: enabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
(actor, hnsw)
}
#[test]
fn redacted_content_lands_on_disk_for_remember() {
let (conn, _tmp) = open_test_db();
let (mut actor, _hnsw) = build_redacting_actor(conn);
let mut episode = fixture_episode("contact me at user@example.com please");
let mid = episode.memory_id;
let embedding = fixture_embedding(4);
let (tx, rx) = oneshot::channel();
actor.dispatch_remember(
std::mem::replace(&mut episode, fixture_episode("placeholder")),
embedding,
Some("alice".into()),
tx,
);
assert!(rx.blocking_recv().unwrap().is_ok());
let content: String = actor
.conn
.query_row(
"SELECT content FROM episodes WHERE memory_id = ?",
params![mid.to_string()],
|r| r.get(0),
)
.unwrap();
assert!(content.contains("[REDACTED:email]"), "got `{content}`");
assert!(!content.contains("user@example.com"));
}
#[test]
fn redaction_audit_row_emitted_with_pattern_counts() {
let (conn, _tmp) = open_test_db();
let (mut actor, _hnsw) = build_redacting_actor(conn);
let episode = fixture_episode(
"ssn 123-45-6789 phone 555-123-4567 mail a@b.com",
);
let mid = episode.memory_id;
let (tx, rx) = oneshot::channel();
actor.dispatch_remember(
episode,
fixture_embedding(4),
Some("carol".into()),
tx,
);
rx.blocking_recv().unwrap().unwrap();
let (op, target, details_json): (String, Option<String>, Option<String>) = actor
.conn
.query_row(
"SELECT operation, target_id, details_json \
FROM audit_events WHERE operation = 'redaction.applied'",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.unwrap();
assert_eq!(op, "redaction.applied");
assert_eq!(target.as_deref(), Some(mid.to_string().as_str()));
let details: serde_json::Value =
serde_json::from_str(details_json.as_deref().unwrap()).unwrap();
let names: Vec<String> = details["matches"]
.as_array()
.unwrap()
.iter()
.map(|m| m["pattern_name"].as_str().unwrap().to_string())
.collect();
assert!(names.contains(&"email".to_string()));
assert!(names.contains(&"ssn".to_string()));
assert!(names.contains(&"us_phone".to_string()));
}
#[test]
fn audit_row_does_not_contain_original_pii() {
// The strict telemetry contract: redaction.applied details
// carry counts, never matched substrings.
let (conn, _tmp) = open_test_db();
let (mut actor, _hnsw) = build_redacting_actor(conn);
let episode = fixture_episode("email leak@example.com here");
let (tx, rx) = oneshot::channel();
actor.dispatch_remember(
episode,
fixture_embedding(4),
Some("dan".into()),
tx,
);
rx.blocking_recv().unwrap().unwrap();
let details: Option<String> = actor
.conn
.query_row(
"SELECT details_json FROM audit_events \
WHERE operation = 'redaction.applied'",
[],
|r| r.get(0),
)
.unwrap();
let d = details.expect("redaction audit row must have details");
assert!(!d.contains("leak@example.com"), "PII leaked into audit: `{d}`");
assert!(!d.contains("leak"), "PII fragment in audit: `{d}`");
}
#[test]
fn principal_subject_persisted_on_episode_row() {
// Migration 0006 column wiring: episodes.principal_subject is
// populated from audit_principal.
let (conn, _tmp) = open_test_db();
let (mut actor, _hnsw) = build_redacting_actor(conn);
let episode = fixture_episode("plain content");
let mid = episode.memory_id;
let (tx, rx) = oneshot::channel();
actor.dispatch_remember(
episode,
fixture_embedding(4),
Some("erin".into()),
tx,
);
rx.blocking_recv().unwrap().unwrap();
let principal: Option<String> = actor
.conn
.query_row(
"SELECT principal_subject FROM episodes WHERE memory_id = ?",
params![mid.to_string()],
|r| r.get(0),
)
.unwrap();
assert_eq!(principal.as_deref(), Some("erin"));
}
#[test]
fn no_redaction_audit_row_when_no_matches() {
// Clean content → no redaction.applied row.
let (conn, _tmp) = open_test_db();
let (mut actor, _hnsw) = build_redacting_actor(conn);
let episode = fixture_episode("no pii here at all");
let (tx, rx) = oneshot::channel();
actor.dispatch_remember(
episode,
fixture_embedding(4),
Some("frank".into()),
tx,
);
rx.blocking_recv().unwrap().unwrap();
let n: i64 = actor
.conn
.query_row(
"SELECT COUNT(*) FROM audit_events WHERE operation = 'redaction.applied'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(n, 0);
}
#[test]
fn read_path_returns_redacted_content() {
// Round-trip the redaction through a recall-style read.
// recall paths go through the read pool, but a SELECT on the
// writer's own connection exercises the same on-disk state.
// Verify the recall surface returns the redacted form.
let (conn, _tmp) = open_test_db();
let (mut actor, _hnsw) = build_redacting_actor(conn);
let episode = fixture_episode("token gh PAT ghp_abcdefghijABCDEFGHIJabcdefghijABCDEF12 done");
let mid = episode.memory_id;
let (tx, rx) = oneshot::channel();
actor.dispatch_remember(
episode,
fixture_embedding(4),
None,
tx,
);
rx.blocking_recv().unwrap().unwrap();
let content: String = actor
.conn
.query_row(
"SELECT content FROM episodes WHERE memory_id = ?",
params![mid.to_string()],
|r| r.get(0),
)
.unwrap();
assert!(content.contains("[REDACTED:github_pat]"), "got `{content}`");
assert!(!content.contains("ghp_abcdefghij"));
}
}
// ---- v0.8.1 P3: quota_bytes enforcement ----
mod quota_tests {
use super::*;
#[test]
fn unlimited_branch_short_circuits_without_db_path() {
// The hot path: quota = None means no enforcement, no file
// stat. Confirm one Option compare and we're done.
let decision = check_quota(None, None, 1_000_000);
assert_eq!(decision, QuotaDecision::Unlimited);
}
#[test]
fn allowed_when_current_plus_growth_fits_under_quota() {
let tmp = tempfile::NamedTempFile::new().unwrap();
// Write 100 bytes into the temp file so metadata().len() = 100.
std::fs::write(tmp.path(), vec![0u8; 100]).unwrap();
let decision = check_quota(Some(1000), Some(tmp.path()), 200);
assert!(
matches!(decision, QuotaDecision::Allowed { current_size: 100, quota: 1000 }),
"got {decision:?}"
);
}
#[test]
fn allowed_when_current_plus_growth_exactly_hits_quota() {
// Strict `>` semantics: hitting exactly is allowed.
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), vec![0u8; 500]).unwrap();
let decision = check_quota(Some(1000), Some(tmp.path()), 500);
assert!(
matches!(decision, QuotaDecision::Allowed { .. }),
"exactly-on-quota must be allowed: got {decision:?}"
);
}
#[test]
fn exceeded_when_growth_would_overflow_quota() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), vec![0u8; 900]).unwrap();
let decision = check_quota(Some(1000), Some(tmp.path()), 200);
assert!(
matches!(decision, QuotaDecision::Exceeded {
current_size: 900,
estimated_growth: 200,
quota: 1000,
}),
"got {decision:?}"
);
}
#[test]
fn exceeded_payload_renders_into_audit_json() {
let err = QuotaExceededError {
current_size: 900,
estimated_growth: 200,
quota: 1000,
};
let v = err.to_details_json();
assert_eq!(v["reason"], "quota_exceeded");
assert_eq!(v["current_size"], 900);
assert_eq!(v["estimated_growth"], 200);
assert_eq!(v["quota"], 1000);
}
#[test]
fn handle_remember_durable_rejects_when_quota_exceeded() {
// Build a writer with a very small quota (10 bytes) and the
// db_path pointing at the test DB. The first `remember` of
// a > 10-byte content should reject and emit a `forbidden`
// audit row.
let (conn, tmp) = open_test_db();
let db_path = tmp.path().join("test.db");
// Seed the on-disk DB so file size > 0; writer will read
// this when computing current_size.
// (open_test_db already created the DB with migrations.)
let hnsw: Arc<dyn solo_core::VectorIndex + Send + Sync> =
Arc::new(crate::test_support::StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
// 10-byte cap — guaranteed below the test DB's actual
// size (SQLite + migrations occupy ≫ 10 bytes).
quota_bytes: Some(10),
db_path: Some(db_path),
invalidate_tx: None,
invalidate_tenant_id: None,
};
let ep = fixture_episode("this exceeds the 10-byte quota easily");
let result = actor.handle_remember_durable(
ep,
fixture_embedding(4),
Some("erin".into()),
);
assert!(
matches!(result, Err(solo_core::Error::Forbidden(_))),
"must reject with Forbidden, got: {result:?}"
);
// Audit row landed (best-effort emit via emit_audit_best_effort).
let count: i64 = actor
.conn
.query_row(
"SELECT COUNT(*) FROM audit_events \
WHERE operation='memory.remember' AND result='forbidden'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(count, 1, "forbidden audit row must land");
// details_json carries the structured fields.
let details: String = actor
.conn
.query_row(
"SELECT details_json FROM audit_events \
WHERE operation='memory.remember' AND result='forbidden' \
ORDER BY audit_id DESC LIMIT 1",
[],
|r| r.get(0),
)
.unwrap();
let v: serde_json::Value = serde_json::from_str(&details).unwrap();
assert_eq!(v["reason"], "quota_exceeded");
assert_eq!(v["quota"], 10);
}
#[test]
fn handle_remember_durable_proceeds_when_quota_unlimited() {
// Regression: writer without quota MUST behave exactly like
// v0.8.0 — no per-op overhead, no file stat.
let (conn, _tmp) = open_test_db();
let hnsw: Arc<dyn solo_core::VectorIndex + Send + Sync> =
Arc::new(crate::test_support::StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
};
let ep = fixture_episode("any content");
let result = actor.handle_remember_durable(
ep,
fixture_embedding(4),
None,
);
assert!(result.is_ok(), "unlimited quota must allow the write: {result:?}");
}
}
/// v0.9.0 P4a: tests pinning the `current_steward()` resolution path
/// — `tenant.steward_slot()` is the canonical source of truth;
/// `self.steward` is the fallback for v0.8.x callers that don't
/// plumb the slot.
mod p4a_steward_slot_tests {
use super::*;
use solo_steward::{Steward, StewardConfig, test_support::StubLlmClient};
fn arc_stub_steward() -> Arc<Steward> {
Arc::new(Steward::new(
Arc::new(StubLlmClient::default_stub().pretend_real_llm(true)),
StewardConfig::default(),
))
}
fn build_actor(
steward: Option<Arc<Steward>>,
slot: Option<Arc<AsyncRwLock<Option<Arc<Steward>>>>>,
) -> WriterActor {
let (conn, _tmp) = open_test_db();
// Leak the tempdir so the test holds the conn for the
// duration; we deliberately don't drop the actor here so
// its connection stays valid for the assertion read.
std::mem::forget(_tmp);
let hnsw = Arc::new(StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward,
steward_slot: slot,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
}
}
/// P4a F1 activation: the writer-actor reads the slot per
/// command. When `self.steward = None` (sampling backend
/// before MCP-initialize) AND the slot is populated (after
/// MCP-initialize), `current_steward` returns the slot's
/// Steward.
#[test]
fn writer_actor_consults_steward_slot_when_self_steward_is_none() {
let slot_steward = arc_stub_steward();
let slot = Arc::new(AsyncRwLock::new(Some(slot_steward.clone())));
let actor = build_actor(None, Some(slot));
let resolved = actor.current_steward().expect("slot populated");
assert!(
Arc::ptr_eq(&resolved, &slot_steward),
"current_steward must return the slot's Steward when self.steward is None",
);
}
/// P4a slot-vs-self priority: when BOTH the slot and
/// `self.steward` carry a Steward, the slot wins. This is the
/// "MCP-session-attaches-mid-life" path — the sampling
/// Steward overwrites a stale eager-captured field.
#[test]
fn writer_actor_prefers_slot_over_self_steward_when_both_set() {
let slot_steward = arc_stub_steward();
let eager_steward = arc_stub_steward();
// Sanity: the two Stewards have distinct allocations so
// ptr_eq can distinguish them.
assert!(!Arc::ptr_eq(&slot_steward, &eager_steward));
let slot = Arc::new(AsyncRwLock::new(Some(slot_steward.clone())));
let actor = build_actor(Some(eager_steward.clone()), Some(slot));
let resolved = actor.current_steward().expect("slot populated");
assert!(
Arc::ptr_eq(&resolved, &slot_steward),
"current_steward must prefer the slot when both are set",
);
assert!(
!Arc::ptr_eq(&resolved, &eager_steward),
"current_steward must NOT return self.steward when slot is populated",
);
}
/// P4a backwards-compat: when the slot is empty AND
/// `self.steward` is populated, `current_steward` falls back
/// to `self.steward`. This preserves the v0.8.x eager-
/// population path that Ollama / Anthropic operators use today.
#[test]
fn writer_actor_uses_self_steward_when_slot_is_none() {
let eager_steward = arc_stub_steward();
// Slot present but empty — the v0.9.0 P0c shape for a
// newly-opened sampling tenant before MCP-initialize.
let slot = Arc::new(AsyncRwLock::new(None));
let actor = build_actor(Some(eager_steward.clone()), Some(slot));
let resolved = actor.current_steward().expect("self.steward populated");
assert!(
Arc::ptr_eq(&resolved, &eager_steward),
"current_steward must fall back to self.steward when the slot is empty",
);
}
/// P4a "no LLM" path: when both the slot and `self.steward`
/// are empty, `current_steward` returns `None`. The merge_plan
/// gate + the deferred batch path both observe `None` and
/// short-circuit cleanly.
#[test]
fn writer_actor_returns_none_when_slot_and_self_steward_are_both_none() {
let actor = build_actor(None, Some(Arc::new(AsyncRwLock::new(None))));
assert!(actor.current_steward().is_none());
}
/// P4a no-slot path: when the writer-actor was spawned without
/// a slot at all (v0.8.x spawn variants like `spawn`,
/// `spawn_with_capacity`, `spawn_full`, `spawn_full_with_quota`),
/// `current_steward` skips the slot lookup entirely and uses
/// `self.steward`. Pins the "spawn without slot" backwards-compat.
#[test]
fn writer_actor_falls_back_when_slot_is_unwired() {
let eager_steward = arc_stub_steward();
let actor = build_actor(Some(eager_steward.clone()), None);
let resolved = actor.current_steward().expect("self.steward populated");
assert!(
Arc::ptr_eq(&resolved, &eager_steward),
"no slot wired → current_steward returns self.steward",
);
}
// ---- v0.10.1 m2 audit-minor closure: contention path pin
// (deferred from v0.9.0 P4 §m2). ----
//
// `current_steward` uses `slot.try_read()` — the sync variant —
// and falls back to `self.steward` when a writer holds the
// lock. The P4 audit (m2) flagged that no test exercised this
// contention path. These tests close that gap by:
//
// 1. Spawning a tokio task that acquires the slot's write
// lock and holds it via a barrier.
// 2. Synchronously calling `current_steward()` from the
// test thread while the write lock is held.
// 3. Asserting the call returns `self.steward` (or `None`
// if `self.steward` is also `None`) — i.e. the
// try_read fell through.
// 4. Releasing the write lock and asserting subsequent
// `current_steward()` calls re-observe the slot.
//
// Coordination uses `tokio::sync::Barrier` + `oneshot` to
// make the contention window deterministic — no `sleep`-
// based timing. If this test ever becomes flaky (the
// barrier should make it not), we'd mark it `#[ignore]`
// with a comment per the brief — but the barrier-based
// shape gives us reliable contention windows.
//
// Grep terms: m2, current_steward_falls_back_on_read_contention,
// current_steward_recovers_after_lock_release.
/// m2 pin: while a tokio task holds the slot's write lock,
/// a sync caller's `current_steward()` falls back to
/// `self.steward` (or `None` if also empty). The write lock
/// is released by a oneshot signal after the assertion runs.
#[test]
fn current_steward_falls_back_to_self_steward_on_read_contention() {
let slot_steward = arc_stub_steward();
let eager_steward = arc_stub_steward();
assert!(
!Arc::ptr_eq(&slot_steward, &eager_steward),
"slot and self.steward must be distinct Arc allocations for ptr_eq to discriminate"
);
let slot = Arc::new(AsyncRwLock::new(Some(slot_steward.clone())));
let actor = build_actor(Some(eager_steward.clone()), Some(slot.clone()));
// Sanity: no contention → slot wins.
let baseline = actor.current_steward().expect("baseline: slot populated");
assert!(
Arc::ptr_eq(&baseline, &slot_steward),
"baseline (no contention) must return the slot's Steward"
);
// Build a multi-thread runtime so the lock-holder task
// runs on a separate worker from the test thread's
// blocking call.
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
// `lock_held_tx`: the holder task signals "write lock is
// mine" when it has acquired the lock.
// `release_rx`: the test thread signals "you can release
// now" by sending on `release_tx`.
let (lock_held_tx, lock_held_rx) =
std::sync::mpsc::sync_channel::<()>(1);
let (release_tx, release_rx) =
tokio::sync::oneshot::channel::<()>();
let slot_for_holder = slot.clone();
let holder = runtime.spawn(async move {
let guard = slot_for_holder.write().await;
let _ = lock_held_tx.send(());
// Hold the lock until the test thread says go.
let _ = release_rx.await;
// Drop the guard to release the lock.
drop(guard);
});
// Wait until the holder confirms it has the write lock.
// The sync_channel recv blocks the test thread without
// requiring a tokio runtime context.
lock_held_rx
.recv()
.expect("holder must signal lock acquisition");
// Contention point: write lock is held, so try_read
// should return Err. `current_steward` falls back to
// `self.steward`.
let under_contention = actor
.current_steward()
.expect("self.steward populated, fallback must succeed");
assert!(
Arc::ptr_eq(&under_contention, &eager_steward),
"under read-contention, current_steward must fall back to self.steward"
);
assert!(
!Arc::ptr_eq(&under_contention, &slot_steward),
"under read-contention, current_steward must NOT return the slot's Steward"
);
// Release the lock and let the holder task finish.
let _ = release_tx.send(());
runtime.block_on(holder).unwrap();
// Post-release: slot wins again.
let after_release = actor.current_steward().expect("post-release: slot");
assert!(
Arc::ptr_eq(&after_release, &slot_steward),
"after lock release, current_steward must return the slot's Steward again"
);
}
/// m2 pin (None branch): contention with NO `self.steward`
/// fallback returns `None`. The writer-actor's downstream
/// consolidation gates already handle a `None` Steward; this
/// test pins that the contention path observes the same shape
/// as the "no LLM configured" steady state.
#[test]
fn current_steward_returns_none_under_contention_when_self_steward_is_none() {
let slot_steward = arc_stub_steward();
let slot = Arc::new(AsyncRwLock::new(Some(slot_steward.clone())));
// self.steward = None, slot = Some(slot_steward).
let actor = build_actor(None, Some(slot.clone()));
let runtime = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let (lock_held_tx, lock_held_rx) =
std::sync::mpsc::sync_channel::<()>(1);
let (release_tx, release_rx) =
tokio::sync::oneshot::channel::<()>();
let slot_for_holder = slot.clone();
let holder = runtime.spawn(async move {
let guard = slot_for_holder.write().await;
let _ = lock_held_tx.send(());
let _ = release_rx.await;
drop(guard);
});
lock_held_rx
.recv()
.expect("holder must signal lock acquisition");
// try_read returns Err; self.steward is None; result is
// None (the "no LLM" steady state).
let under_contention = actor.current_steward();
assert!(
under_contention.is_none(),
"contention + no self.steward fallback => current_steward returns None"
);
let _ = release_tx.send(());
runtime.block_on(holder).unwrap();
// Post-release: slot is observable again.
let after = actor
.current_steward()
.expect("post-release: slot populated");
assert!(Arc::ptr_eq(&after, &slot_steward));
}
}
/// v0.9.0 P4b structural pins (P4 audit m1): the architectural
/// invariants cited in `handle_consolidate_impl`'s "Tests pinning
/// this" comment. Re-added in the P4 revision after the audit found
/// they were referenced but missing.
mod p4b_no_inline_llm_pins {
use super::*;
use crate::embedder_registry::{EmbedderIdentity, get_or_insert_embedder_id};
use crate::test_support::{StubVectorIndex, fixture_embedding, fixture_episode};
use crate::writer::ConsolidationScope;
use solo_steward::test_support::StubLlmClient;
use solo_steward::{Steward, StewardConfig};
use std::sync::Arc;
use std::time::{Duration as StdDuration, Instant};
use tempfile::TempDir;
fn rt_multi() -> tokio::runtime::Runtime {
tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap()
}
/// Pin: `WriteCommand::Consolidate` returns "quickly" — i.e.
/// the writer-actor's `handle_consolidate_impl` no longer
/// `block_on`s the LLM-driven abstraction step. We verify this
/// by wiring a `Steward` whose `LlmClient` claims to be a real
/// LLM but never returns a canned response: pre-P4 (with the
/// inline `block_on(steward.abstract_cluster)` loop), reaching
/// this path with no canned response would either error out
/// PER CLUSTER inside the LLM call (slow) or hang. Post-P4
/// the writer never touches the LLM at all — the call
/// returns in single-digit milliseconds.
///
/// The wall-time bound is intentionally generous (100ms): we
/// want failure to mean "the writer-actor is BLOCKING on
/// SOMETHING (probably an LLM)", not flakiness from CI
/// jitter.
#[test]
fn consolidate_command_returns_quickly_without_blocking_on_llm() {
use crate::test_support::open_test_db_at;
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("test.db");
let dim = 4usize;
let embedder_id = {
let conn = open_test_db_at(&path);
get_or_insert_embedder_id(
&conn,
&EmbedderIdentity {
name: "stub".into(),
version: "v1".into(),
dim: dim as u32,
dtype: "f32".into(),
},
)
.unwrap()
};
// Steward says it has a real LLM, but no canned response
// is wired. Pre-P4 the writer's `block_on` would hit this
// and the test would slow or hang per cluster. Post-P4
// the writer never invokes it.
let llm = Arc::new(StubLlmClient::default_stub().pretend_real_llm(true));
let steward = Some(Arc::new(Steward::new(llm, StewardConfig::default())));
let runtime = rt_multi();
runtime.block_on(async {
let conn = open_test_db_at(&path);
let hnsw = Arc::new(StubVectorIndex::new(dim));
let embedder: Arc<dyn solo_core::Embedder> =
Arc::new(crate::embedder::StubEmbedder::new("stub", "v1", dim));
let WriterSpawn { handle, join } =
WriterActor::spawn_full_with_embedder_and_optional_steward(
conn,
hnsw,
tmp.path().to_path_buf(),
embedder_id,
embedder,
steward,
);
// Land 3 episodes that DEFINITELY cluster together.
// Use unit-norm aligned embeddings so cosine
// similarity is 1.0 between them (the all-zero
// fixture_embedding never satisfies the cosine gate).
fn aligned_embedding(dim: usize) -> Embedding {
let mut data = vec![0u8; dim * 4];
let bytes = 1.0f32.to_le_bytes();
data[..4].copy_from_slice(&bytes);
Embedding {
dtype: solo_core::EmbeddingDtype::F32,
dim,
data,
}
}
for i in 0..3 {
let mut ep = fixture_episode(&format!("e{i}"));
ep.ts_ms = 1_700_000_000_000 + (i as i64) * 1000;
handle
.remember(ep, aligned_embedding(dim))
.await
.unwrap();
}
let started = Instant::now();
let report = handle
.consolidate(ConsolidationScope::default())
.await
.expect("consolidate ok");
let elapsed = started.elapsed();
assert!(
elapsed < StdDuration::from_millis(100),
"consolidate took {elapsed:?}; pre-P4 it ran the LLM \
loop inline. Post-P4 it MUST NOT — the writer-actor's \
command path stays off the LLM critical path. (If the \
pin fires the lesson is: the v0.8.x `block_on` regressed.)"
);
// Sanity: cheap clustering pass DID run.
assert!(
report.clusters_built >= 1,
"clustering pass should at least try; got {:?}",
report,
);
// The LLM-loop's effects MUST NOT appear.
assert_eq!(
report.abstractions_built, 0,
"writer-actor must NOT build abstractions inline"
);
assert_eq!(
report.triples_built, 0,
"writer-actor must NOT extract triples inline"
);
drop(handle);
tokio::task::spawn_blocking(move || join.join().unwrap())
.await
.unwrap();
});
}
/// Pin: triple extraction does NOT happen in the writer-actor's
/// command path. Concretely: a `Remember` returns and there is
/// NO `triples` row written by the same writer tx (or by any
/// path the writer-actor controls). Triples land later via the
/// daemon-side `triples_batch_timer` + `AttachAbstractionBatch`
/// path.
///
/// Two-pronged assertion:
/// 1. After a single Remember, `SELECT COUNT(*) FROM triples`
/// is 0.
/// 2. After a Consolidate with a steward wired (the v0.8.x
/// trigger for inline triple extraction), the `triples`
/// table is STILL empty — the structural removal stays
/// removed.
#[test]
fn triples_extraction_does_not_happen_in_writer_actor_command_path() {
use crate::test_support::open_test_db_at;
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("test.db");
let dim = 4usize;
let embedder_id = {
let conn = open_test_db_at(&path);
get_or_insert_embedder_id(
&conn,
&EmbedderIdentity {
name: "stub".into(),
version: "v1".into(),
dim: dim as u32,
dtype: "f32".into(),
},
)
.unwrap()
};
// Steward with a CANNED extract-triples response, so any
// accidental inline-LLM invocation would actually write
// triples — making the post-condition strict.
let canned = r#"{
"content": "Inline triples MUST NOT land via the writer-actor.",
"confidence": 0.9,
"triples": [
{ "subject_id": "ghost", "predicate": "should_not", "object_id": "exist", "object_kind": "literal" }
]
}"#;
let llm = Arc::new(StubLlmClient::with_canned("stub-llm", canned)
.pretend_real_llm(true));
let steward = Some(Arc::new(Steward::new(llm, StewardConfig::default())));
let runtime = rt_multi();
runtime.block_on(async {
let conn = open_test_db_at(&path);
let hnsw = Arc::new(StubVectorIndex::new(dim));
let embedder: Arc<dyn solo_core::Embedder> =
Arc::new(crate::embedder::StubEmbedder::new("stub", "v1", dim));
let WriterSpawn { handle, join } =
WriterActor::spawn_full_with_embedder_and_optional_steward(
conn,
hnsw,
tmp.path().to_path_buf(),
embedder_id,
embedder,
steward,
);
// (1) Bare Remember.
let ep = fixture_episode("remember-only");
handle
.remember(ep, fixture_embedding(dim))
.await
.unwrap();
{
let read = open_test_db_at(&path);
let n: i64 = read
.query_row("SELECT COUNT(*) FROM triples", [], |r| r.get(0))
.unwrap();
assert_eq!(
n, 0,
"Remember command must NOT write any triple rows; \
triples land later via AttachAbstractionBatch"
);
}
// (2) Remember several + Consolidate (the v0.8.x
// trigger). Triples table STILL empty afterwards.
for i in 1..4 {
let mut ep = fixture_episode(&format!("c{i}"));
ep.ts_ms = 1_700_000_000_000 + (i as i64) * 1000;
handle
.remember(ep, fixture_embedding(dim))
.await
.unwrap();
}
let _report = handle
.consolidate(ConsolidationScope::default())
.await
.unwrap();
{
let read = open_test_db_at(&path);
let n: i64 = read
.query_row("SELECT COUNT(*) FROM triples", [], |r| r.get(0))
.unwrap();
assert_eq!(
n, 0,
"writer-actor's Consolidate command must NOT \
extract triples even with a canned-response Steward \
wired (pre-P4 it would write the 'ghost' triple)"
);
let n_abs: i64 = read
.query_row(
"SELECT COUNT(*) FROM semantic_abstractions",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(
n_abs, 0,
"matching pin: writer-actor's Consolidate must NOT \
write semantic_abstractions inline either"
);
}
drop(handle);
tokio::task::spawn_blocking(move || join.join().unwrap())
.await
.unwrap();
});
}
}
/// v0.9.2 — `WriteCommand::RememberBatch` writer-actor invariants.
///
/// What's pinned here:
///
/// * Empty batch rejected as `InvalidInput` BEFORE BEGIN.
/// * Over-`MAX_REMEMBER_BATCH_SIZE` batch rejected likewise.
/// * Happy-path 5-item batch lands all 5 INSERTs in one tx,
/// pending_index is drained, hnsw receives 5 adds.
/// * The reply is `Vec<MemoryId>` in input order.
/// * Exactly ONE batch-level `memory.remember_batch` audit row
/// lands inside the tx (per dev-log 0120 §3 Decision G) — not
/// N rows.
/// * Caller-supplied `salience` round-trips to the `episodes`
/// row; omitted salience defaults to 0.5.
mod p0_remember_batch_tests {
use super::*;
use crate::test_support::{
StubVectorIndex, disabled_test_redactor, fixture_embedding, fixture_episode,
open_test_db,
};
fn build_actor() -> WriterActor {
let (conn, _tmp) = open_test_db();
std::mem::forget(_tmp);
let hnsw: Arc<dyn solo_core::VectorIndex + Send + Sync> =
Arc::new(StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
quota_bytes: None,
db_path: None,
invalidate_tx: None,
invalidate_tenant_id: None,
}
}
#[test]
fn dispatch_remember_batch_empty_returns_invalid_input() {
let mut actor = build_actor();
let (reply_tx, reply_rx) = oneshot::channel();
actor.dispatch_remember_batch(Vec::new(), None, reply_tx);
let result = reply_rx.blocking_recv().unwrap();
assert!(
matches!(result, Err(solo_core::Error::InvalidInput(_))),
"empty batch must reject with InvalidInput, got: {result:?}"
);
}
#[test]
fn dispatch_remember_batch_over_cap_returns_invalid_input() {
let mut actor = build_actor();
let (reply_tx, reply_rx) = oneshot::channel();
let items: Vec<(Episode, Embedding)> = (0..(MAX_REMEMBER_BATCH_SIZE + 1))
.map(|i| (fixture_episode(&format!("over-cap-{i}")), fixture_embedding(4)))
.collect();
actor.dispatch_remember_batch(items, None, reply_tx);
let result = reply_rx.blocking_recv().unwrap();
match result {
Err(solo_core::Error::InvalidInput(msg)) => {
assert!(
msg.contains("MAX_REMEMBER_BATCH_SIZE"),
"error must reference the cap; got: {msg}"
);
}
other => panic!("expected InvalidInput, got: {other:?}"),
}
}
#[test]
fn dispatch_remember_batch_inserts_all_items_in_one_tx() {
let mut actor = build_actor();
let (reply_tx, reply_rx) = oneshot::channel();
let items: Vec<(Episode, Embedding)> = (0..5)
.map(|i| {
let mut ep = fixture_episode(&format!("batch-item-{i}"));
// Vary the salience so the round-trip assertion has
// something to bite on.
ep.salience = 0.1 + (i as f32) * 0.15;
(ep, fixture_embedding(4))
})
.collect();
let expected_ids: Vec<MemoryId> =
items.iter().map(|(e, _)| e.memory_id).collect();
let expected_saliences: Vec<f32> =
items.iter().map(|(e, _)| e.salience).collect();
actor.dispatch_remember_batch(items, Some("alice".into()), reply_tx);
let ids = reply_rx.blocking_recv().unwrap().unwrap();
// Reply is ordered: ids match input order.
assert_eq!(ids, expected_ids, "memory_ids must preserve input order");
// All 5 episode rows landed.
let n_episodes: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM episodes", [], |r| r.get(0))
.unwrap();
assert_eq!(n_episodes, 5, "5 episode rows expected");
// Saliences round-tripped.
for (id, expected) in expected_ids.iter().zip(expected_saliences.iter()) {
let s: f32 = actor
.conn
.query_row(
"SELECT salience FROM episodes WHERE memory_id = ?",
params![id.to_string()],
|r| r.get(0),
)
.unwrap();
assert!(
(s - expected).abs() < 1e-5,
"salience round-trip mismatch: got {s}, expected {expected}",
);
}
// Exactly ONE batch-level audit row, not N.
let n_batch_audit: i64 = actor
.conn
.query_row(
"SELECT COUNT(*) FROM audit_events \
WHERE operation = 'memory.remember_batch' \
AND result = 'ok'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(
n_batch_audit, 1,
"exactly one batch-level audit row per call (dev-log 0120 §3 Decision G)"
);
// The audit row's details_json carries item_count = 5.
let details: String = actor
.conn
.query_row(
"SELECT details_json FROM audit_events \
WHERE operation = 'memory.remember_batch' \
ORDER BY audit_id DESC LIMIT 1",
[],
|r| r.get(0),
)
.unwrap();
let v: serde_json::Value = serde_json::from_str(&details).unwrap();
assert_eq!(
v["item_count"], 5,
"details_json.item_count must reflect the batch size"
);
// pending_index drained on the dispatch path (post-commit) —
// 0 rows left over.
let n_pending: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM pending_index", [], |r| r.get(0))
.unwrap();
assert_eq!(
n_pending, 0,
"pending_index must be drained after a successful batch"
);
}
#[test]
fn dispatch_remember_batch_with_no_principal_persists_null_principal() {
let mut actor = build_actor();
let (reply_tx, reply_rx) = oneshot::channel();
let items: Vec<(Episode, Embedding)> = (0..3)
.map(|i| (fixture_episode(&format!("no-principal-{i}")), fixture_embedding(4)))
.collect();
actor.dispatch_remember_batch(items, None, reply_tx);
assert!(reply_rx.blocking_recv().unwrap().is_ok());
let principal: Option<String> = actor
.conn
.query_row(
"SELECT principal_subject FROM audit_events \
WHERE operation = 'memory.remember_batch' \
ORDER BY audit_id DESC LIMIT 1",
[],
|r| r.get(0),
)
.unwrap();
assert!(
principal.is_none(),
"audit row principal must be NULL when caller passed None"
);
}
#[test]
fn dispatch_remember_batch_quota_exceeded_returns_forbidden() {
let (conn, tmp) = open_test_db();
let db_path = tmp.path().join("test.db");
std::mem::forget(tmp);
let hnsw: Arc<dyn solo_core::VectorIndex + Send + Sync> =
Arc::new(StubVectorIndex::new(4));
let (_tx, rx) = mpsc::channel(1);
let mut actor = WriterActor {
conn,
hnsw,
rx,
snapshot_dir: None,
embedder_id: None,
embedder: None,
runtime_handle: None,
steward: None,
steward_slot: None,
triples_batch_signal: None,
key: None,
redactor: disabled_test_redactor(),
// 10-byte cap forces the whole batch into Forbidden — same
// pattern as `handle_remember_durable_rejects_when_quota_exceeded`.
quota_bytes: Some(10),
db_path: Some(db_path),
invalidate_tx: None,
invalidate_tenant_id: None,
};
let (reply_tx, reply_rx) = oneshot::channel();
let items: Vec<(Episode, Embedding)> = (0..3)
.map(|i| (fixture_episode(&format!("quota-batch-{i}")), fixture_embedding(4)))
.collect();
actor.dispatch_remember_batch(items, Some("alice".into()), reply_tx);
let result = reply_rx.blocking_recv().unwrap();
assert!(
matches!(result, Err(solo_core::Error::Forbidden(_))),
"over-quota batch must reject with Forbidden, got: {result:?}"
);
// Forbidden audit row lands (one, not N) — same audit-ratio
// invariant as the happy path.
let count: i64 = actor
.conn
.query_row(
"SELECT COUNT(*) FROM audit_events \
WHERE operation = 'memory.remember_batch' \
AND result = 'forbidden'",
[],
|r| r.get(0),
)
.unwrap();
assert_eq!(
count, 1,
"exactly one forbidden audit row for the over-quota batch"
);
// No episode rows landed.
let n_episodes: i64 = actor
.conn
.query_row("SELECT COUNT(*) FROM episodes", [], |r| r.get(0))
.unwrap();
assert_eq!(
n_episodes, 0,
"Forbidden return must NOT leak episode rows (no BEGIN was opened)"
);
}
#[test]
fn remember_batch_invokes_hnsw_add_per_item() {
// Use the spawned actor + WriteHandle path so we exercise the
// mpsc → dispatch glue end-to-end. The StubVectorIndex
// counts `add` calls so we can pin one per item.
let (conn, _tmp) = open_test_db();
let hnsw = Arc::new(StubVectorIndex::new(4));
let WriterSpawn { handle, join: _ } =
WriterActor::spawn(conn, hnsw.clone());
let items: Vec<(Episode, Embedding)> = (0..4)
.map(|i| (fixture_episode(&format!("hnsw-batch-{i}")), fixture_embedding(4)))
.collect();
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let ids = rt
.block_on(handle.remember_batch_as(Some("alice".into()), items))
.unwrap();
assert_eq!(ids.len(), 4);
// Drain — give the dispatch path a moment to finish the
// post-commit `pending_index` cleanup before we shut down.
std::thread::sleep(std::time::Duration::from_millis(50));
drop(handle);
std::thread::sleep(std::time::Duration::from_millis(50));
assert_eq!(
hnsw.add_count(),
4,
"hnsw.add must run once per batched item"
);
}
}
}