khive-db 0.9.0

SQLite storage backend: entities, edges, notes, events, FTS5, sqlite-vec vectors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
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
use super::*;
use crate::pool::PoolConfig;

fn setup_memory_store(table_key: &str) -> Fts5TextSearch {
    let config = PoolConfig {
        path: None,
        ..PoolConfig::default()
    };
    let pool = Arc::new(ConnectionPool::new(config).unwrap());

    {
        let writer = pool.writer().unwrap();
        ensure_fts5_schema(writer.conn(), table_key).unwrap();
    }

    Fts5TextSearch::new(pool, false, table_key.to_string())
}

/// #397 regression fixture: the FTS5 `trigram` tokenizer, matching
/// `StorageBackend::text()`'s production default (`backend.rs`) byte-for-byte
/// (`tokenize = 'trigram'`), rather than the bare `ensure_fts5_schema` helper
/// above, which omits `tokenize=` and so falls back to SQLite's own default
/// (`unicode61`). Production generic search (`operations.rs`, Plain mode) and
/// AnyTerm search both run against trigram-tokenized tables; a regression
/// covered only under the test helper's `unicode61` default would miss
/// trigram-specific behavior entirely.
fn setup_trigram_store(table_key: &str) -> Fts5TextSearch {
    let config = PoolConfig {
        path: None,
        ..PoolConfig::default()
    };
    let pool = Arc::new(ConnectionPool::new(config).unwrap());

    {
        let writer = pool.writer().unwrap();
        let table_name = format!("fts_{}", table_key);
        let ddl = format!(
            "CREATE VIRTUAL TABLE IF NOT EXISTS {} USING fts5(\
             subject_id UNINDEXED, \
             kind UNINDEXED, \
             title, \
             body, \
             tags UNINDEXED, \
             namespace UNINDEXED, \
             metadata UNINDEXED, \
             updated_at UNINDEXED, \
             record_kind, \
             tokenize = 'trigram'\
             )",
            table_name
        );
        writer.conn().execute_batch(&ddl).unwrap();
        writer
            .conn()
            .execute_batch(&rowid_map_ddl(&table_name))
            .unwrap();
    }

    Fts5TextSearch::new(pool, false, table_key.to_string())
}

fn make_document(subject_id: Uuid, title: &str, body: &str) -> TextDocument {
    TextDocument {
        subject_id,
        kind: SubstrateKind::Note,
        record_kind: None,
        title: if title.is_empty() {
            None
        } else {
            Some(title.to_string())
        },
        body: body.to_string(),
        tags: vec![],
        namespace: "test_ns".to_string(),
        metadata: None,
        updated_at: Utc::now(),
    }
}

fn make_record_kind_document(
    subject_id: Uuid,
    record_kind: &str,
    title: &str,
    body: &str,
) -> TextDocument {
    TextDocument {
        record_kind: Some(record_kind.to_string()),
        ..make_document(subject_id, title, body)
    }
}

fn ns_filter(namespace: &str) -> TextFilter {
    TextFilter {
        namespaces: vec![namespace.to_string()],
        ..TextFilter::default()
    }
}

#[tokio::test]
async fn test_upsert_and_search() {
    let store = setup_memory_store("upsert_search");

    let id = Uuid::new_v4();
    let doc = TextDocument {
        subject_id: id,
        kind: SubstrateKind::Entity,
        record_kind: None,
        title: Some("Rust Programming".to_string()),
        body: "Rust is a systems programming language focused on safety and performance."
            .to_string(),
        tags: vec!["rust".to_string(), "programming".to_string()],
        namespace: "tech".to_string(),
        metadata: None,
        updated_at: Utc::now(),
    };

    store.upsert_document(doc).await.unwrap();

    let hits = store
        .search(TextSearchRequest {
            query: "Rust programming".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("tech")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();

    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].subject_id, id);
    assert_eq!(hits[0].rank, 1);
    assert!(hits[0].score.to_f64() > 0.0);
    assert!(hits[0].title.is_some());
}

#[tokio::test]
async fn test_phrase_search() {
    let store = setup_memory_store("phrase");

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

    store
        .upsert_document(make_document(
            id1,
            "Animals",
            "The quick brown fox jumps over the lazy dog.",
        ))
        .await
        .unwrap();

    store
        .upsert_document(make_document(
            id2,
            "Colors",
            "The brown paint was quick to dry, unlike the fox.",
        ))
        .await
        .unwrap();

    let hits = store
        .search(TextSearchRequest {
            query: "quick brown fox".to_string(),
            mode: TextQueryMode::Phrase,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();

    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].subject_id, id1);

    let hits = store
        .search(TextSearchRequest {
            query: "quick brown fox".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();

    assert_eq!(hits.len(), 2);
}

/// A stale map entry — left behind by a crash between an FTS-row delete and
/// its own map-row delete — must not make `get_document`/`delete_document`
/// operate on whatever
/// unrelated document FTS5 later reuses that freed rowid for. Seeds A,
/// removes A's FTS row directly via raw SQL while leaving its map entry
/// dangling (reproducing the crash window), inserts B at the exact freed
/// rowid (pinned explicitly rather than relying on FTS5's own rowid-reuse
/// policy), then asserts `get_document(A)` is `None`, `delete_document(A)`
/// returns `false`, and B is untouched.
#[tokio::test]
async fn stale_map_entry_never_returns_or_deletes_the_wrong_document() {
    let store = setup_memory_store("stale_map_wrong_doc");
    let ns = "test_ns";

    let a = Uuid::new_v4();
    store
        .upsert_document(make_document(a, "Doc A", "first document"))
        .await
        .unwrap();

    let table = store.table_name.clone();
    let a_rowid: i64 = {
        let writer = store.pool.writer().unwrap();
        let rowid: i64 = writer
            .conn()
            .query_row(
                &format!("SELECT rowid FROM {table} WHERE subject_id = ?1"),
                rusqlite::params![a.to_string()],
                |row| row.get(0),
            )
            .expect("read A's rowid");
        writer
            .conn()
            .execute(
                &format!("DELETE FROM {table} WHERE rowid = ?1"),
                rusqlite::params![rowid],
            )
            .expect("delete A's FTS row directly, leaving its map entry stale");
        rowid
    };

    let b = Uuid::new_v4();
    {
        let writer = store.pool.writer().unwrap();
        writer
            .conn()
            .execute(
                &format!(
                    "INSERT INTO {table} \
                     (rowid, subject_id, kind, title, body, tags, namespace, metadata, \
                      updated_at, record_kind) \
                     VALUES (?1, ?2, 'note', '', 'second document', '[]', ?3, NULL, 0, NULL)"
                ),
                rusqlite::params![a_rowid, b.to_string(), ns],
            )
            .expect("insert B reusing A's freed rowid");
        // A real upsert would also write B's own map entry — do that here so
        // the assertions below isolate A's stale entry as the only anomaly.
        writer
            .conn()
            .execute(
                &format!(
                    "INSERT INTO {table}_rowids (namespace, subject_id, rowid) VALUES (?1, ?2, ?3)"
                ),
                rusqlite::params![ns, b.to_string(), a_rowid],
            )
            .expect("insert B's own map entry");
    }

    let fetched_a = store.get_document(ns, a).await.unwrap();
    assert!(
        fetched_a.is_none(),
        "a stale map entry must not resolve get_document(A) to B's document, got {fetched_a:?}"
    );

    let deleted_a = store.delete_document(ns, a).await.unwrap();
    assert!(
        !deleted_a,
        "a stale map entry must not let delete_document(A) delete B's row"
    );

    let fetched_b = store.get_document(ns, b).await.unwrap();
    assert!(
        fetched_b.is_some(),
        "B's document must remain intact after A's stale-map operations"
    );
}

/// The batch upsert path (`batch_upsert_documents_dml`) must recheck the
/// same key predicate the single-row delete already does: a stale map entry
/// for A pointing at a rowid B now occupies must not let `upsert_documents`
/// delete B while re-inserting A. Reproduces the same crash-window setup as
/// `stale_map_entry_never_returns_or_deletes_the_wrong_document` above, then
/// drives the fix via the batch path instead of the single-document path.
#[tokio::test]
async fn batch_upsert_never_deletes_the_wrong_document_via_a_stale_map_entry() {
    let store = setup_memory_store("stale_map_batch_upsert");
    let ns = "test_ns";

    let a = Uuid::new_v4();
    store
        .upsert_document(make_document(a, "Doc A", "first document"))
        .await
        .unwrap();

    let table = store.table_name.clone();
    let a_rowid: i64 = {
        let writer = store.pool.writer().unwrap();
        let rowid: i64 = writer
            .conn()
            .query_row(
                &format!("SELECT rowid FROM {table} WHERE subject_id = ?1"),
                rusqlite::params![a.to_string()],
                |row| row.get(0),
            )
            .expect("read A's rowid");
        writer
            .conn()
            .execute(
                &format!("DELETE FROM {table} WHERE rowid = ?1"),
                rusqlite::params![rowid],
            )
            .expect("delete A's FTS row directly, leaving its map entry stale");
        rowid
    };

    let b = Uuid::new_v4();
    {
        let writer = store.pool.writer().unwrap();
        writer
            .conn()
            .execute(
                &format!(
                    "INSERT INTO {table} \
                     (rowid, subject_id, kind, title, body, tags, namespace, metadata, \
                      updated_at, record_kind) \
                     VALUES (?1, ?2, 'note', '', 'second document', '[]', ?3, NULL, 0, NULL)"
                ),
                rusqlite::params![a_rowid, b.to_string(), ns],
            )
            .expect("insert B reusing A's freed rowid");
        writer
            .conn()
            .execute(
                &format!(
                    "INSERT INTO {table}_rowids (namespace, subject_id, rowid) VALUES (?1, ?2, ?3)"
                ),
                rusqlite::params![ns, b.to_string(), a_rowid],
            )
            .expect("insert B's own map entry");
    }

    let summary = store
        .upsert_documents(vec![make_document(a, "Doc A v2", "updated document")])
        .await
        .unwrap();
    assert_eq!(
        summary.failed, 0,
        "the batch upsert itself must succeed, got {summary:?}"
    );
    assert_eq!(summary.affected, 1);

    let fetched_b = store.get_document(ns, b).await.unwrap();
    assert!(
        fetched_b.is_some(),
        "a stale map entry for A must not let batch upsert delete B's row, got None"
    );
    assert_eq!(fetched_b.unwrap().body, "second document");

    let fetched_a = store.get_document(ns, a).await.unwrap();
    assert!(
        fetched_a.is_some(),
        "A must be inserted and correctly mapped by the batch upsert"
    );
    assert_eq!(fetched_a.unwrap().body, "updated document");
}

/// `delete_document_dml`'s unmanaged (no-writer-task) path wraps the FTS-row
/// delete and the map-row delete in one explicit `BEGIN IMMEDIATE` / `COMMIT`
/// / `ROLLBACK` block (`Fts5TextSearch::delete_document`'s fallback, used
/// when `current_writer_task` returns `None`) so a failure between the two
/// statements rolls both back together instead of leaving the FTS row
/// deleted while its map row survives. Forces that failure via the
/// `delete_dml_test_seam` for this test's own `(ns, a)` key and asserts on
/// the raw rows that neither statement's effect was left half-committed,
/// then disarms the seam and confirms a real delete still removes both rows.
///
/// No `#[serial_test::serial]` needed: the seam only fires for the armed
/// `(namespace, subject_id)` key, so a concurrent test operating on a
/// different key (e.g. `test_delete_document`) is unaffected even while this
/// test's seam is armed.
#[tokio::test]
async fn unmanaged_delete_rolls_back_the_fts_row_when_the_map_delete_fails() {
    let store = setup_memory_store("unmanaged_delete_rollback");
    assert!(
        store
            .current_writer_task("precondition_check")
            .unwrap()
            .is_none(),
        "this test exercises the no-writer-task fallback path; a writer-task \
         handle here would route delete_document through the queue's own \
         transaction instead of the explicit BEGIN IMMEDIATE block under test"
    );

    let ns = "test_ns";
    let a = Uuid::new_v4();
    store
        .upsert_document(make_document(a, "Doc A", "first document"))
        .await
        .unwrap();

    let table = store.table_name.clone();
    let map_table = rowid_map_table(&table);

    struct ResetSeamOnDrop {
        namespace: String,
        subject_id: Uuid,
    }
    impl Drop for ResetSeamOnDrop {
        fn drop(&mut self) {
            delete_dml_test_seam::disarm(&self.namespace, self.subject_id);
        }
    }
    let reset_seam = ResetSeamOnDrop {
        namespace: ns.to_string(),
        subject_id: a,
    };
    delete_dml_test_seam::arm(ns, a);

    let result = store.delete_document(ns, a).await;
    assert!(
        result.is_err(),
        "the forced map-row-delete failure must surface as an error, got {result:?}"
    );

    {
        let writer = store.pool.writer().unwrap();
        let fts_count: i64 = writer
            .conn()
            .query_row(
                &format!("SELECT COUNT(*) FROM {table} WHERE subject_id = ?1"),
                rusqlite::params![a.to_string()],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            fts_count, 1,
            "the FTS-row delete must roll back alongside the failed map-row delete"
        );

        let map_count: i64 = writer
            .conn()
            .query_row(
                &format!(
                    "SELECT COUNT(*) FROM {map_table} WHERE namespace = ?1 AND subject_id = ?2"
                ),
                rusqlite::params![ns, a.to_string()],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            map_count, 1,
            "the map row must survive a rolled-back delete alongside its FTS row"
        );
    }

    let fetched = store.get_document(ns, a).await.unwrap();
    assert!(
        fetched.is_some(),
        "a rolled-back delete must leave the document fully readable, got {fetched:?}"
    );

    drop(reset_seam);

    let deleted = store.delete_document(ns, a).await.unwrap();
    assert!(
        deleted,
        "with the seam cleared, delete_document must succeed and remove both rows"
    );

    let writer = store.pool.writer().unwrap();
    let fts_count: i64 = writer
        .conn()
        .query_row(
            &format!("SELECT COUNT(*) FROM {table} WHERE subject_id = ?1"),
            rusqlite::params![a.to_string()],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(
        fts_count, 0,
        "the FTS row must be gone after the real delete"
    );

    let map_count: i64 = writer
        .conn()
        .query_row(
            &format!("SELECT COUNT(*) FROM {map_table} WHERE namespace = ?1 AND subject_id = ?2"),
            rusqlite::params![ns, a.to_string()],
            |row| row.get(0),
        )
        .unwrap();
    assert_eq!(
        map_count, 0,
        "the map row must be gone after the real delete"
    );
}

/// The seam's targets are stored in a shared set, not a single `Option`
/// slot -- two independently armed `(namespace, subject_id)` targets must
/// not clobber each other: arming a second target must not disturb the
/// first, disarming one target must remove only that target and leave the
/// other armed, and a delete against either target while armed must roll
/// back on its own key regardless of what else is armed at the time.
#[tokio::test]
async fn delete_dml_test_seam_isolates_two_independently_armed_targets() {
    let store = setup_memory_store("seam_isolation");
    let ns = "test_ns";
    let a = Uuid::new_v4();
    let c = Uuid::new_v4();
    store
        .upsert_document(make_document(a, "Doc A", "doc a body"))
        .await
        .unwrap();
    store
        .upsert_document(make_document(c, "Doc C", "doc c body"))
        .await
        .unwrap();

    delete_dml_test_seam::arm(ns, a);
    delete_dml_test_seam::arm(ns, c);
    assert!(
        delete_dml_test_seam::matches(ns, a),
        "arming a second target must not un-arm the first"
    );
    assert!(
        delete_dml_test_seam::matches(ns, c),
        "the second target must itself be armed"
    );

    // Both targets armed concurrently: each delete must roll back under its
    // own key, independent of the other's armed state.
    let (result_a, result_c) =
        tokio::join!(store.delete_document(ns, a), store.delete_document(ns, c));
    assert!(
        result_a.is_err(),
        "A's forced failure must fire while A is armed"
    );
    assert!(
        result_c.is_err(),
        "C's forced failure must fire while C is armed, independent of A"
    );
    assert!(
        store.get_document(ns, a).await.unwrap().is_some(),
        "A's rolled-back delete must leave A readable"
    );
    assert!(
        store.get_document(ns, c).await.unwrap().is_some(),
        "C's rolled-back delete must leave C readable"
    );

    // Disarm only A -- C's own target must survive untouched.
    delete_dml_test_seam::disarm(ns, a);
    assert!(
        !delete_dml_test_seam::matches(ns, a),
        "disarming A must remove exactly A's own target"
    );
    assert!(
        delete_dml_test_seam::matches(ns, c),
        "disarming A must leave C's independently armed target in place"
    );

    let deleted_a = store.delete_document(ns, a).await.unwrap();
    assert!(
        deleted_a,
        "with A disarmed, its delete must succeed for real"
    );
    let result_c_still_armed = store.delete_document(ns, c).await;
    assert!(
        result_c_still_armed.is_err(),
        "C must still force-fail: disarming A must not have disarmed C"
    );

    delete_dml_test_seam::disarm(ns, c);
    let deleted_c = store.delete_document(ns, c).await.unwrap();
    assert!(
        deleted_c,
        "with C disarmed, its delete must succeed for real"
    );
}

#[tokio::test]
async fn test_delete_document() {
    let store = setup_memory_store("delete");

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

    store
        .upsert_document(make_document(id1, "Doc One", "First document content."))
        .await
        .unwrap();
    store
        .upsert_document(make_document(id2, "Doc Two", "Second document content."))
        .await
        .unwrap();

    let stats = store.stats().await.unwrap();
    assert_eq!(stats.document_count, 2);

    let deleted = store.delete_document("test_ns", id1).await.unwrap();
    assert!(deleted);

    let stats = store.stats().await.unwrap();
    assert_eq!(stats.document_count, 1);

    let deleted_again = store.delete_document("test_ns", id1).await.unwrap();
    assert!(!deleted_again);

    let doc = store.get_document("test_ns", id2).await.unwrap();
    assert!(doc.is_some());

    let doc = store.get_document("test_ns", id1).await.unwrap();
    assert!(doc.is_none());
}

/// The pre-fix `DELETE` scanned the whole FTS5 virtual
/// table because `namespace`/`subject_id` are `UNINDEXED` columns; the
/// rowid-map version resolves the same lookup through the map's primary key
/// instead. This test pins both plan shapes as strings measured against a
/// live `EXPLAIN QUERY PLAN`, not shapes it merely expects, and keeps the OLD
/// statement inline as the control so a future edit to either builder cannot
/// silently make this comparison meaningless.
#[test]
fn delete_statement_plan_uses_the_map_not_a_table_scan() {
    let conn = rusqlite::Connection::open_in_memory().expect("in-memory SQLite");
    ensure_fts5_schema(&conn, "plan_check").expect("schema");
    let table = "fts_plan_check";

    // The exact statement `delete_document_statement` issued before this fix.
    // `VIRTUAL TABLE INDEX 0:` with NO trailing operator is FTS5's plan label
    // for an unconstrained cursor: every row is opened and tested, because
    // `namespace`/`subject_id` are UNINDEXED and xBestIndex has nothing to
    // push down. That bare, operator-less form is the control this test
    // pins — measured live, not assumed.
    const OLD_DELETE_SQL: &str = "DELETE FROM {table} WHERE namespace = ?1 AND subject_id = ?2";
    let old_sql = OLD_DELETE_SQL.replace("{table}", table);
    let old_plan = explain_query_plan(
        &conn,
        &old_sql,
        &["local", "00000000-0000-0000-0000-000000000000"],
    );
    let unconstrained_scan = format!("SCAN {table} VIRTUAL TABLE INDEX 0:");
    assert!(
        old_plan
            .iter()
            .any(|step| step.trim_end() == unconstrained_scan.trim_end()),
        "control (pre-fix) plan must be an unconstrained FTS5 scan: {old_plan:?}"
    );

    let new_statement = delete_document_statement(
        table,
        "local",
        Uuid::parse_str("00000000-0000-0000-0000-000000000000").unwrap(),
    );
    let new_plan = explain_query_plan(
        &conn,
        &new_statement.sql,
        &["local", "00000000-0000-0000-0000-000000000000"],
    );
    assert!(
        !new_plan.iter().any(|step| step.trim_end() == unconstrained_scan.trim_end()),
        "fixed plan must not fall back to the unconstrained FTS5 scan the control used: {new_plan:?}"
    );
    assert!(
        new_plan
            .iter()
            .any(|step| step.contains("SEARCH fts_plan_check_rowids USING PRIMARY KEY")),
        "fixed plan must search the rowid map by its primary key: {new_plan:?}"
    );
    assert!(
        new_plan
            .iter()
            .any(|step| step.contains(&format!("SCAN {table} VIRTUAL TABLE INDEX 0:="))),
        "fixed plan's FTS5 access must be constrained (rowid equality driven by the map's \
         primary-key search), not the bare unconstrained cursor: {new_plan:?}"
    );
}

/// Runs `EXPLAIN QUERY PLAN` for `sql` bound with `params` (all bound as
/// text — sufficient for this file's plan-shape assertions) and returns each
/// step's human-readable `detail` column.
fn explain_query_plan(conn: &rusqlite::Connection, sql: &str, params: &[&str]) -> Vec<String> {
    let plan_sql = format!("EXPLAIN QUERY PLAN {sql}");
    let mut stmt = conn.prepare(&plan_sql).expect("prepare EXPLAIN QUERY PLAN");
    let params: Vec<&dyn rusqlite::types::ToSql> = params
        .iter()
        .map(|p| p as &dyn rusqlite::types::ToSql)
        .collect();
    let rows = stmt
        .query_map(params.as_slice(), |row| row.get::<_, String>(3))
        .expect("query plan rows");
    rows.collect::<Result<Vec<_>, _>>()
        .expect("collect plan steps")
}

/// `insert_document_map_statement`'s `last_insert_rowid()` must
/// resolve to the FTS5 `INSERT` that ran immediately before it on the same
/// connection — this is the whole correctness argument for keeping the two
/// statements adjacent instead of assuming SQLite's `INSERT`-then-read-back
/// contract without checking it against the actual FTS5 virtual table
/// implementation.
#[test]
fn last_insert_rowid_reflects_the_fts5_insert() {
    let conn = rusqlite::Connection::open_in_memory().expect("in-memory SQLite");
    ensure_fts5_schema(&conn, "rowid_check").expect("schema");
    let table = "fts_rowid_check";

    let doc = make_document(Uuid::new_v4(), "Title", "Body");
    let insert_stmt = insert_document_statement(table, &doc);
    {
        let mut stmt = conn.prepare(&insert_stmt.sql).expect("prepare fts insert");
        crate::sql_bridge::bind_params(&mut stmt, &insert_stmt.params).expect("bind fts insert");
        stmt.raw_execute().expect("insert fts row");
    }
    let observed_rowid = conn.last_insert_rowid();

    let actual_rowid: i64 = conn
        .query_row(
            &format!("SELECT rowid FROM {table} WHERE subject_id = ?1"),
            rusqlite::params![doc.subject_id.to_string()],
            |row| row.get(0),
        )
        .expect("read back inserted row's rowid");
    assert_eq!(
        observed_rowid, actual_rowid,
        "last_insert_rowid() must equal the FTS5 insert's own rowid"
    );
}

/// Not a CI test — a manual scale measurement, run with:
/// `cargo test -p khive-db --lib scale_measurement_delete_by_subject -- --ignored --nocapture`
///
/// Builds a 200,000-row, ~1.6 KB-body `fts_notes`-shaped table on disk under
/// `/private/tmp/` (production-shaped: file-backed, trigram-tokenized,
/// non-trivial body text — an in-memory table or tiny bodies would not
/// reproduce the overflow-page I/O the pre-fix scan pays for), then times
/// 100 deletes by subject through the OLD (pre-fix, literal) statement and
/// 100 through the NEW (rowid-map) statement, against the same corpus.
#[test]
#[ignore = "manual scale measurement, not a CI assertion — see doc comment"]
fn scale_measurement_delete_by_subject() {
    let path = std::path::PathBuf::from(format!(
        "/private/tmp/khive-fts-scale-{}.db",
        std::process::id()
    ));
    let _ = std::fs::remove_file(&path);
    let conn = rusqlite::Connection::open(&path).expect("open scratch db under /private/tmp");
    conn.execute_batch(
        "CREATE VIRTUAL TABLE fts_notes USING fts5(\
         subject_id UNINDEXED, kind UNINDEXED, title, body, tags UNINDEXED, \
         namespace UNINDEXED, metadata UNINDEXED, updated_at UNINDEXED, record_kind, \
         tokenize = 'trigram')",
    )
    .expect("create production-shaped fts_notes");
    conn.execute_batch(&rowid_map_ddl("fts_notes"))
        .expect("create rowid map");

    const ROW_COUNT: usize = 200_000;
    const DELETE_COUNT: usize = 100;
    let body_filler = "the quick brown fox jumps over the lazy dog ".repeat(35); // ~1.6 KB
    let ids: Vec<Uuid> = (0..ROW_COUNT).map(|_| Uuid::new_v4()).collect();

    let seed_start = std::time::Instant::now();
    conn.execute_batch("BEGIN").expect("begin seed");
    {
        let mut insert = conn
            .prepare(
                "INSERT INTO fts_notes \
                 (subject_id, kind, title, body, tags, namespace, metadata, updated_at, record_kind) \
                 VALUES (?1, 'note', '', ?2, '[]', 'local', NULL, 0, 'memory')",
            )
            .expect("prepare seed insert");
        for id in &ids {
            let body = format!("{body_filler}{id}");
            insert
                .execute(rusqlite::params![id.to_string(), body])
                .expect("insert seed row");
        }
    }
    conn.execute_batch("COMMIT").expect("commit seed");
    conn.execute_batch(
        "INSERT OR REPLACE INTO fts_notes_rowids (namespace, subject_id, rowid) \
         SELECT namespace, subject_id, rowid FROM fts_notes ORDER BY rowid ASC",
    )
    .expect("backfill rowid map");
    eprintln!(
        "seeded {ROW_COUNT} rows (~{} bytes/body) in {:?}",
        body_filler.len(),
        seed_start.elapsed()
    );

    // OLD: the literal statement `delete_document_statement` issued before
    // this fix — namespace/subject_id are UNINDEXED, so this is a full scan.
    const OLD_DELETE_SQL: &str = "DELETE FROM fts_notes WHERE namespace = ?1 AND subject_id = ?2";
    let old_start = std::time::Instant::now();
    {
        let mut stmt = conn.prepare(OLD_DELETE_SQL).expect("prepare old delete");
        for id in &ids[0..DELETE_COUNT] {
            let affected = stmt
                .execute(rusqlite::params!["local", id.to_string()])
                .expect("old delete");
            assert_eq!(affected, 1);
        }
    }
    let old_elapsed = old_start.elapsed();

    // NEW: the rowid-map statement, against the (now 200,000 - 100 row, i.e.
    // still effectively 200,000-row) same corpus.
    let new_statement_sql = delete_document_statement("fts_notes", "local", ids[DELETE_COUNT]).sql;
    let new_start = std::time::Instant::now();
    {
        let mut fts_stmt = conn
            .prepare(&new_statement_sql)
            .expect("prepare new delete");
        let mut map_stmt = conn
            .prepare("DELETE FROM fts_notes_rowids WHERE namespace = ?1 AND subject_id = ?2")
            .expect("prepare new delete map");
        for id in &ids[DELETE_COUNT..DELETE_COUNT * 2] {
            let affected = fts_stmt
                .execute(rusqlite::params!["local", id.to_string()])
                .expect("new delete");
            assert_eq!(affected, 1);
            map_stmt
                .execute(rusqlite::params!["local", id.to_string()])
                .expect("new delete map row");
        }
    }
    let new_elapsed = new_start.elapsed();

    let ratio = old_elapsed.as_secs_f64() / new_elapsed.as_secs_f64().max(1e-9);
    eprintln!(
        "{DELETE_COUNT} deletes by subject over {ROW_COUNT} rows: \
         OLD (full scan) = {old_elapsed:?}, NEW (rowid map) = {new_elapsed:?}, ratio = {ratio:.1}x"
    );

    let _ = std::fs::remove_file(&path);
    let _ = std::fs::remove_file(format!("{}-wal", path.display()));
    let _ = std::fs::remove_file(format!("{}-shm", path.display()));

    assert!(
        new_elapsed < old_elapsed,
        "the rowid-map delete must be faster than the full-scan delete at this scale \
         (old={old_elapsed:?}, new={new_elapsed:?})"
    );
}

#[tokio::test]
async fn test_count_with_filter() {
    let store = setup_memory_store("count_filter");
    let ns = "test_ns".to_string();

    for i in 0..5 {
        let kind = if i % 2 == 0 {
            SubstrateKind::Entity
        } else {
            SubstrateKind::Note
        };
        let doc = TextDocument {
            subject_id: Uuid::new_v4(),
            kind,
            record_kind: None,
            title: Some(format!("Doc {}", i)),
            body: format!("Content for document number {}", i),
            tags: vec![],
            namespace: ns.clone(),
            metadata: None,
            updated_at: Utc::now(),
        };
        store.upsert_document(doc).await.unwrap();
    }

    let total = store
        .count(TextFilter {
            namespaces: vec![ns.clone()],
            ..TextFilter::default()
        })
        .await
        .unwrap();
    assert_eq!(total, 5);

    let entities = store
        .count(TextFilter {
            namespaces: vec![ns.clone()],
            kinds: vec![SubstrateKind::Entity],
            ..TextFilter::default()
        })
        .await
        .unwrap();
    assert_eq!(entities, 3);

    let notes = store
        .count(TextFilter {
            namespaces: vec![ns.clone()],
            kinds: vec![SubstrateKind::Note],
            ..TextFilter::default()
        })
        .await
        .unwrap();
    assert_eq!(notes, 2);
}

#[tokio::test]
async fn test_get_document_roundtrip() {
    let store = setup_memory_store("get_roundtrip");

    let id = Uuid::new_v4();
    let original = TextDocument {
        subject_id: id,
        kind: SubstrateKind::Note,
        record_kind: Some("memory".to_string()),
        title: Some("Important Memo".to_string()),
        body: "This memo contains critical information.".to_string(),
        tags: vec!["important".to_string(), "memo".to_string()],
        namespace: "work".to_string(),
        metadata: Some(serde_json::json!({"priority": "high"})),
        updated_at: Utc::now(),
    };

    store.upsert_document(original.clone()).await.unwrap();

    let retrieved = store.get_document("work", id).await.unwrap().unwrap();
    assert_eq!(retrieved.subject_id, id);
    assert_eq!(retrieved.kind, SubstrateKind::Note);
    assert_eq!(retrieved.record_kind.as_deref(), Some("memory"));
    assert_eq!(retrieved.title, Some("Important Memo".to_string()));
    assert_eq!(retrieved.body, "This memo contains critical information.");
    assert_eq!(retrieved.tags, vec!["important", "memo"]);
    assert_eq!(retrieved.namespace, "work");
}

#[tokio::test]
async fn test_upsert_replaces_existing() {
    let store = setup_memory_store("replace");

    let id = Uuid::new_v4();
    store
        .upsert_document(make_document(id, "Original", "Original body text."))
        .await
        .unwrap();

    store
        .upsert_document(make_document(id, "Updated", "Updated body text."))
        .await
        .unwrap();

    let stats = store.stats().await.unwrap();
    assert_eq!(stats.document_count, 1);

    let doc = store.get_document("test_ns", id).await.unwrap().unwrap();
    assert_eq!(doc.title, Some("Updated".to_string()));
    assert_eq!(doc.body, "Updated body text.");
}

#[tokio::test]
async fn test_batch_upsert() {
    let store = setup_memory_store("batch");

    let docs: Vec<TextDocument> = (0..50)
        .map(|i| TextDocument {
            subject_id: Uuid::new_v4(),
            kind: SubstrateKind::Entity,
            record_kind: None,
            title: Some(format!("Item {}", i)),
            body: format!("This is the body content for item number {}", i),
            tags: vec![format!("tag_{}", i % 5)],
            namespace: "batch_ns".to_string(),
            metadata: None,
            updated_at: Utc::now(),
        })
        .collect();

    let summary = store.upsert_documents(docs).await.unwrap();
    assert_eq!(summary.attempted, 50);
    assert_eq!(summary.affected, 50);
    assert_eq!(summary.failed, 0);

    let stats = store.stats().await.unwrap();
    assert_eq!(stats.document_count, 50);
}

#[tokio::test]
async fn test_empty_search() {
    let store = setup_memory_store("empty");

    let hits = store
        .search(TextSearchRequest {
            query: "nonexistent".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();

    assert!(hits.is_empty());
}

#[tokio::test]
async fn test_rebuild() {
    let store = setup_memory_store("rebuild");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "Test",
            "Test document for rebuild.",
        ))
        .await
        .unwrap();

    let stats = store.rebuild(IndexRebuildScope::Full).await.unwrap();
    assert_eq!(stats.document_count, 1);
    assert!(!stats.needs_rebuild);
    assert!(stats.last_rebuild_at.is_some());
}

#[tokio::test]
async fn test_search_with_kind_filter() {
    let store = setup_memory_store("filter_kind");

    let id_entity = Uuid::new_v4();
    let id_note = Uuid::new_v4();

    store
        .upsert_document(TextDocument {
            subject_id: id_entity,
            kind: SubstrateKind::Entity,
            record_kind: None,
            title: Some("Rust Guide".to_string()),
            body: "A comprehensive guide to Rust programming.".to_string(),
            tags: vec![],
            namespace: "test_ns".to_string(),
            metadata: None,
            updated_at: Utc::now(),
        })
        .await
        .unwrap();

    store
        .upsert_document(TextDocument {
            subject_id: id_note,
            kind: SubstrateKind::Note,
            record_kind: None,
            title: Some("Rust Notes".to_string()),
            body: "Quick notes about Rust concepts.".to_string(),
            tags: vec![],
            namespace: "test_ns".to_string(),
            metadata: None,
            updated_at: Utc::now(),
        })
        .await
        .unwrap();

    let hits = store
        .search(TextSearchRequest {
            query: "Rust".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(TextFilter {
                kinds: vec![SubstrateKind::Entity],
                namespaces: vec!["test_ns".to_string()],
                ..TextFilter::default()
            }),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();

    assert_eq!(hits.len(), 1);
    assert_eq!(hits[0].subject_id, id_entity);
}

#[tokio::test]
async fn record_kind_filter_preserves_results_and_scopes_every_gather_mode() {
    let store = setup_trigram_store("record_kind_gather_modes");
    let memory_ids = [Uuid::new_v4(), Uuid::new_v4(), Uuid::new_v4()];
    for id in memory_ids {
        store
            .upsert_document(make_record_kind_document(
                id,
                "memory",
                "recall fixture",
                "zircon recall evidence",
            ))
            .await
            .unwrap();
    }

    let request = |record_kinds: Vec<String>| TextSearchRequest {
        query: "zircon".to_string(),
        mode: TextQueryMode::Plain,
        filter: Some(TextFilter {
            namespaces: vec!["test_ns".to_string()],
            record_kinds,
            ..TextFilter::default()
        }),
        top_k: 10,
        snippet_chars: 0,
    };
    let before_noise = store.search(request(Vec::new())).await.unwrap();
    assert_eq!(before_noise.len(), memory_ids.len());
    let mut classifier_only_query = request(Vec::new());
    classifier_only_query.query = "memory".to_string();
    assert!(
        store
            .search(classifier_only_query)
            .await
            .unwrap()
            .is_empty(),
        "an unscoped lexical query must not match indexed classifier text"
    );

    for i in 0..100 {
        store
            .upsert_document(make_record_kind_document(
                Uuid::new_v4(),
                "message",
                &format!("unrelated {i}"),
                "zircon recall evidence",
            ))
            .await
            .unwrap();
    }

    let ranked = store
        .search(request(vec!["memory".to_string()]))
        .await
        .unwrap();
    assert_eq!(
        ranked.iter().map(|hit| hit.subject_id).collect::<Vec<_>>(),
        before_noise
            .iter()
            .map(|hit| hit.subject_id)
            .collect::<Vec<_>>(),
        "indexed corpus scoping must preserve the memory-only result set and order"
    );

    for options in [
        TextSearchOptions {
            gather_mode: khive_storage::types::TextGatherMode::Unranked,
            gather_limit: None,
        },
        TextSearchOptions {
            gather_mode: khive_storage::types::TextGatherMode::RankWithinCap,
            gather_limit: Some(20),
        },
    ] {
        let hits = store
            .search_with_options(request(vec!["memory".to_string()]), options)
            .await
            .unwrap();
        assert_eq!(hits.len(), memory_ids.len());
        assert!(
            hits.iter().all(|hit| memory_ids.contains(&hit.subject_id)),
            "every gather mode must honor the indexed record-kind corpus"
        );
    }
}

#[tokio::test]
async fn record_kind_filter_scopes_count_term_stats_and_short_kind_fallback() {
    let store = setup_trigram_store("record_kind_counts");
    for (record_kind, body) in [
        ("memory", "common rare recall"),
        ("memory", "common recall"),
        ("message", "common rare message"),
        ("message", "common rare message"),
        ("ai", "common rare short classifier"),
    ] {
        store
            .upsert_document(make_record_kind_document(
                Uuid::new_v4(),
                record_kind,
                "fixture",
                body,
            ))
            .await
            .unwrap();
    }

    let memory_filter = TextFilter {
        namespaces: vec!["test_ns".to_string()],
        record_kinds: vec!["memory".to_string()],
        ..TextFilter::default()
    };
    assert_eq!(store.count(memory_filter.clone()).await.unwrap(), 2);
    let stats = store
        .term_stats(TextTermStatsRequest {
            terms: vec!["common".to_string(), "rare".to_string()],
            filter: Some(memory_filter),
        })
        .await
        .unwrap();
    let common = stats.iter().find(|stat| stat.term == "common").unwrap();
    let rare = stats.iter().find(|stat| stat.term == "rare").unwrap();
    assert_eq!(common.document_count, 2);
    assert_eq!(common.document_frequency, 2);
    assert_eq!(rare.document_frequency, 1);

    let short_kind_hits = store
        .search(TextSearchRequest {
            query: "common".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(TextFilter {
                namespaces: vec!["test_ns".to_string()],
                record_kinds: vec!["ai".to_string()],
                ..TextFilter::default()
            }),
            top_k: 10,
            snippet_chars: 0,
        })
        .await
        .unwrap();
    assert_eq!(
        short_kind_hits.len(),
        1,
        "a classifier too short for trigram postings must retain exact-filter correctness"
    );
}

#[tokio::test]
async fn test_sanitize_fts5_query() {
    assert_eq!(sanitize_fts5_query("hello world"), "hello world");
    assert_eq!(sanitize_fts5_query("hello*world"), "helloworld");
    assert_eq!(sanitize_fts5_query("\"quoted\""), "quoted");
    assert_eq!(sanitize_fts5_query("(parens)"), "parens");
    assert_eq!(sanitize_fts5_query("a + b - c"), "a b c");
    assert_eq!(sanitize_fts5_query("col:value"), "col value");
    assert_eq!(sanitize_fts5_query(""), "");
    assert_eq!(sanitize_fts5_query("***"), "");
    // M-C4: decimal numbers must not produce "syntax error near '.'"
    assert_eq!(
        sanitize_fts5_query("salience 0.9 vs 0.3"),
        "salience 0 9 vs 0 3"
    );
    assert_eq!(sanitize_fts5_query("version 1.2.3"), "version 1 2 3");
    // #397: hyphenated and dotted identifiers must space-split, not concatenate.
    assert_eq!(
        sanitize_fts5_query("khive-pack-memory"),
        "khive pack memory"
    );
    assert_eq!(
        sanitize_fts5_query("khive.pack.memory"),
        "khive pack memory"
    );
    // H1: tilde and comma must be stripped to prevent FTS5 syntax errors
    assert_eq!(sanitize_fts5_query("~hello"), "hello");
    assert_eq!(sanitize_fts5_query("\"+_~!\""), "_");
    assert_eq!(sanitize_fts5_query("NEAR(smile, 5)"), "smile 5");
    assert_eq!(sanitize_fts5_query("a,b,c"), "a b c");
    // Full operator-class matrix
    // Apostrophe fix: single quote is an FTS5 string-literal delimiter in Plain mode.
    assert_eq!(sanitize_fts5_query("Bob's tenant"), "Bobs tenant");
    assert_eq!(
        sanitize_fts5_query("tenant AND isolation"),
        "tenant isolation"
    );
    assert_eq!(
        sanitize_fts5_query("tenant OR isolation"),
        "tenant isolation"
    );
    assert_eq!(
        sanitize_fts5_query("tenant NOT isolation"),
        "tenant isolation"
    );
    assert_eq!(
        sanitize_fts5_query("tenant NEAR(isolation, 5)"),
        "tenant isolation 5"
    );
    assert_eq!(sanitize_fts5_query("tenant:isolation"), "tenant isolation");
    assert_eq!(
        sanitize_fts5_query("tenant ^ isolation"),
        "tenant isolation"
    );
    assert_eq!(
        sanitize_fts5_query("(tenant isolation)"),
        "tenant isolation"
    );
    // whitespace-only becomes empty
    assert_eq!(sanitize_fts5_query("   "), "");
    // operator-only after stripping becomes empty
    assert_eq!(sanitize_fts5_query("AND OR NOT"), "");
    // #388: dollar sign is an unconditional FTS5 MATCH-parser syntax error
    // ("syntax error near \"$\"") regardless of position in the token or query.
    assert_eq!(sanitize_fts5_query("$prev.id"), "prev id");
    assert_eq!(sanitize_fts5_query("$prev"), "prev");
    assert_eq!(sanitize_fts5_query("foo$bar"), "foobar");
    assert_eq!(sanitize_fts5_query("$"), "");
    assert_eq!(sanitize_fts5_query("$$"), "");
}

/// H1 regression: queries with tilde (~) must not produce "fts5: syntax error near '~'".
#[tokio::test]
async fn test_search_with_tilde_does_not_crash() {
    let store = setup_memory_store("tilde_query");

    store
        .upsert_document(make_document(Uuid::new_v4(), "smile", "smiling face"))
        .await
        .unwrap();

    let result = store
        .search(TextSearchRequest {
            query: "~smile".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "tilde query must not crash FTS5, got: {:?}",
        result.err()
    );
}

/// H1 regression: NEAR() queries must not produce "fts5: syntax error near ','".
#[tokio::test]
async fn test_search_with_near_operator_does_not_crash() {
    let store = setup_memory_store("near_query");

    store
        .upsert_document(make_document(Uuid::new_v4(), "smile", "quokka smile happy"))
        .await
        .unwrap();

    let result = store
        .search(TextSearchRequest {
            query: "quokka NEAR(smile, 5)".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "NEAR() query must not crash FTS5, got: {:?}",
        result.err()
    );
}

/// M-C4 regression: searching with decimal numbers must succeed (not crash FTS5).
///
/// Previously `.` was not stripped, causing FTS5 to return
/// "fts5: syntax error near '.'" when queries contained decimal literals like "0.9".
#[tokio::test]
async fn test_search_with_decimal_query_does_not_crash() {
    let store = setup_memory_store("decimal_query");

    // Insert a document that contains decimal-like content.
    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "salience thresholds",
            "salience 0 9 vs 0 3 comparison",
        ))
        .await
        .unwrap();

    // Must not return an error — previously "fts5: syntax error near '.'"
    let result = store
        .search(TextSearchRequest {
            query: "salience 0.9 vs 0.3".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "decimal query must succeed, got error: {:?}",
        result.err()
    );

    // Also test with version strings.
    let result2 = store
        .search(TextSearchRequest {
            query: "salience 0.9 vs version 1.2.3".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result2.is_ok(),
        "version-string query must succeed, got error: {:?}",
        result2.err()
    );
}

/// #397 regression: punctuated identifier queries must not be concatenated into
/// tokens that cannot occur in the indexed text.
#[tokio::test]
async fn test_search_with_hyphenated_and_dotted_queries_matches_literal_tokens() {
    let store = setup_memory_store("punctuated_query_match");

    let hyphen_id = Uuid::new_v4();
    store
        .upsert_document(make_document(hyphen_id, "doc", "LEGACY-FLAT-NOTE"))
        .await
        .unwrap();

    let dotted_id = Uuid::new_v4();
    store
        .upsert_document(make_document(dotted_id, "doc", "khive.pack.memory"))
        .await
        .unwrap();

    for (query, expected_id) in [
        ("LEGACY-FLAT-NOTE", hyphen_id),
        ("khive.pack.memory", dotted_id),
    ] {
        let hits = store
            .search(TextSearchRequest {
                query: query.to_string(),
                mode: TextQueryMode::AnyTerm,
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await
            .unwrap();
        let hit_ids: Vec<_> = hits.iter().map(|hit| hit.subject_id).collect();
        assert!(
            hit_ids.contains(&expected_id),
            "#397 query {query:?} must match {expected_id}; got {hit_ids:?}"
        );
    }
}

/// Regression: `sanitize_fts5_token_group` must keep
/// the legacy-merged bareword alternative reachable for ordinary punctuated
/// identifiers under `unicode61`. The merged form (`khivepackmemory`,
/// `previd`) is content indexed before #397's split-terms change, or content
/// whose own tokenizer collapsed punctuation the same way; a query for the
/// punctuated spelling must still find it. Assert exact hit-id sets (not
/// just "contains") so a fix that accidentally broadens the match — e.g. by
/// dropping the trigram-safety gate on multi-term merges — is caught too.
#[tokio::test]
async fn test_search_matches_legacy_merged_and_punctuated_forms_exact_ids() {
    let store = setup_memory_store("legacy_merged_punctuated");

    let legacy_merged_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            legacy_merged_id,
            "doc",
            "khivepackmemory legacy note",
        ))
        .await
        .unwrap();

    let punctuated_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            punctuated_id,
            "doc",
            "khive-pack-memory crate",
        ))
        .await
        .unwrap();

    let legacy_prev_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            legacy_prev_id,
            "DSL docs",
            "chain results with previd token",
        ))
        .await
        .unwrap();

    let punctuated_prev_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            punctuated_prev_id,
            "DSL docs",
            "chain results with the $prev.id token",
        ))
        .await
        .unwrap();

    let unrelated_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            unrelated_id,
            "doc",
            "completely unrelated content about gardening",
        ))
        .await
        .unwrap();

    for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
        for (query, expected_ids, label) in [
            (
                "khive-pack-memory",
                vec![legacy_merged_id, punctuated_id],
                "punctuated identifier reaches both legacy-merged and split forms",
            ),
            (
                "$prev.id",
                vec![legacy_prev_id, punctuated_prev_id],
                "dollar+dot query reaches both legacy-merged and split forms",
            ),
        ] {
            let hits = store
                .search(TextSearchRequest {
                    query: query.to_string(),
                    mode: mode.clone(),
                    filter: Some(ns_filter("test_ns")),
                    top_k: 10,
                    snippet_chars: 0,
                })
                .await
                .unwrap();
            let hit_ids: std::collections::HashSet<_> =
                hits.iter().map(|hit| hit.subject_id).collect();
            let expected: std::collections::HashSet<_> = expected_ids.into_iter().collect();
            assert_eq!(
                hit_ids, expected,
                "unicode61 {mode:?} query {query:?} ({label}) must match exactly {expected:?}; got {hit_ids:?}"
            );
            assert!(
                !hit_ids.contains(&unrelated_id),
                "unicode61 {mode:?} query {query:?} ({label}) must not match unrelated doc {unrelated_id}; got {hit_ids:?}"
            );
        }
    }
}

/// #397 regression: production defaults to the FTS5 `trigram`
/// tokenizer (`backend.rs`'s `StorageBackend::text()`), and generic search
/// (`operations.rs::search_notes`) queries it in `Plain` mode — neither of
/// which the prior `unicode61`/`AnyTerm`-only coverage exercised. Assert
/// exact hit-id sets (not just "contains") for punctuated identifiers,
/// decimals, versions, and legacy-normalized forms, under a real trigram
/// table, in both `Plain` and `AnyTerm` mode.
#[tokio::test]
async fn test_search_trigram_punctuated_and_decimal_queries_matches_exact_ids() {
    let store = setup_trigram_store("trigram_punctuated");

    let hyphen_id = Uuid::new_v4();
    store
        .upsert_document(make_document(hyphen_id, "doc", "khive-pack-memory crate"))
        .await
        .unwrap();

    let dotted_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            dotted_id,
            "doc",
            "the khive.pack.memory module",
        ))
        .await
        .unwrap();

    let decimal_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            decimal_id,
            "doc",
            "salience 0.9 vs 0.3 comparison",
        ))
        .await
        .unwrap();

    let version_id = Uuid::new_v4();
    store
        .upsert_document(make_document(version_id, "doc", "released version 1.2.3"))
        .await
        .unwrap();

    // A literal punctuated identifier short enough (`id` = 2 chars) that its
    // split segments are trigram-unsafe (below FTS5_TRIGRAM_MIN_SAFE_LEN):
    // only reachable via the exact-substring phrase alternative under
    // `trigram`, since the doc body embeds the raw "$prev.id" token verbatim
    // rather than as separately tokenizable words.
    let legacy_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            legacy_id,
            "DSL docs",
            "chain results with the $prev.id token",
        ))
        .await
        .unwrap();

    let unrelated_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            unrelated_id,
            "doc",
            "completely unrelated content about gardening",
        ))
        .await
        .unwrap();

    for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
        for (query, expected_id, label) in [
            ("khive-pack-memory", hyphen_id, "hyphenated identifier"),
            ("khive.pack.memory", dotted_id, "dotted identifier"),
            ("0.9", decimal_id, "decimal"),
            ("1.2.3", version_id, "version string"),
            ("$prev.id", legacy_id, "legacy dollar+dot query"),
        ] {
            let hits = store
                .search(TextSearchRequest {
                    query: query.to_string(),
                    mode: mode.clone(),
                    filter: Some(ns_filter("test_ns")),
                    top_k: 10,
                    snippet_chars: 0,
                })
                .await
                .unwrap();
            let hit_ids: std::collections::HashSet<_> =
                hits.iter().map(|hit| hit.subject_id).collect();
            assert!(
                hit_ids.contains(&expected_id),
                "trigram {mode:?} query {query:?} ({label}) must match {expected_id}; got {hit_ids:?}"
            );
            assert!(
                !hit_ids.contains(&unrelated_id),
                "trigram {mode:?} query {query:?} ({label}) must not match unrelated doc {unrelated_id}; got {hit_ids:?}"
            );
        }
    }
}

/// #397 concrete broadening regression: a hyphenated date query
/// under the trigram tokenizer must not collapse to matching every document
/// that merely shares the year. `sanitize_fts5_token_group`'s split reading
/// keeps the year term ("2026", 4 chars) fully discriminating under trigram;
/// this test pins that neither the split nor the merged OR-alternative
/// widens the match to a different day in the same year.
#[tokio::test]
async fn test_search_trigram_date_query_does_not_broaden_to_same_year() {
    let store = setup_trigram_store("trigram_date");

    let target_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            target_id,
            "doc",
            "changelog entry dated 2026-07-10",
        ))
        .await
        .unwrap();

    let other_day_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            other_day_id,
            "doc",
            "changelog entry dated 2026-03-15",
        ))
        .await
        .unwrap();

    for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
        let hits = store
            .search(TextSearchRequest {
                query: "2026-07-10".to_string(),
                mode: mode.clone(),
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 0,
            })
            .await
            .unwrap();
        let hit_ids: std::collections::HashSet<_> = hits.iter().map(|hit| hit.subject_id).collect();
        assert!(
            hit_ids.contains(&target_id),
            "trigram {mode:?} date query must match its own date {target_id}; got {hit_ids:?}"
        );
        assert!(
            !hit_ids.contains(&other_day_id),
            "trigram {mode:?} date query for 2026-07-10 must not broaden to 2026-03-15 \
             ({other_day_id}); got {hit_ids:?}"
        );
    }
}

/// #397 regression: a punctuated operand of an FTS5
/// operator expression (`NEAR(alpha-beta,5)`, `NOT(alpha-beta,5)`) makes the
/// legacy-merged OR-alternative in `sanitize_fts5_token_group` collapse to
/// multiple space-separated terms (`"alphabeta 5"`) instead of one bareword,
/// because the operand's comma spaces the trailing short segment off from
/// the merged word. Pushed unguarded into the OR-group, that fragment's
/// trigram-unsafe `5` term silently drops out under FTS5's implicit-AND
/// adjacency (see `join_plain_groups`'s doc comment), broadening the match
/// to any row containing the bare `alphabeta` merge. Pin under the
/// production trigram tokenizer that an unrelated row containing only the
/// merged bareword does not match.
#[tokio::test]
async fn test_search_trigram_operator_short_operand_does_not_broaden() {
    let store = setup_trigram_store("trigram_operator_short_operand");

    let unrelated_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            unrelated_id,
            "doc",
            "an alphabeta widget completely unrelated to any proximity or negation query",
        ))
        .await
        .unwrap();

    for (query, label) in [
        (
            "NEAR(alpha-beta,5)",
            "NEAR operator with a short numeric operand",
        ),
        (
            "NOT(alpha-beta,5)",
            "NOT operator with a short numeric operand",
        ),
    ] {
        for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
            let hits = store
                .search(TextSearchRequest {
                    query: query.to_string(),
                    mode: mode.clone(),
                    filter: Some(ns_filter("test_ns")),
                    top_k: 10,
                    snippet_chars: 0,
                })
                .await
                .unwrap();
            let hit_ids: std::collections::HashSet<_> =
                hits.iter().map(|hit| hit.subject_id).collect();
            assert!(
                !hit_ids.contains(&unrelated_id),
                "trigram {mode:?} query {query:?} ({label}) must not broaden to match \
                 {unrelated_id} via the trigram-unsafe multi-term merged alternative; \
                 got {hit_ids:?}"
            );
        }
    }
}

/// All FTS5 operator classes must not crash the generic text search surface.
#[tokio::test]
async fn test_search_with_fts_operator_matrix_does_not_crash() {
    let store = setup_memory_store("fts_operator_matrix");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "tenant isolation",
            "multi-tenant isolation operator regression anchor content",
        ))
        .await
        .unwrap();

    let cases: &[&str] = &[
        "\"tenant isolation\"",
        "Bob \"quoted\" tenant",
        "tenant AND isolation",
        "tenant OR isolation",
        "tenant NOT isolation",
        "tenant NEAR(isolation, 5)",
        "tenant*",
        "***",
        "tenant:isolation",
        "tenant ^ isolation",
        "(tenant isolation)",
        "(\"+_~!\")",
        "tenant:foo^bar*",
        "multi-tenant isolation",
        "   ",
        "",
    ];

    for query in cases {
        let result = store
            .search(TextSearchRequest {
                query: query.to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await;
        assert!(
            result.is_ok(),
            "#570 DB search query {query:?} must not crash FTS5, got: {:?}",
            result.err()
        );
    }
}

/// #388 regression: a bareword `$` query (e.g. the DSL doc query `$prev.id`) must not
/// crash the FTS5 leg. Previously `$` was untouched by `sanitize_fts5_query`, so it
/// reached FTS5 raw and produced `fts5: syntax error near "$"`, aborting the whole
/// search instead of degrading.
#[tokio::test]
async fn test_search_with_dollar_sign_does_not_crash() {
    let store = setup_memory_store("dollar_query");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "DSL docs",
            "chain results with the prev id token",
        ))
        .await
        .unwrap();

    let result = store
        .search(TextSearchRequest {
            query: "$prev.id".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "#388 dollar-sign query must not crash FTS5, got: {:?}",
        result.err()
    );
    // sanitize_fts5_query("$prev.id") == "prev id" ('$' stripped, '.' space-split),
    // confirming legitimate text search stays intact after sanitization.
    assert_eq!(result.unwrap().len(), 1);
}

/// #388 regression: a bareword query consisting solely of `$` sanitizes to an empty
/// match expression. `search()` must short-circuit to an empty result set rather than
/// sending an empty/invalid MATCH string to FTS5.
#[tokio::test]
async fn test_search_with_bare_dollar_returns_empty_not_error() {
    let store = setup_memory_store("bare_dollar_query");

    store
        .upsert_document(make_document(Uuid::new_v4(), "doc", "some content"))
        .await
        .unwrap();

    let result = store
        .search(TextSearchRequest {
            query: "$".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "#388 bare-$ query must not crash FTS5, got: {:?}",
        result.err()
    );
    assert!(result.unwrap().is_empty());
}

/// #388 regression: `$` combined with an embedded quote must not crash the FTS5 leg
/// either, exercising both the apostrophe and dollar-sign (#388) fixes together.
#[tokio::test]
async fn test_search_with_dollar_and_quote_does_not_crash() {
    let store = setup_memory_store("dollar_quote_query");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "mixed",
            "operator syntax reference content",
        ))
        .await
        .unwrap();

    let result = store
        .search(TextSearchRequest {
            query: "$prev \"operator syntax\"".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "#388 dollar+quote query must not crash FTS5, got: {:?}",
        result.err()
    );
}

/// #388 regression: `AnyTerm` mode (used by memory.recall fanout) must also survive a
/// `$`-bearing query — this mode sanitizes each term independently before joining with OR.
#[tokio::test]
async fn test_search_any_term_mode_with_dollar_does_not_crash() {
    let store = setup_memory_store("dollar_any_term_query");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "DSL docs",
            "chain results with prev id",
        ))
        .await
        .unwrap();

    let result = store
        .search(TextSearchRequest {
            query: "$prev id".to_string(),
            mode: TextQueryMode::AnyTerm,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "#388 AnyTerm dollar query must not crash FTS5, got: {:?}",
        result.err()
    );
    assert_eq!(result.unwrap().len(), 1);
}

/// Slash-bearing query (e.g. `GB/s throughput measurements`) must not crash the FTS5
/// leg. `/` was previously untouched by `sanitize_fts5_query`, reaching FTS5 raw and
/// producing `fts5: syntax error near "/"`.
#[tokio::test]
async fn test_search_with_slash_does_not_crash_and_matches() {
    let store = setup_memory_store("slash_query");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "bandwidth benchmark",
            "measured 900 GB/s throughput on the device",
        ))
        .await
        .unwrap();

    let result = store
        .search(TextSearchRequest {
            query: "GB/s throughput".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "slash query must not crash FTS5, got: {:?}",
        result.err()
    );
    assert_eq!(
        result.unwrap().len(),
        1,
        "slash query must still return the seeded matching document"
    );
}

/// AnyTerm mode (used by memory.recall fanout) must also survive a slash-bearing query.
#[tokio::test]
async fn test_search_any_term_mode_with_slash_does_not_crash() {
    let store = setup_memory_store("slash_any_term_query");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "bandwidth benchmark",
            "measured 900 GB/s throughput on the device",
        ))
        .await
        .unwrap();

    let result = store
        .search(TextSearchRequest {
            query: "GB/s".to_string(),
            mode: TextQueryMode::AnyTerm,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await;
    assert!(
        result.is_ok(),
        "AnyTerm slash query must not crash FTS5, got: {:?}",
        result.err()
    );
    assert_eq!(result.unwrap().len(), 1);
}

/// Phrase mode must preserve slash punctuation so the production trigram
/// tokenizer matches the literal substring rather than a space-split phrase.
#[tokio::test]
async fn test_search_trigram_phrase_with_slash_returns_exact_literal_id() {
    let store = setup_trigram_store("trigram_phrase_slash_literal");
    let target_id = Uuid::new_v4();
    let spaced_distractor_id = Uuid::new_v4();

    store
        .upsert_document(make_document(
            target_id,
            "slash literal",
            "measured 900 GB/s throughput on the device",
        ))
        .await
        .unwrap();
    store
        .upsert_document(make_document(
            spaced_distractor_id,
            "space-separated distractor",
            "measured 900 GB s throughput on the device",
        ))
        .await
        .unwrap();

    let hits = store
        .search(TextSearchRequest {
            query: "GB/s throughput".to_string(),
            mode: TextQueryMode::Phrase,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();
    let hit_ids: std::collections::HashSet<_> = hits.iter().map(|hit| hit.subject_id).collect();

    assert_eq!(
        hit_ids,
        std::collections::HashSet::from([target_id]),
        "trigram Phrase query must return only its slash-bearing literal; got {hit_ids:?}"
    );
}

async fn assert_slash_query_excludes_merged_alias(store: Fts5TextSearch, tokenizer: &str) {
    let slash_id = Uuid::new_v4();
    let merged_distractor_id = Uuid::new_v4();

    store
        .upsert_document(make_document(
            slash_id,
            "slash spelling",
            "the link sustained 900 GB/s transfer rates",
        ))
        .await
        .unwrap();
    store
        .upsert_document(make_document(
            merged_distractor_id,
            "merged spelling",
            "the link sustained 900 GBs transfer rates",
        ))
        .await
        .unwrap();

    for mode in [
        TextQueryMode::Plain,
        TextQueryMode::AnyTerm,
        TextQueryMode::Phrase,
    ] {
        let hits = store
            .search(TextSearchRequest {
                query: "GB/s".to_string(),
                mode: mode.clone(),
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await
            .unwrap();
        let hit_ids: std::collections::HashSet<_> = hits.iter().map(|hit| hit.subject_id).collect();

        assert_eq!(
            hit_ids,
            std::collections::HashSet::from([slash_id]),
            "{tokenizer} {mode:?} GB/s query must exclude GBs alias {merged_distractor_id}; got {hit_ids:?}"
        );
    }
}

/// The legacy merged alternative applies only to the pre-#397 hyphen/dot
/// behavior. A slash query must not match the unrelated slashless spelling.
#[tokio::test]
async fn test_search_slash_query_excludes_merged_alias_all_modes_and_tokenizers() {
    assert_slash_query_excludes_merged_alias(
        setup_memory_store("unicode61_slash_alias"),
        "unicode61",
    )
    .await;
    assert_slash_query_excludes_merged_alias(setup_trigram_store("trigram_slash_alias"), "trigram")
        .await;
}

#[test]
fn test_is_fts5_bareword_safe() {
    assert!(is_fts5_bareword_safe("hello"));
    assert!(is_fts5_bareword_safe("hello123"));
    assert!(is_fts5_bareword_safe("_prefixed"));
    assert!(is_fts5_bareword_safe("682"));
    assert!(!is_fts5_bareword_safe(""));
    for bad in [
        "#682", "B=128", "K%Prob", "a&b", "a;b", "a<b", "a>b", "a?b", "a@b", "a[b", "a\\b", "a]b",
        "a`b", "a{b", "a|b", "a}b", "a:b", "a-b",
    ] {
        assert!(
            !is_fts5_bareword_safe(bad),
            "{bad:?} must not be treated as a bareword-safe token"
        );
    }
}

#[tokio::test]
async fn test_search_with_hash_sign_does_not_crash_and_matches() {
    let store = setup_trigram_store("hash_sign_query");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "issue tracker",
            "tracking #682 Stage 2: MoE expert-cache prefetch work",
        ))
        .await
        .unwrap();

    for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
        let result = store
            .search(TextSearchRequest {
                query: "#682".to_string(),
                mode: mode.clone(),
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await;
        assert!(
            result.is_ok(),
            "#916 {mode:?} hash-sign query must not crash FTS5, got: {:?}",
            result.err()
        );
        assert_eq!(
            result.unwrap().len(),
            1,
            "#916 {mode:?} hash-sign query must still match the seeded document"
        );
    }
}

#[tokio::test]
async fn test_search_with_equals_sign_does_not_crash_and_matches() {
    let store = setup_trigram_store("equals_sign_query");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "benchmark notes",
            "chunkwise B=128 traffic arithmetic simdgroup_matrix DPLR",
        ))
        .await
        .unwrap();

    for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
        let result = store
            .search(TextSearchRequest {
                query: "B=128".to_string(),
                mode: mode.clone(),
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await;
        assert!(
            result.is_ok(),
            "#916 {mode:?} equals-sign query must not crash FTS5, got: {:?}",
            result.err()
        );
        assert_eq!(
            result.unwrap().len(),
            1,
            "#916 {mode:?} equals-sign query must still match the seeded document"
        );
    }
}

#[tokio::test]
async fn test_search_with_percent_sign_does_not_crash_and_matches() {
    let store = setup_trigram_store("percent_sign_query");

    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "sampling notes",
            "evaluated with the Min-K%Prob membership inference method",
        ))
        .await
        .unwrap();

    for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
        let result = store
            .search(TextSearchRequest {
                query: "Min-K%Prob".to_string(),
                mode: mode.clone(),
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await;
        assert!(
            result.is_ok(),
            "#916 {mode:?} percent-sign query must not crash FTS5, got: {:?}",
            result.err()
        );
        assert_eq!(
            result.unwrap().len(),
            1,
            "#916 {mode:?} percent-sign query must still match the seeded document"
        );
    }
}

#[tokio::test]
async fn test_search_with_embedded_quote_preserves_literal_match() {
    let store = setup_trigram_store("embedded_quote_query");
    let target_id = Uuid::new_v4();
    let unquoted_id = Uuid::new_v4();

    store
        .upsert_document(make_document(
            target_id,
            "quoted identifier",
            "the foo\"bar identifier appears here",
        ))
        .await
        .unwrap();
    store
        .upsert_document(make_document(
            unquoted_id,
            "unquoted identifier",
            "the foobar identifier appears here",
        ))
        .await
        .unwrap();

    for mode in [
        TextQueryMode::Plain,
        TextQueryMode::AnyTerm,
        TextQueryMode::Phrase,
    ] {
        let hits = store
            .search(TextSearchRequest {
                query: "foo\"bar".to_string(),
                mode: mode.clone(),
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await
            .unwrap();
        let hit_ids: std::collections::HashSet<_> =
            hits.into_iter().map(|hit| hit.subject_id).collect();

        assert!(
            hit_ids.contains(&target_id),
            "{mode:?} must preserve an embedded quote as literal query text; got {hit_ids:?}"
        );
    }
}

#[tokio::test]
async fn test_search_with_mixed_punctuated_and_plain_tokens_does_not_crash() {
    let store = setup_trigram_store("mixed_punctuated_plain_query");

    let target_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            target_id,
            "issue tracker",
            "tracking #682 Stage 2: MoE expert-cache prefetch work",
        ))
        .await
        .unwrap();

    let unrelated_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            unrelated_id,
            "doc",
            "completely unrelated content about gardening Stage props",
        ))
        .await
        .unwrap();

    for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
        let result = store
            .search(TextSearchRequest {
                query: "#682 Stage 2".to_string(),
                mode: mode.clone(),
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await;
        assert!(
            result.is_ok(),
            "#916 {mode:?} mixed punctuated+plain query must not crash FTS5, got: {:?}",
            result.err()
        );
        let hit_ids: std::collections::HashSet<_> =
            result.unwrap().into_iter().map(|h| h.subject_id).collect();
        assert!(
            hit_ids.contains(&target_id),
            "#916 {mode:?} mixed query must match the seeded document; got {hit_ids:?}"
        );
    }
}

#[tokio::test]
async fn test_score_is_bounded() {
    let store = setup_memory_store("score_bounds");

    for i in 0..5 {
        store
            .upsert_document(make_document(
                Uuid::new_v4(),
                &format!("Doc {}", i),
                &format!("This document discusses topic number {}", i),
            ))
            .await
            .unwrap();
    }

    let hits = store
        .search(TextSearchRequest {
            query: "document topic".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();

    for hit in &hits {
        let score = hit.score.to_f64();
        assert!(
            score > 0.0 && score <= 1.0,
            "score out of (0, 1] range: {}",
            score
        );
    }

    for (i, hit) in hits.iter().enumerate() {
        assert_eq!(hit.rank, (i + 1) as u32);
    }
}

#[tokio::test]
async fn test_rename_namespace() {
    let store = setup_memory_store("rename_ns");

    let id = Uuid::new_v4();
    let doc = TextDocument {
        subject_id: id,
        kind: SubstrateKind::Note,
        record_kind: None,
        title: Some("Rename test".to_string()),
        body: "keyword_unique_xyz".to_string(),
        tags: vec![],
        namespace: "old_ns".to_string(),
        metadata: None,
        updated_at: Utc::now(),
    };
    store.upsert_document(doc).await.unwrap();

    let before = store
        .search(TextSearchRequest {
            query: "keyword_unique_xyz".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("old_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();
    assert_eq!(before.len(), 1);

    let moved = store.rename_namespace("old_ns", "new_ns").await.unwrap();
    assert_eq!(moved, 1);

    let after_new = store
        .search(TextSearchRequest {
            query: "keyword_unique_xyz".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("new_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();
    assert_eq!(after_new.len(), 1);

    let after_old = store
        .search(TextSearchRequest {
            query: "keyword_unique_xyz".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("old_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();
    assert!(after_old.is_empty());
}

#[tokio::test]
async fn test_metadata_none_roundtrip() {
    let store = setup_memory_store("meta_none");
    let id = uuid::Uuid::new_v4();
    let doc = TextDocument {
        subject_id: id,
        kind: SubstrateKind::Note,
        record_kind: None,
        namespace: "test_ns".to_string(),
        title: None,
        body: "no metadata".to_string(),
        tags: vec![],
        metadata: None,
        updated_at: Utc::now(),
    };
    store.upsert_document(doc).await.unwrap();
    let fetched = store.get_document("test_ns", id).await.unwrap().unwrap();
    assert!(fetched.metadata.is_none());
}

#[tokio::test]
async fn test_rename_namespace_noop() {
    let store = setup_memory_store("rename_noop");

    let id = Uuid::new_v4();
    let doc = TextDocument {
        subject_id: id,
        kind: SubstrateKind::Note,
        record_kind: None,
        title: None,
        body: "noop_test_content".to_string(),
        tags: vec![],
        namespace: "same_ns".to_string(),
        metadata: None,
        updated_at: Utc::now(),
    };
    store.upsert_document(doc).await.unwrap();

    let moved = store.rename_namespace("same_ns", "same_ns").await.unwrap();
    assert_eq!(moved, 0);

    let hits = store
        .search(TextSearchRequest {
            query: "noop_test_content".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("same_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();
    assert_eq!(hits.len(), 1);
}

/// snippet_chars=0 omits snippet computation without changing IDs, ranks, or scores.
///
/// Regression for the snippet-free FTS optimization: verifies the `NULL AS snippet`
/// path returns identical candidate identity and ordering to the regular path, and
/// that every snippet field is None when snippet_chars=0.
#[tokio::test]
async fn search_snippet_chars_zero_omits_snippets_without_changing_rank() {
    let store = setup_memory_store("snippet_zero");

    let ids: Vec<Uuid> = (0..4).map(|_| Uuid::new_v4()).collect();
    let bodies = [
        "alpha bravo charlie delta the quick fox jumped",
        "bravo charlie delta echo the slow fox slept",
        "charlie delta echo foxtrot the lazy dog barked",
        "delta echo foxtrot golf a completely different document",
    ];
    for (id, body) in ids.iter().zip(bodies.iter()) {
        store
            .upsert_document(make_document(*id, "title", body))
            .await
            .unwrap();
    }

    let req_with = TextSearchRequest {
        query: "bravo charlie".to_string(),
        mode: TextQueryMode::AnyTerm,
        filter: Some(ns_filter("test_ns")),
        top_k: 10,
        snippet_chars: 64,
    };
    let req_zero = TextSearchRequest {
        snippet_chars: 0,
        ..req_with.clone()
    };

    let hits_with = store.search(req_with).await.unwrap();
    let hits_zero = store.search(req_zero).await.unwrap();

    assert!(!hits_with.is_empty(), "snippet path must return hits");
    assert_eq!(
        hits_with.len(),
        hits_zero.len(),
        "hit count must be identical regardless of snippet_chars"
    );

    for (hw, hz) in hits_with.iter().zip(hits_zero.iter()) {
        assert_eq!(hw.subject_id, hz.subject_id, "subject_id must match");
        assert_eq!(hw.rank, hz.rank, "rank must match");
        assert!(
            (hw.score.to_f64() - hz.score.to_f64()).abs() < 1e-12,
            "score must match: with={} zero={}",
            hw.score.to_f64(),
            hz.score.to_f64()
        );
        assert!(
            hz.snippet.is_none(),
            "snippet must be None when snippet_chars=0, got {:?}",
            hz.snippet
        );
    }
}

// Boundary case: a hit ranked near the last position in a multi-result set
// must still have snippet=None when snippet_chars=0.
#[tokio::test]
async fn search_snippet_chars_zero_bottom_ranked_hit_has_no_snippet() {
    let store = setup_memory_store("snippet_zero_boundary");

    // Insert enough docs so the last-ranked result is a "boundary" case.
    let ids: Vec<Uuid> = (0..5).map(|_| Uuid::new_v4()).collect();
    for (i, id) in ids.iter().enumerate() {
        let body = format!("keyword_boundary doc number {i} with varying relevance");
        store
            .upsert_document(make_document(*id, "t", &body))
            .await
            .unwrap();
    }

    let hits = store
        .search(TextSearchRequest {
            query: "keyword_boundary".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 0,
        })
        .await
        .unwrap();

    assert_eq!(hits.len(), 5, "all 5 docs must match");
    // The last-ranked hit (boundary) must also have no snippet.
    let last = hits.last().unwrap();
    assert!(
        last.snippet.is_none(),
        "bottom-ranked hit must have snippet=None when snippet_chars=0, got {:?}",
        last.snippet
    );
}

/// Score normalization: all scores stay in (0, 1], and a single-hit result
/// scores ≈ 1.0. This validates the normalization formula independent of
/// FTS5 rank ordering guarantees (which are already tested via `rank` field).
#[tokio::test]
async fn test_score_normalization_range() {
    let store = setup_memory_store("score_range");

    // Insert three documents; only two match the query.
    let id1 = Uuid::new_v4();
    let id2 = Uuid::new_v4();
    let id3 = Uuid::new_v4();
    store
        .upsert_document(make_document(
            id1,
            "normtest topic",
            "normtest normtest normtest",
        ))
        .await
        .unwrap();
    store
        .upsert_document(make_document(
            id2,
            "normtest light",
            "other content without the keyword",
        ))
        .await
        .unwrap();
    store
        .upsert_document(make_document(
            id3,
            "irrelevant title",
            "completely different document content",
        ))
        .await
        .unwrap();

    let hits = store
        .search(TextSearchRequest {
            query: "normtest".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();

    // id3 must not match; id1 and id2 should.
    assert!(!hits.is_empty(), "at least one doc must match");
    assert!(
        hits.iter().all(|h| h.subject_id != id3),
        "id3 must not appear"
    );

    // All scores must be in (0, 1].
    for h in &hits {
        let s = h.score.to_f64();
        assert!(s > 0.0 && s <= 1.0, "score out of (0,1]: {s}");
    }
    // Rank field must be 1-indexed and contiguous.
    for (i, h) in hits.iter().enumerate() {
        assert_eq!(h.rank, (i + 1) as u32, "rank must equal position+1");
    }
    // Best hit (rank=1) must score ≈ 1.0 — normalization anchors the best
    // rank to 1.0 regardless of absolute BM25 magnitude.
    assert!(
        hits[0].score.to_f64() > 0.99,
        "top hit must score ≈ 1.0, got {}",
        hits[0].score.to_f64()
    );

    // Single-hit result: the only match scores ≈ 1.0 (degenerate case:
    // range == 0 → all hits get 1.0).
    let single_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            single_id,
            "xqzplurp_unique_marker",
            "xqzplurp_unique_marker body",
        ))
        .await
        .unwrap();
    let single = store
        .search(TextSearchRequest {
            query: "xqzplurp_unique_marker".to_string(),
            mode: TextQueryMode::Plain,
            filter: Some(ns_filter("test_ns")),
            top_k: 10,
            snippet_chars: 64,
        })
        .await
        .unwrap();
    assert_eq!(single.len(), 1);
    assert!(
        single[0].score.to_f64() > 0.99,
        "single-hit must score ≈ 1.0, got {}",
        single[0].score.to_f64()
    );
}

// ── search_with_options tests ─────────────────────────────────────────────

#[tokio::test]
async fn search_with_options_default_matches_search() {
    let store = setup_memory_store("opts_default");

    let id1 = Uuid::new_v4();
    let id2 = Uuid::new_v4();
    store
        .upsert_document(make_document(id1, "alpha beta", "alpha beta gamma"))
        .await
        .unwrap();
    store
        .upsert_document(make_document(id2, "delta epsilon", "delta epsilon zeta"))
        .await
        .unwrap();

    let req = TextSearchRequest {
        query: "alpha".to_string(),
        mode: TextQueryMode::Plain,
        filter: Some(ns_filter("test_ns")),
        top_k: 10,
        snippet_chars: 0,
    };

    let plain = store.search(req.clone()).await.unwrap();
    let with_opts = store
        .search_with_options(req, TextSearchOptions::default())
        .await
        .unwrap();

    assert_eq!(
        plain.len(),
        with_opts.len(),
        "default options must match plain search"
    );
    for (p, w) in plain.iter().zip(with_opts.iter()) {
        assert_eq!(p.subject_id, w.subject_id);
        assert_eq!(p.rank, w.rank);
    }
}

#[tokio::test]
async fn search_unranked_returns_capped_candidates() {
    let store = setup_memory_store("unranked_cap");

    for i in 0..10u32 {
        store
            .upsert_document(make_document(
                Uuid::new_v4(),
                &format!("doc {i}"),
                &format!("keyword content {i}"),
            ))
            .await
            .unwrap();
    }

    let hits = store
        .search_with_options(
            TextSearchRequest {
                query: "keyword".to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(ns_filter("test_ns")),
                top_k: 5,
                snippet_chars: 0,
            },
            TextSearchOptions {
                gather_mode: khive_storage::types::TextGatherMode::Unranked,
                gather_limit: None,
            },
        )
        .await
        .unwrap();

    assert_eq!(hits.len(), 5, "unranked must cap at top_k");
    for h in &hits {
        assert!(
            (h.score.to_f64() - 1.0).abs() < 1e-10,
            "unranked hits must have uniform score 1.0, got {}",
            h.score.to_f64()
        );
        assert!(
            h.snippet.is_none(),
            "unranked with snippet_chars=0 must have no snippet"
        );
    }
}

#[tokio::test]
async fn search_rank_within_cap_returns_ranked_subset() {
    let store = setup_memory_store("rank_within_cap");

    let ids: Vec<Uuid> = (0..5).map(|_| Uuid::new_v4()).collect();
    let bodies = [
        "rust programming language systems",
        "rust systems memory safety",
        "programming language design patterns",
        "memory management allocation",
        "systems software engineering",
    ];
    for (id, body) in ids.iter().zip(bodies.iter()) {
        store
            .upsert_document(make_document(*id, "doc", body))
            .await
            .unwrap();
    }

    let hits = store
        .search_with_options(
            TextSearchRequest {
                query: "rust".to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(ns_filter("test_ns")),
                top_k: 3,
                snippet_chars: 0,
            },
            TextSearchOptions {
                gather_mode: khive_storage::types::TextGatherMode::RankWithinCap,
                gather_limit: Some(10),
            },
        )
        .await
        .unwrap();

    // Must return at most top_k (3) hits with BM25-normalized scores.
    assert!(hits.len() <= 3, "rank_within_cap must cap at top_k");
    assert!(!hits.is_empty(), "must find at least one 'rust' hit");
    for h in &hits {
        let score = h.score.to_f64();
        assert!(score > 0.0 && score <= 1.0, "scores must be in (0, 1]");
    }
    // Ranks must be 1-indexed and contiguous.
    for (i, h) in hits.iter().enumerate() {
        assert_eq!(h.rank, (i + 1) as u32, "rank must equal position+1");
    }
}

// ── term_stats tests ──────────────────────────────────────────────────────

#[tokio::test]
async fn term_stats_returns_df_and_idf_for_fixture() {
    let store = setup_memory_store("term_stats_fixture");

    // Insert 10 docs: 3 contain "rare_term", 8 contain "common_term".
    for i in 0..8u32 {
        store
            .upsert_document(make_document(
                Uuid::new_v4(),
                &format!("doc {i}"),
                &format!("common_term content number {i}"),
            ))
            .await
            .unwrap();
    }
    for i in 0..3u32 {
        store
            .upsert_document(make_document(
                Uuid::new_v4(),
                &format!("rare {i}"),
                &format!("rare_term common_term extra {i}"),
            ))
            .await
            .unwrap();
    }

    let stats = store
        .term_stats(TextTermStatsRequest {
            terms: vec!["rare_term".to_string(), "common_term".to_string()],
            filter: Some(ns_filter("test_ns")),
        })
        .await
        .unwrap();

    assert_eq!(stats.len(), 2);
    let rare = stats.iter().find(|s| s.term == "rare_term").unwrap();
    let common = stats.iter().find(|s| s.term == "common_term").unwrap();

    assert_eq!(rare.document_count, 11, "total doc count must be 11");
    assert_eq!(rare.document_frequency, 3, "rare_term appears in 3 docs");
    assert_eq!(
        common.document_frequency, 11,
        "common_term appears in all 11 docs"
    );
    assert!(
        rare.inverse_document_frequency > common.inverse_document_frequency,
        "rarer term must have higher IDF: rare={} common={}",
        rare.inverse_document_frequency,
        common.inverse_document_frequency
    );
}

#[tokio::test]
async fn term_stats_empty_terms_returns_empty() {
    let store = setup_memory_store("term_stats_empty");
    store
        .upsert_document(make_document(Uuid::new_v4(), "t", "body"))
        .await
        .unwrap();

    let stats = store
        .term_stats(TextTermStatsRequest {
            terms: vec![],
            filter: Some(ns_filter("test_ns")),
        })
        .await
        .unwrap();
    assert!(stats.is_empty());
}

#[tokio::test]
async fn term_stats_missing_term_has_zero_df() {
    let store = setup_memory_store("term_stats_missing");
    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "doc",
            "only this content exists",
        ))
        .await
        .unwrap();

    let stats = store
        .term_stats(TextTermStatsRequest {
            terms: vec!["xyzzy_nonexistent".to_string()],
            filter: Some(ns_filter("test_ns")),
        })
        .await
        .unwrap();
    assert_eq!(stats.len(), 1);
    assert_eq!(stats[0].document_frequency, 0);
}

async fn assert_slash_term_stats_exclude_merged_alias(store: Fts5TextSearch, tokenizer: &str) {
    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "slash spelling",
            "the link sustained 900 GB/s transfer rates",
        ))
        .await
        .unwrap();
    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "merged spelling",
            "the link sustained 900 GBs transfer rates",
        ))
        .await
        .unwrap();

    let stats = store
        .term_stats(TextTermStatsRequest {
            terms: vec!["GB/s".to_string()],
            filter: Some(ns_filter("test_ns")),
        })
        .await
        .unwrap();

    assert_eq!(stats.len(), 1);
    assert_eq!(stats[0].sanitized_term, "\"GB/s\"");
    assert_eq!(
        stats[0].document_frequency, 1,
        "{tokenizer} term stats must count only the slash-bearing document"
    );
    assert_eq!(stats[0].document_count, 2);
}

#[tokio::test]
async fn term_stats_slash_literal_excludes_merged_alias_all_tokenizers() {
    assert_slash_term_stats_exclude_merged_alias(
        setup_memory_store("unicode61_term_stats_slash_alias"),
        "unicode61",
    )
    .await;
    assert_slash_term_stats_exclude_merged_alias(
        setup_trigram_store("trigram_term_stats_slash_alias"),
        "trigram",
    )
    .await;
}

/// Dropping the FTS5 virtual table makes every per-item INSERT in the batch
/// fail with a SQLite error.  Each failure is caught by the SAVEPOINT so the
/// outer transaction still commits and the method returns Ok.
///
/// Regression: before the fix, `first_error` was always `String::new()` even
/// when `failed > 0`.  This test is RED against the unfixed code and GREEN
/// after the fix.
#[tokio::test]
async fn upsert_documents_first_error_populated_on_item_failure() {
    let table_key = "first_err_fts";

    // Keep a clone of the pool so we can manipulate the schema before the batch.
    let config = PoolConfig {
        path: None,
        ..PoolConfig::default()
    };
    let pool = Arc::new(ConnectionPool::new(config).unwrap());
    {
        let writer = pool.writer().unwrap();
        ensure_fts5_schema(writer.conn(), table_key).unwrap();
    }
    let store = Fts5TextSearch::new(Arc::clone(&pool), false, table_key.to_string());

    // Drop the FTS5 virtual table (which also removes all its shadow tables).
    // Every subsequent DELETE/INSERT on the table will fail with "no such table".
    // Each failure is isolated by a SAVEPOINT, so the outer transaction commits.
    {
        let writer = pool.writer().unwrap();
        writer
            .conn()
            .execute_batch(&format!("DROP TABLE fts_{}", table_key))
            .expect("drop FTS5 virtual table");
    }

    let docs = vec![
        make_document(Uuid::new_v4(), "Doc A", "body a"),
        make_document(Uuid::new_v4(), "Doc B", "body b"),
    ];

    let summary = store.upsert_documents(docs).await.unwrap();

    assert!(
        summary.failed > 0,
        "expected at least one item to fail after the FTS5 table was dropped"
    );
    assert!(
        !summary.first_error.is_empty(),
        "first_error must describe the failure when failed > 0, \
         but got an empty string; the error is being silently swallowed"
    );
}

/// ADR-067 Component A entry 4: with `KHIVE_WRITE_QUEUE=1`, `upsert_documents`
/// routes through the WriterTask channel instead of the pool-mutex path, and
/// both documents are actually committed and independently readable back.
///
/// Constructed via a `PoolConfig` literal (`write_queue_enabled: Some(true)`), not
/// the `KHIVE_WRITE_QUEUE` env var — that env var is process-global and this
/// crate's other tests are NOT `#[serial]` against it, so a window where it
/// is set here could leak into a concurrently-scheduled test's own pool
/// construction (ADR-067 Component A).
#[tokio::test]
async fn upsert_documents_routes_through_writer_task_when_flag_enabled() {
    let table_key = "write_queue_flag_test";
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("write_queue_text.db");
    let pool_cfg = PoolConfig {
        path: Some(path.clone()),
        write_queue_enabled: Some(true),
        ..PoolConfig::for_test()
    };
    let pool = Arc::new(ConnectionPool::new(pool_cfg).unwrap());
    {
        let writer = pool.writer().unwrap();
        ensure_fts5_schema(writer.conn(), table_key).unwrap();
    }

    let store = Fts5TextSearch::new(Arc::clone(&pool), true, table_key.to_string());

    let subject1 = Uuid::new_v4();
    let subject2 = Uuid::new_v4();
    let docs = vec![
        make_document(subject1, "Doc A", "body a"),
        make_document(subject2, "Doc B", "body b"),
    ];

    let summary = store.upsert_documents(docs).await.unwrap();
    assert_eq!(summary.attempted, 2);
    assert_eq!(summary.affected, 2);
    assert_eq!(summary.failed, 0);

    assert!(store
        .get_document("test_ns", subject1)
        .await
        .unwrap()
        .is_some());
    assert!(store
        .get_document("test_ns", subject2)
        .await
        .unwrap()
        .is_some());
    assert_eq!(
        pool.writer_task_spawn_count(),
        1,
        "the flag-ON path must actually spawn and use the writer task"
    );
}

/// #1064 regression: a hyphenated identifier token mixed with plain keyword
/// terms (`"ADR-086 workspace mirror"`) must still surface the document whose
/// title/body contains that identifier under the production `trigram`
/// tokenizer, in both `Plain` and `AnyTerm` mode.
#[tokio::test]
async fn test_search_hyphenated_id_with_plain_terms_matches_exact_id() {
    let store = setup_trigram_store("issue_1064_hyphenated_multiword");
    let target_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            target_id,
            "ADR-086",
            "ADR-086 workspace mirror amendment document",
        ))
        .await
        .unwrap();
    let unrelated_id = Uuid::new_v4();
    store
        .upsert_document(make_document(
            unrelated_id,
            "unrelated",
            "completely unrelated gardening content",
        ))
        .await
        .unwrap();

    for mode in [TextQueryMode::Plain, TextQueryMode::AnyTerm] {
        let hits = store
            .search(TextSearchRequest {
                query: "ADR-086 workspace mirror".to_string(),
                mode: mode.clone(),
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await
            .unwrap();
        let hit_ids: std::collections::HashSet<_> = hits.iter().map(|h| h.subject_id).collect();
        assert!(
            hit_ids.contains(&target_id),
            "#1064 {mode:?} query must match {target_id}, got {hit_ids:?}"
        );
        assert!(
            !hit_ids.contains(&unrelated_id),
            "#1064 {mode:?} query must not match unrelated doc, got {hit_ids:?}"
        );
    }
}

// `fts_passes` is an issued counter (khive_storage::usage): it must count
// one FTS5 statement actually prepared and executed. An empty/fully-sanitized
// query short-circuits `search()` before any statement exists (`build_match_expr`
// returns `None`) and must not count; a normal query that does reach
// `conn.prepare` must count exactly once.
#[tokio::test]
async fn test_search_empty_query_does_not_count_fts_pass() {
    let store = setup_memory_store("empty_query_no_count");

    let ctx = khive_storage::usage::UsageContext::new();
    let hits = khive_storage::usage::scope(ctx.clone(), async {
        store
            .search(TextSearchRequest {
                query: String::new(),
                mode: TextQueryMode::Plain,
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await
    })
    .await
    .unwrap();

    assert!(hits.is_empty(), "empty query must return no hits");
    let snap = ctx.snapshot();
    assert!(
        snap.get("fts_passes").is_none(),
        "an empty query must never prepare an FTS5 statement, so fts_passes \
         must not count; got {snap:?}"
    );
}

#[tokio::test]
async fn test_search_fully_sanitized_query_does_not_count_fts_pass() {
    let store = setup_memory_store("sanitized_query_no_count");

    // Pure FTS5 metacharacters — `sanitize_fts5_token_group` strips every
    // token to nothing, so `build_match_expr` still returns `None`.
    let ctx = khive_storage::usage::UsageContext::new();
    let hits = khive_storage::usage::scope(ctx.clone(), async {
        store
            .search(TextSearchRequest {
                query: "\"\"^^**".to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await
    })
    .await
    .unwrap();

    assert!(hits.is_empty(), "fully-sanitized query must return no hits");
    let snap = ctx.snapshot();
    assert!(
        snap.get("fts_passes").is_none(),
        "a fully-sanitized query must never prepare an FTS5 statement, so \
         fts_passes must not count; got {snap:?}"
    );
}

#[tokio::test]
async fn test_search_normal_query_counts_exactly_one_fts_pass() {
    let store = setup_memory_store("normal_query_counts_once");

    let id = Uuid::new_v4();
    store
        .upsert_document(make_document(id, "counted", "fts pass accounting body"))
        .await
        .unwrap();

    let ctx = khive_storage::usage::UsageContext::new();
    let hits = khive_storage::usage::scope(ctx.clone(), async {
        store
            .search(TextSearchRequest {
                query: "accounting".to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 64,
            })
            .await
    })
    .await
    .unwrap();

    assert_eq!(hits.len(), 1, "query must match the upserted document");
    let snap = ctx.snapshot();
    assert_eq!(
        snap["fts_passes"], 1,
        "a query that reaches conn.prepare must count exactly one fts_pass; got {snap:?}"
    );
}

#[tokio::test]
async fn test_cancelled_search_does_not_issue_fts_pass() {
    let store = Arc::new(setup_memory_store("cancelled_search_counts"));
    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "counted",
            "cancelled continuation accounting",
        ))
        .await
        .unwrap();

    let pool = Arc::clone(&store.pool);
    let reader_blocker = pool.writer().unwrap();
    let ctx = khive_storage::usage::UsageContext::new();
    let blocked_store = Arc::clone(&store);
    let task = tokio::spawn(khive_storage::usage::scope(ctx.clone(), async move {
        blocked_store
            .search(TextSearchRequest {
                query: "continuation".to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 0,
            })
            .await
    }));

    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    task.abort();
    let joined = task.await;
    assert!(joined.unwrap_err().is_cancelled());
    assert!(
        ctx.snapshot().get("fts_passes").is_none(),
        "a search cancelled during reader checkout must not issue an FTS pass"
    );
    drop(reader_blocker);

    let hits = khive_storage::usage::scope(ctx.clone(), async {
        store
            .search(TextSearchRequest {
                query: "continuation".to_string(),
                mode: TextQueryMode::Plain,
                filter: Some(ns_filter("test_ns")),
                top_k: 10,
                snippet_chars: 0,
            })
            .await
    })
    .await
    .unwrap();
    assert_eq!(
        hits.len(),
        1,
        "the pool must remain usable after cancellation"
    );
    assert_eq!(
        ctx.snapshot()["fts_passes"],
        1,
        "only the follow-up search may issue an FTS pass after cancellation"
    );
}

#[tokio::test]
async fn test_search_unranked_counts_exactly_one_fts_pass() {
    let store = setup_memory_store("unranked_counts_once");
    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "counted",
            "unranked pass accounting",
        ))
        .await
        .unwrap();

    let ctx = khive_storage::usage::UsageContext::new();
    khive_storage::usage::scope(ctx.clone(), async {
        store
            .search_with_options(
                TextSearchRequest {
                    query: "unranked".to_string(),
                    mode: TextQueryMode::Plain,
                    filter: Some(ns_filter("test_ns")),
                    top_k: 10,
                    snippet_chars: 0,
                },
                TextSearchOptions {
                    gather_mode: TextGatherMode::Unranked,
                    gather_limit: None,
                },
            )
            .await
    })
    .await
    .unwrap();

    assert_eq!(ctx.snapshot()["fts_passes"], 1);
}

#[tokio::test]
async fn test_search_rank_within_cap_counts_two_fts_passes() {
    let store = setup_memory_store("rank_within_cap_counts_twice");
    store
        .upsert_document(make_document(
            Uuid::new_v4(),
            "counted",
            "rank within cap accounting",
        ))
        .await
        .unwrap();

    let ctx = khive_storage::usage::UsageContext::new();
    khive_storage::usage::scope(ctx.clone(), async {
        store
            .search_with_options(
                TextSearchRequest {
                    query: "accounting".to_string(),
                    mode: TextQueryMode::Plain,
                    filter: Some(ns_filter("test_ns")),
                    top_k: 10,
                    snippet_chars: 0,
                },
                TextSearchOptions {
                    gather_mode: TextGatherMode::RankWithinCap,
                    gather_limit: Some(20),
                },
            )
            .await
    })
    .await
    .unwrap();

    assert_eq!(ctx.snapshot()["fts_passes"], 2);
}

/// ADR-136 D1 gate 2/4: `rename_namespace`'s flag-on path must route through
/// the pool-wide `WriterTask`, not `with_writer_unmanaged`'s
/// standalone-connection path, when the write queue is enabled — same
/// occupier / `queue_depth()` technique as
/// `upsert_documents_routes_through_writer_task_when_flag_enabled` above (a
/// `writer_task_spawn_count() == 1` assertion alone is a false positive:
/// `upsert_document` setup calls already spawn/use the task). Red-proof:
/// reverting the `current_writer_task("fts_rename_namespace")` branch in
/// `rename_namespace` (forcing every call through `with_writer_unmanaged`)
/// makes `saw_enqueued` stay `false` and this test fail — see the impl
/// report for the exact revert/run/restore transcript.
#[tokio::test]
async fn rename_namespace_routes_through_writer_task_when_flag_enabled() {
    let table_key = "write_queue_rename_namespace";
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("write_queue_rename_namespace.db");
    let pool_cfg = PoolConfig {
        path: Some(path.clone()),
        write_queue_enabled: Some(true),
        ..PoolConfig::for_test()
    };
    let pool = Arc::new(ConnectionPool::new(pool_cfg).unwrap());
    {
        let writer = pool.writer().unwrap();
        ensure_fts5_schema(writer.conn(), table_key).unwrap();
    }

    let store = Fts5TextSearch::new(Arc::clone(&pool), true, table_key.to_string());

    let subject = Uuid::new_v4();
    let mut doc = make_document(subject, "Doc A", "body a");
    doc.namespace = "old_ns".to_string();
    store.upsert_document(doc).await.unwrap();

    let writer_task = pool
        .writer_task_handle()
        .unwrap()
        .expect("writer task must be spawned for a file-backed pool with the flag on");

    let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
    let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
    let occupier = {
        let writer_task = writer_task.clone();
        tokio::spawn(async move {
            writer_task
                .send(move |_conn| {
                    let _ = started_tx.send(());
                    let _ = release_rx.blocking_recv();
                    Ok::<(), StorageError>(())
                })
                .await
        })
    };

    started_rx
        .await
        .expect("occupier must signal it has started running inside the writer task");
    assert_eq!(
        writer_task.queue_depth(),
        0,
        "channel must start empty once the occupier has been dequeued and is running"
    );

    let rename_task = tokio::spawn(async move { store.rename_namespace("old_ns", "new_ns").await });

    let mut saw_enqueued = false;
    for _ in 0..100 {
        if writer_task.queue_depth() >= 1 {
            saw_enqueued = true;
            break;
        }
        tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    }
    assert!(
        saw_enqueued,
        "rename_namespace's write request never appeared in the writer task's channel \
         while the occupier held the single drain slot — rename_namespace is not routing \
         through the shared writer task"
    );

    release_tx
        .send(())
        .expect("occupier must still be waiting on the release signal");
    occupier
        .await
        .expect("occupier task must not panic")
        .expect("occupier write must succeed");
    let moved = rename_task
        .await
        .expect("rename task must not panic")
        .expect("rename_namespace must succeed once unblocked");
    assert_eq!(moved, 1);
}

/// ADR-136 D1 gate 3/4: with `KHIVE_WRITE_ROUTING=strict` and no writer task
/// available, `rename_namespace` must error instead of silently falling back
/// to `with_writer_unmanaged`'s standalone-connection path.
#[tokio::test]
async fn rename_namespace_strict_routing_fails_closed_without_writer_task() {
    let table_key = "strict_rename_namespace";
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("strict_rename_namespace.db");
    let pool_cfg = PoolConfig {
        path: Some(path.clone()),
        write_queue_enabled: Some(false),
        write_routing_strict: true,
        ..PoolConfig::for_test()
    };
    let pool = Arc::new(ConnectionPool::new(pool_cfg).unwrap());
    {
        let writer = pool.writer().unwrap();
        ensure_fts5_schema(writer.conn(), table_key).unwrap();
    }

    let store = Fts5TextSearch::new(Arc::clone(&pool), true, table_key.to_string());
    let err = store.rename_namespace("old_ns", "new_ns").await.expect_err(
        "KHIVE_WRITE_ROUTING=strict with no writer task must fail closed, not silently \
             fall back to with_writer_unmanaged",
    );
    assert!(
        err.to_string().contains("strict"),
        "error must name strict routing, got: {err}"
    );
}

/// ADR-136 D1 gate 3 amendment: a store built on a thread with no ambient
/// Tokio runtime caches `writer_task: None` at construction — the pool
/// returns `Err(WriterTaskNoRuntime)`, which `Fts5TextSearch::new` collapses
/// via `.ok().flatten()` (a documented, deliberate best-effort degrade). The
/// bug this guards against: without `with_writer`'s write-time re-lookup
/// (`current_writer_task`), that construction-time `None` would stick
/// forever, so a *normal* FTS write (`upsert_document`, routed through the
/// general `with_writer` helper, not a maintenance path) issued later inside
/// a real runtime would silently bypass the queue via the direct-connection
/// path instead of routing through the shared `WriterTask` like every other
/// write on this pool. Same occupier / `queue_depth()` discriminator as
/// `rename_namespace_routes_through_writer_task_when_flag_enabled` above,
/// proving genuine queue routing rather than a `writer_task_spawn_count() ==
/// 1` false positive.
///
/// Deliberately `#[test]`, not `#[tokio::test]`: construction must happen
/// with no ambient runtime, which a `#[tokio::test]` function body would
/// not give it (the whole test body already runs on a Tokio worker thread).
/// Red-proof: reverting `with_writer`'s `self.current_writer_task(op)` check
/// back to `&self.writer_task` makes `saw_enqueued` stay `false` and this
/// test fail — the write takes the direct-connection path immediately
/// instead of ever appearing in the writer task's channel.
#[test]
fn general_write_routes_through_writer_task_when_store_built_outside_runtime() {
    let table_key = "general_write_no_runtime_construction";
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("general_write_no_runtime_construction.db");
    let pool_cfg = PoolConfig {
        path: Some(path.clone()),
        write_queue_enabled: Some(true),
        ..PoolConfig::for_test()
    };
    let pool = Arc::new(ConnectionPool::new(pool_cfg).unwrap());
    {
        let writer = pool.writer().unwrap();
        ensure_fts5_schema(writer.conn(), table_key).unwrap();
    }

    assert!(
        tokio::runtime::Handle::try_current().is_err(),
        "sanity: this test body must not already be running inside a Tokio runtime"
    );
    // Construction happens here, outside any runtime — reproduces the
    // permanent-`None`-cache scenario `writer_task_handle()`'s doc comment
    // describes.
    let store = Fts5TextSearch::new(Arc::clone(&pool), true, table_key.to_string());

    let rt = tokio::runtime::Runtime::new().unwrap();
    rt.block_on(async move {
        let writer_task = pool
            .writer_task_handle()
            .unwrap()
            .expect("writer task must be available now that a runtime exists");

        let (started_tx, started_rx) = tokio::sync::oneshot::channel::<()>();
        let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
        let occupier = {
            let writer_task = writer_task.clone();
            tokio::spawn(async move {
                writer_task
                    .send(move |_conn| {
                        let _ = started_tx.send(());
                        let _ = release_rx.blocking_recv();
                        Ok::<(), StorageError>(())
                    })
                    .await
            })
        };
        started_rx
            .await
            .expect("occupier must signal it has started running inside the writer task");
        assert_eq!(
            writer_task.queue_depth(),
            0,
            "channel must start empty once the occupier has been dequeued and is running"
        );

        let write_task = tokio::spawn(async move {
            store
                .upsert_document(make_document(Uuid::new_v4(), "outside-runtime", "body"))
                .await
        });

        let mut saw_enqueued = false;
        for _ in 0..100 {
            if writer_task.queue_depth() >= 1 {
                saw_enqueued = true;
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(5)).await;
        }
        assert!(
            saw_enqueued,
            "upsert_document's write request never appeared in the writer task's channel \
             while the occupier held the single drain slot — a store built outside a \
             runtime is not re-checking writer-task availability at write time"
        );

        release_tx
            .send(())
            .expect("occupier must still be waiting on the release signal");
        occupier
            .await
            .expect("occupier task must not panic")
            .expect("occupier write must succeed");
        write_task
            .await
            .expect("write task must not panic")
            .expect("upsert_document must succeed once unblocked");
    });
}

/// #1907: memory recall's lexical work must scale with the memory corpus, not
/// with unrelated notes that happen to match the same common query term.
#[test]
fn memory_kind_match_work_is_bounded_by_memory_corpus() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use rusqlite::functions::FunctionFlags;

    fn measure(noise_rows: usize) -> (usize, usize, String) {
        let conn = rusqlite::Connection::open_in_memory().expect("in-memory SQLite");
        conn.execute_batch(
            "CREATE VIRTUAL TABLE fts_notes USING fts5(\
             subject_id UNINDEXED, \
             kind UNINDEXED, \
             title, \
             body, \
             tags UNINDEXED, \
             namespace UNINDEXED, \
             metadata UNINDEXED, \
             updated_at UNINDEXED, \
             record_kind, \
             tokenize = 'trigram'\
             )",
        )
        .expect("production-shaped trigram table");
        conn.execute_batch(&rowid_map_ddl("fts_notes"))
            .expect("production-shaped rowid map");

        conn.execute_batch("BEGIN").expect("begin seed");
        {
            let mut insert = conn
                .prepare(
                    "INSERT INTO fts_notes \
                    (subject_id, kind, title, body, tags, namespace, metadata, updated_at, record_kind) \
                     VALUES (?1, 'note', '', 'common recall token', '[]', 'local', NULL, 0, ?2)",
                )
                .expect("prepare seed insert");
            for i in 0..noise_rows {
                insert
                    .execute(rusqlite::params![format!("noise-{i}"), "message"])
                    .expect("insert non-memory note");
            }
            for i in 0..50 {
                insert
                    .execute(rusqlite::params![format!("memory-{i}"), "memory"])
                    .expect("insert memory note");
            }
        }
        conn.execute_batch("COMMIT").expect("commit seed");

        let visits = std::sync::Arc::new(AtomicUsize::new(0));
        let visits_for_fn = std::sync::Arc::clone(&visits);
        conn.create_scalar_function(
            "visit_memory_kind",
            1,
            FunctionFlags::SQLITE_UTF8,
            move |ctx| {
                visits_for_fn.fetch_add(1, Ordering::Relaxed);
                Ok(i64::from(ctx.get::<String>(0)? == "memory"))
            },
        )
        .expect("register visit counter");

        let filter = TextFilter {
            record_kinds: vec!["memory".to_string()],
            ..TextFilter::default()
        };
        let match_expr = build_filtered_match_expr("common", TextQueryMode::Plain, Some(&filter))
            .expect("filtered MATCH expression");
        assert!(
            match_expr.contains("record_kind : \"memory\""),
            "granular kind must be part of MATCH, got {match_expr:?}"
        );
        let sql = format!(
            "SELECT subject_id FROM fts_notes \
             WHERE fts_notes MATCH ?1 \
             AND rank MATCH '{LEXICAL_BM25_RANK}' \
             AND visit_memory_kind(record_kind) = 1 \
             ORDER BY rank LIMIT 20"
        );
        let plan = conn
            .prepare(&format!("EXPLAIN QUERY PLAN {sql}"))
            .expect("prepare explain")
            .query_map([&match_expr], |row| row.get::<_, String>(3))
            .expect("query explain")
            .collect::<Result<Vec<_>, _>>()
            .expect("collect explain")
            .join("\n");
        let hits = conn
            .prepare(&sql)
            .expect("prepare measured query")
            .query_map([&match_expr], |row| row.get::<_, String>(0))
            .expect("run measured query")
            .collect::<Result<Vec<_>, _>>()
            .expect("collect measured hits");

        (hits.len(), visits.load(Ordering::Relaxed), plan)
    }

    let (small_hits, small_visits, small_plan) = measure(200);
    let (large_hits, large_visits, large_plan) = measure(2_000);
    assert_eq!(small_hits, 20);
    assert_eq!(large_hits, 20);
    assert_eq!(
        small_visits, 20,
        "only the requested memory top-K is visited"
    );
    assert_eq!(large_visits, 20, "unrelated notes must add no visits");
    assert!(small_plan.contains("VIRTUAL TABLE"), "{small_plan}");
    assert!(large_plan.contains("VIRTUAL TABLE"), "{large_plan}");
    assert!(
        large_visits < small_visits.saturating_mul(3),
        "memory query scanned the unrelated note corpus: {small_visits} candidate visits \
         with 200 noise rows versus {large_visits} with 2,000 noise rows\n\
         small plan:\n{small_plan}\nlarge plan:\n{large_plan}"
    );
}