khive-pack-knowledge 0.9.0

Knowledge verb pack — lore corpus (atoms/domains), TF-IDF retrieval, concept registration
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
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
//! Search, suggest, and compose handlers.
//!
//! TF-IDF scoring primitives live in `super::scoring`; this module owns the
//! FTS/ANN pipeline, reranking, hydration, and handler dispatch.

use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

use serde_json::{json, Value};
use uuid::Uuid;

use khive_runtime::{
    hex_prefix_to_uuid_pattern, KhiveRuntime, Namespace, NamespaceToken, RuntimeError,
};
use khive_score::DeterministicScore;
use khive_storage::types::{PageRequest, SqlStatement, SqlValue};
use khive_storage::EntityFilter;

use super::lexical_timeout::{
    LexicalBound, LexicalPass, LexicalPhase, LexicalStage, LexicalTimeout,
};
use super::matching;
use super::schema::{Atom, ComposeParams, Domain, SearchParams, SuggestParams};
use super::scoring::{
    compute_idf, exact_name_bonus, expand_terms, load_candidates_from_atoms, score_candidate,
    Candidate, Weights,
};
use super::sections::to_slug;
use super::util::{
    atom_embed_text, atom_from_row, deser, domain_from_row, estimate_compose_item_tokens,
    explicitly_requested_status, is_stop, row_bool, row_i64, row_str, sql_err, status_multiplier,
    status_sql_clause, status_values, CANDIDATE_POOL, CHARS_PER_TOKEN, D_SUGGEST_RERANK_ALPHA,
    MIN_TERM_LEN,
};
use super::vamana;
use super::KnowledgeHandlers;

// ─── scored hit (internal) ────────────────────────────────────────────────────

#[derive(Clone)]
struct ScoredHit {
    id: String,
    slug: String,
    name: String,
    content: Option<String>,
    tags: Option<String>,
    finalized: bool,
    is_domain: bool,
    status: Option<String>,
    score: f32,
    provenance: ScoreProvenance,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ScoreProvenance {
    lexical: bool,
    ann: bool,
    embedding_rerank: bool,
}

impl ScoreProvenance {
    const fn lexical() -> Self {
        Self {
            lexical: true,
            ann: false,
            embedding_rerank: false,
        }
    }

    const fn ann() -> Self {
        Self {
            lexical: false,
            ann: true,
            embedding_rerank: false,
        }
    }

    fn merge_sources(&mut self, other: Self) {
        self.lexical |= other.lexical;
        self.ann |= other.ann;
        self.embedding_rerank |= other.embedding_rerank;
    }

    fn to_json(self) -> Value {
        let mut sources = Vec::with_capacity(2);
        if self.lexical {
            sources.push("lexical");
        }
        if self.ann {
            sources.push("ann");
        }
        json!({
            "sources": sources,
            "embedding_rerank": self.embedding_rerank,
            "normalization": "s_over_s_plus_1",
            "calibrated": false,
        })
    }
}

fn candidate_fallback(hits: &[ScoredHit]) -> &'static str {
    if hits.iter().any(|hit| hit.provenance.ann) && !hits.iter().any(|hit| hit.provenance.lexical) {
        "ann"
    } else {
        "none"
    }
}

enum AnnAvailability {
    Ready,
    WarmingTimedOut { corpus_non_empty: bool },
    Absent,
}

struct AnnSearchState {
    hits: Vec<(Uuid, f32)>,
    availability: AnnAvailability,
    /// Whether the ANN source itself returned fewer than `k` entries.
    /// Fresh-tail deletes may shrink `hits` afterward without proving that
    /// deeper ANN candidates do not exist.
    source_exhausted: bool,
}

struct FreshTailSearchState {
    hits: Vec<(Uuid, f32)>,
    source_exhausted: bool,
}

async fn merge_fresh_tail_for_search(
    runtime: &KhiveRuntime,
    ann: &vamana::SharedAnn,
    key: &vamana::AnnKey,
    query_embedding: &[f32],
    k: usize,
    loaded: Option<(Vec<(Uuid, f32)>, u64)>,
) -> FreshTailSearchState {
    let (candidates, watermark, source_exhausted) = match loaded {
        Some((candidates, watermark)) => {
            let source_exhausted = candidates.len() < k;
            (candidates, Some(watermark), source_exhausted)
        }
        None => (Vec::new(), None, true),
    };
    match vamana::fresh_tail_leg(runtime, ann, key, query_embedding, k, watermark).await {
        vamana::FreshTailOutcome::Ops(ops) => FreshTailSearchState {
            hits: vamana::merge_fresh_tail_off_thread(candidates, query_embedding, ops).await,
            source_exhausted,
        },
        vamana::FreshTailOutcome::Replace {
            candidates,
            source_exhausted,
        } => FreshTailSearchState {
            hits: candidates,
            source_exhausted,
        },
        vamana::FreshTailOutcome::Skipped => FreshTailSearchState {
            hits: candidates,
            source_exhausted,
        },
    }
}

/// Search the loaded ANN slot, waiting a bounded time when its warm is in flight.
async fn search_ann_with_warm_wait(
    runtime: &KhiveRuntime,
    token: &NamespaceToken,
    ann: &vamana::SharedAnn,
    key: &vamana::AnnKey,
    query_embedding: &[f32],
    k: usize,
) -> AnnSearchState {
    if let Some(loaded) = vamana::search_loaded_with_seq(ann, key, query_embedding, k).await {
        let tail =
            merge_fresh_tail_for_search(runtime, ann, key, query_embedding, k, Some(loaded)).await;
        return AnnSearchState {
            hits: tail.hits,
            availability: AnnAvailability::Ready,
            source_exhausted: tail.source_exhausted,
        };
    }
    if !vamana::is_warming_not_loaded(ann, key) {
        let tail = merge_fresh_tail_for_search(runtime, ann, key, query_embedding, k, None).await;
        return AnnSearchState {
            hits: tail.hits,
            availability: AnnAvailability::Absent,
            source_exhausted: tail.source_exhausted,
        };
    }
    if vamana::wait_ready(
        ann,
        key,
        vamana::warm_wait_timeout_ms(),
        vamana::ANN_WARM_WAIT_POLL_MS,
    )
    .await
    {
        let loaded = vamana::search_loaded_with_seq(ann, key, query_embedding, k).await;
        let availability = if loaded.is_some() {
            AnnAvailability::Ready
        } else {
            AnnAvailability::Absent
        };
        let tail = merge_fresh_tail_for_search(runtime, ann, key, query_embedding, k, loaded).await;
        return AnnSearchState {
            hits: tail.hits,
            availability,
            source_exhausted: tail.source_exhausted,
        };
    }

    let corpus_non_empty =
        vamana::compute_fingerprint(runtime, token, runtime.default_embedder_name())
            .await
            .map(|fingerprint| fingerprint.vector_count > 0)
            .unwrap_or(false);
    let tail = merge_fresh_tail_for_search(runtime, ann, key, query_embedding, k, None).await;
    AnnSearchState {
        hits: tail.hits,
        availability: AnnAvailability::WarmingTimedOut { corpus_non_empty },
        source_exhausted: tail.source_exhausted,
    }
}

// ─── ANN fusion (symmetric RRF) ─────────────────────────────────────────────

const RRF_K: usize = 60;

fn normalize_rrf_score(raw: f32, source_count: usize, k: usize) -> f32 {
    if source_count == 0 {
        return 0.0;
    }
    let theoretical_max = source_count as f32 / (k as f32 + 1.0);
    (raw / theoretical_max).clamp(0.0, 1.0)
}

fn fuse_ann_hits(fts_hits: &mut Vec<ScoredHit>, ann_hits: &[ScoredHit], min_score: f32) {
    let drained: Vec<ScoredHit> = std::mem::take(fts_hits);

    let fts_source: Vec<(String, DeterministicScore)> = drained
        .iter()
        .map(|hit| (hit.id.clone(), DeterministicScore::from_f32(hit.score)))
        .collect();
    let mut by_id: HashMap<String, ScoredHit> = drained
        .into_iter()
        .map(|hit| (hit.id.clone(), hit))
        .collect();
    let ann_source: Vec<(String, DeterministicScore)> = ann_hits
        .iter()
        .map(|hit| (hit.id.clone(), DeterministicScore::from_f32(hit.score)))
        .collect();
    for hit in ann_hits {
        by_id
            .entry(hit.id.clone())
            .and_modify(|existing| existing.provenance.merge_sources(hit.provenance))
            .or_insert_with(|| hit.clone());
    }

    let source_count = usize::from(!fts_source.is_empty()) + usize::from(!ann_source.is_empty());
    let fused = khive_fusion::reciprocal_rank_fusion(vec![fts_source, ann_source], RRF_K);

    for (id, fused_score) in fused {
        let raw_score = fused_score.to_f64() as f32;
        let score = normalize_rrf_score(raw_score, source_count, RRF_K);
        if score < min_score {
            continue;
        }

        if let Some(mut hit) = by_id.remove(&id) {
            hit.score = score;
            fts_hits.push(hit);
        }
    }
}

// ─── status filtering (post-hydration) ───────────────────────────────────────

/// Remove hits whose `status` is in `exclude_statuses` after hydration.
fn filter_by_excluded_statuses(hits: &mut Vec<ScoredHit>, exclude_statuses: &[&str]) {
    if exclude_statuses.is_empty() {
        return;
    }
    hits.retain(|hit| {
        let status = hit.status.as_deref().unwrap_or("");
        !exclude_statuses.contains(&status)
    });
}

/// Apply the complete public status contract to hydrated hits.
///
/// An explicit `status=` is an allowlist, not merely a request to disable the
/// default exclusions. This distinction is load-bearing for ANN candidates,
/// which do not pass through the FTS SQL predicate.
fn filter_hits_by_status(
    hits: &mut Vec<ScoredHit>,
    statuses: &[String],
    exclude_statuses: &[&str],
) {
    if statuses.is_empty() {
        filter_by_excluded_statuses(hits, exclude_statuses);
        return;
    }

    hits.retain(|hit| {
        hit.status
            .as_deref()
            .is_some_and(|status| statuses.iter().any(|allowed| allowed == status))
    });
}

fn deprecated_allowed_by_status_policy(statuses: &[String], exclude_statuses: &[&str]) -> bool {
    if statuses.is_empty() {
        !exclude_statuses.contains(&"deprecated")
    } else {
        explicitly_requested_status(statuses, "deprecated")
    }
}

// ─── type filtering (post-hydration) ─────────────────────────────────────────

/// Remove hits that do not match `type_filter` after hydration.
///
/// Mirrors eligibility in the FTS/SQL path in `fetch_fts_candidates`:
///
/// - `Some("domain")` keeps only domain hits (`hit.is_domain == true`).
/// - `Some(other)` where other is non-empty keeps only non-domain hits.
/// - `None` or `Some("")` is a no-op.
///
/// Applied to hydrated ANN candidates before fusion/refill and again to the
/// fused pool as a final shared-source guard.
fn filter_hits_by_type(hits: &mut Vec<ScoredHit>, type_filter: Option<&str>) {
    let filt = match type_filter {
        Some(f) if !f.is_empty() => f,
        _ => return,
    };
    let want_domain = filt == "domain";
    hits.retain(|hit| {
        if want_domain {
            hit.is_domain
        } else {
            !hit.is_domain
        }
    });
}

// ─── status scoring ───────────────────────────────────────────────────────────

fn apply_status_multipliers(hits: &mut Vec<ScoredHit>, include_deprecated: bool) {
    hits.retain_mut(|hit| {
        let multiplier = status_multiplier(hit.status.as_deref());
        // Squash raw score to (0,1) via monotonic s/(s+1) before applying the status
        // multiplier so that TF-IDF scores > 1 don't saturate ranking. RRF-normalized
        // scores (already ≤ 1) are squashed at most to 0.5, preserving relative order.
        hit.score = (hit.score / (hit.score + 1.0) * multiplier).clamp(0.0, 1.0);
        include_deprecated || multiplier > 0.0
    });
    hits.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.slug.cmp(&b.slug))
    });
}

/// Re-applies `min_score` after [`apply_status_multipliers`] so it is a genuine
/// floor on the scores returned to the caller.
///
/// The fusion-stage application in `fuse_ann_hits` stays as an early admission
/// filter, but the multiplier step rewrites every surviving score via
/// `s / (s + 1)` (mapping 1.0 to 0.5), so a hit that cleared fusion can land
/// below the caller's floor. Filtering again here — after the rewrite, before
/// the `limit` truncation — guarantees every returned score is >= `min_score`;
/// returning fewer than `limit` hits when the floor removes some is correct.
fn enforce_min_score_floor(hits: &mut Vec<ScoredHit>, min_score: f32) {
    hits.retain(|hit| hit.score >= min_score);
}

// ─── FTS5 candidate expression ───────────────────────────────────────────────

fn quote_fts5_phrase(raw_query: &str) -> String {
    let escaped = raw_query.replace('"', "\"\"");
    format!("\"{escaped}\"")
}

/// Build the per-term FTS5 match clauses the candidate fetch runs bounded
/// subqueries over — one quoted phrase per de-duplicated, non-stop, expanded
/// term. Queries with no scoreable term fall back to the exact raw phrase.
///
/// FTS is only the candidate generator; TF-IDF remains the ranker. Requiring
/// the whole raw query as one phrase drops candidates whose matching terms are
/// separated in the document; per-term clauses keep those non-contiguous
/// matches reachable for the scorer to judge.
fn fts5_candidate_terms(raw_query: &str) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut terms: Vec<String> = matching::tokenize_field(raw_query)
        .into_iter()
        .filter(|term| term.len() >= MIN_TERM_LEN && !is_stop(term))
        .filter(|term| seen.insert(term.clone()))
        .collect();

    if terms.is_empty() {
        vec![quote_fts5_phrase(raw_query)]
    } else {
        // Candidate recall observes the same singular/plural expansion as the
        // scorer. The returned set is used by IDF weighting later; expansion's
        // mutation of `terms` is the only result needed here.
        let _ = expand_terms(&mut terms);
        terms.iter().map(|term| quote_fts5_phrase(term)).collect()
    }
}

/// SQL eligibility predicate for the public atom/domain kind filter.
///
/// Domain mirrors are atoms carrying the exact `type:domain` tag. Applying
/// this predicate in FTS hydration and recovery is load-bearing: filtering after
/// `LIMIT` lets the wrong kind consume every candidate slot.
fn type_eligibility_sql(type_filter: Option<&str>, atom_alias: &str) -> String {
    match type_filter {
        Some("domain") => format!(" AND {atom_alias}.tags LIKE '%\"type:domain\"%'"),
        Some(filter) if !filter.is_empty() => {
            format!(" AND {atom_alias}.tags NOT LIKE '%\"type:domain\"%'")
        }
        _ => String::new(),
    }
}

// ─── FTS5 candidate pool fetch ────────────────────────────────────────────────

/// Per-term candidate cap. FTS enumerates in rowid order and stops at the
/// limit; application TF-IDF scoring ranks only the admitted candidates.
const FTS_TERM_LIMIT: usize = 500;

/// Shared by the full query and both decomposed passes. Admission happens
/// before rarity probes; every later stage reuses that admitted term set.
const FTS_TERM_COUNT_LIMIT: usize = 32;

struct FtsTermBudget {
    remaining: AtomicUsize,
    truncated: AtomicBool,
}

impl FtsTermBudget {
    fn new() -> Self {
        Self {
            remaining: AtomicUsize::new(FTS_TERM_COUNT_LIMIT),
            truncated: AtomicBool::new(false),
        }
    }

    fn admit(&self, mut terms: Vec<String>) -> Vec<String> {
        let remaining = self
            .remaining
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| {
                Some(remaining.saturating_sub(terms.len()))
            })
            .expect("term reservation always succeeds");
        if terms.len() > remaining {
            self.truncated.store(true, Ordering::Relaxed);
            terms.truncate(remaining);
        }
        terms
    }

    fn truncated(&self) -> bool {
        self.truncated.load(Ordering::Relaxed)
    }

    /// Count only terms this pass can actually admit. Decomposed passes share
    /// the request allowance, so a pass after exhaustion must not acquire a
    /// larger deadline just because its raw query contains many terms.
    fn available_for(&self, raw_query: &str) -> usize {
        fts5_candidate_terms(raw_query)
            .len()
            .min(self.remaining.load(Ordering::Relaxed))
    }
}

fn phase_a_rowids_statement(term: &str, limit: usize) -> SqlStatement {
    SqlStatement {
        sql: "SELECT rowid FROM fts_knowledge WHERE fts_knowledge MATCH ?1 \
              ORDER BY rowid LIMIT ?2"
            .into(),
        params: vec![SqlValue::Text(term.into()), SqlValue::Integer(limit as i64)],
        label: Some("knowledge.fts_rowids".into()),
    }
}

fn term_frequency_statement(term: &str) -> SqlStatement {
    SqlStatement {
        sql: "SELECT count(*) AS frequency FROM ( \
                  SELECT rowid FROM fts_knowledge WHERE fts_knowledge MATCH ?1 \
                  ORDER BY rowid LIMIT ?2 \
              )"
        .into(),
        params: vec![
            SqlValue::Text(term.into()),
            SqlValue::Integer((FTS_TERM_LIMIT + 1) as i64),
        ],
        label: Some("knowledge.fts_term_frequency".into()),
    }
}

async fn rarest_fts_terms_first(
    reader: &mut dyn khive_storage::SqlReader,
    terms: Vec<String>,
    stage: &mut LexicalStage,
) -> Result<Vec<String>, khive_storage::StorageError> {
    let mut frequencies = Vec::with_capacity(terms.len());
    // The index has exactly one reader, the `cfg(test)` seam at the bottom of
    // this loop, so in a non-test build it genuinely has none and clippy says
    // so. The exemption is scoped to that configuration rather than written as
    // a bare allow, and the alternatives were both worse: a hand-rolled counter
    // is an unused assignment in a non-test build and an explicit counter loop
    // in a test one, and dropping the index removes the seam.
    #[cfg_attr(not(test), allow(clippy::unused_enumerate_index))]
    for (_probe_index, term) in terms.into_iter().enumerate() {
        // Count only a bounded index prefix. Rare counts are exact; terms
        // above the cap tie by spelling, without scanning their whole lists.
        // Aggregating inside SQLite avoids materializing up to 501 owned
        // SqlRows just to discard their rowids and count them in Rust.
        let rows = stage
            .read_bounded(
                LexicalPhase::TermFrequency,
                LexicalBound::OrderingProbe,
                // The caller scoped this same budget as the read deadline;
                // both sides call `rarity_probe_budget()` so they cannot
                // disagree, and recording it here is what lets the timeout
                // record name the 500 ms that governed the read instead of
                // the stage's 2000 ms (issue #2879).
                rarity_probe_budget(),
                reader.query_all(term_frequency_statement(&term)),
            )
            .await?;
        let frequency = rows
            .first()
            .and_then(|row| row_i64(row, "frequency"))
            .ok_or_else(|| khive_storage::StorageError::Serialization {
                capability: khive_storage::StorageCapability::Sql,
                message: "term frequency probe returned no integer count".into(),
            })?;
        if frequency > 0 {
            frequencies.push((term, frequency));
        }
        #[cfg(test)]
        advance_fts_test_probe_deadline_after_term(_probe_index + 1).await;
    }
    frequencies
        .sort_unstable_by(|(a, a_count), (b, b_count)| a_count.cmp(b_count).then_with(|| a.cmp(b)));
    Ok(frequencies.into_iter().map(|(term, _)| term).collect())
}

/// Overfetch factor applied to a term's phase-A rowid window when phase B has
/// an eligibility predicate (status or type) that can reject rows phase A had
/// no way to see (issue #1930 Amendment 2 — see [`fetch_fts_candidates`]).
/// Phase A carries no eligibility predicate at all, so without headroom an
/// ineligible-heavy match set could starve phase B down to nothing even
/// though eligible rows exist further down the rowid sequence.
const PHASE_A_OVERFETCH_FACTOR: usize = 4;

/// Ceiling a single term's phase-A probe window is allowed to widen to
/// (issue #1930 Amendment 2). Bounds the worst case — every phase-A row
/// ineligible, and the corpus large enough to keep returning full pages — to
/// a fixed per-term cost instead of an unbounded retry loop.
const PHASE_A_WIDEN_CEILING: usize = 8000;

/// Independent read-deadline budget for the lexical/FTS candidate fetch
/// (issue #1930 Amendment 2). `khive_storage::scope_request_read_deadline`
/// keeps whichever deadline is earlier, so nesting this around just the
/// fetch only ever *tightens* its effective deadline; popping back out of
/// the scope once the fetch returns restores the wider request deadline for
/// every stage that runs after it (rerank, body-line counts, member
/// sizing). A lexical-stage timeout therefore no longer means the request
/// itself is out of time — only that this one stage's own budget is.
pub(crate) const LEXICAL_STAGE_BUDGET_MS: u64 = 2_000;

/// The fixed 2 s stage allowance leaves the same time for one or many
/// sequential bounded term reads. Give each additional admitted term one
/// quarter of the base budget, capped at 4x for a pass. The request's outer
/// read deadline remains authoritative (normally 30 s), and the 32-term
/// request-wide admission bound still limits actual FTS work.
const LEXICAL_STAGE_EXTRA_TERM_QUARTERS: usize = 12;

fn lexical_stage_budget_for_terms(
    base: std::time::Duration,
    admitted_terms: usize,
) -> std::time::Duration {
    let quarters = 4 + admitted_terms
        .saturating_sub(1)
        .min(LEXICAL_STAGE_EXTRA_TERM_QUARTERS);
    base.saturating_mul(quarters as u32) / 4
}

/// Share of the base lexical budget the rarity probe may spend before it is
/// cut off and the terms are used in the order they arrived. Multi-term
/// candidate fetches gain time; the optional ordering probe does not.
///
/// `rarest_fts_terms_first` fetches no candidates. It issues one bounded
/// `count(*)` per term, sequentially, and its entire product is an ORDERING of
/// the terms the real fetch then queries. Before this bound existed it ran
/// against the whole stage budget, and on a production corpus a five-to-seven
/// term query spent all 2000 ms in it — after which the caller returned an
/// empty candidate list for a stage that had not yet asked for a candidate
/// (issue #2766). An optimization must not be able to consume the budget of
/// the work it optimizes, and its expiry must degrade to the unoptimized path
/// rather than to no path.
///
/// A quarter, rather than a half or a tenth, for two reasons stated so a later
/// change has something to argue against. The probe's value is largest on the
/// first few terms (querying the rarest term first is what bounds the rowid
/// window the later terms widen) and falls off across the tail, so it does not
/// need most of the budget to deliver most of its benefit. And the fetch it
/// precedes is the part that can return nothing useful when it is short of
/// time, so the remainder belongs to the fetch.
const RARITY_PROBE_BUDGET_NUMERATOR: u32 = 1;
const RARITY_PROBE_BUDGET_DENOMINATOR: u32 = 4;

/// The rarity probe's own deadline, derived from the base budget in force
/// (including the test override) rather than from a second constant that
/// could drift away from it.
fn rarity_probe_budget() -> std::time::Duration {
    lexical_stage_budget() / RARITY_PROBE_BUDGET_DENOMINATOR * RARITY_PROBE_BUDGET_NUMERATOR
}

// ── Test-only seam: override the lexical-stage budget and the phase-A widen
// ceiling ──────────────────────────────────────────────────────────────────
//
// Both overrides ride the same request-scoped `tokio::task_local!` mechanism
// `khive_storage::scope_request_read_deadline` already uses for the read
// deadline (issue #2396 fix 4). A task-local override is visible only to the
// task it is scoped around, so two tests running concurrently under Cargo's
// parallel runner can never observe each other's override the way the prior
// process-global `AtomicU64` could — there is nothing shared left to reset
// on drop or serialize with a mutex.
tokio::task_local! {
    static LEXICAL_STAGE_BUDGET_OVERRIDE_MS: u64;
    static PHASE_A_WIDEN_CEILING_OVERRIDE: usize;
}

#[cfg(test)]
tokio::task_local! {
    // Expire only sizing after ANN and lexical candidate work has finished.
    static MEMBER_SIZING_READ_TIMEOUT: ();
}

#[cfg(test)]
pub(crate) async fn with_member_sizing_read_timeout<F: std::future::Future>(
    future: F,
) -> F::Output {
    MEMBER_SIZING_READ_TIMEOUT.scope((), future).await
}

fn lexical_stage_budget() -> std::time::Duration {
    let ms = LEXICAL_STAGE_BUDGET_OVERRIDE_MS
        .try_with(|ms| *ms)
        .unwrap_or(LEXICAL_STAGE_BUDGET_MS);
    std::time::Duration::from_millis(ms)
}

fn phase_a_widen_ceiling() -> usize {
    PHASE_A_WIDEN_CEILING_OVERRIDE
        .try_with(|ceiling| *ceiling)
        .unwrap_or(PHASE_A_WIDEN_CEILING)
}

/// Scope `future` to a lexical-stage budget override, so a test can force a
/// controlled deadline instead of depending on a real multi-second wall-clock
/// wait against the production default (mirrors `vamana::warm_wait_timeout_ms`'s
/// override seam). `pub(crate)` (not scoped to `mod tests` below) so the
/// handler-level degrade tests in `ann_degrade_tests.rs` can reuse it.
#[cfg(test)]
pub(crate) async fn with_lexical_stage_budget_override_ms<F>(ms: u64, future: F) -> F::Output
where
    F: std::future::Future,
{
    LEXICAL_STAGE_BUDGET_OVERRIDE_MS.scope(ms, future).await
}

/// Scope `future` to a phase-A widen-ceiling override, so a test can shrink
/// the ceiling far below `PHASE_A_WIDEN_CEILING` and reach the ceiling-
/// exhaustion fallback (fix 2) with a small fixture.
#[cfg(test)]
pub(crate) async fn with_phase_a_widen_ceiling_override<F>(ceiling: usize, future: F) -> F::Output
where
    F: std::future::Future,
{
    PHASE_A_WIDEN_CEILING_OVERRIDE.scope(ceiling, future).await
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LexicalCandidateState {
    Matched,
    ExactName,
    NoMatch,
    Filtered,
    PartialTimeout,
    TimedOut,
}

impl LexicalCandidateState {
    fn as_str(self) -> &'static str {
        match self {
            Self::Matched => "matched",
            Self::ExactName => "exact_name",
            Self::NoMatch => "no_match",
            Self::Filtered => "filtered",
            Self::PartialTimeout => "partial_timeout",
            Self::TimedOut => "timed_out",
        }
    }

    fn merge(states: &[Self]) -> Self {
        let timed_out = states
            .iter()
            .filter(|&&state| state == Self::TimedOut)
            .count();
        if !states.is_empty() && timed_out == states.len() {
            Self::TimedOut
        } else if timed_out > 0 || states.contains(&Self::PartialTimeout) {
            Self::PartialTimeout
        } else if states.contains(&Self::Matched) {
            Self::Matched
        } else if states.contains(&Self::ExactName) {
            Self::ExactName
        } else if states.contains(&Self::Filtered) {
            Self::Filtered
        } else {
            Self::NoMatch
        }
    }
}

/// Outcome of the bounded lexical candidate fetch.
///
/// `timeout` is set only for [`khive_storage::StorageError::Timeout`]. Any other storage error
/// (including a genuine FTS5 syntax/parser error) still surfaces as an `Err`;
/// fail-open applies to a timeout only.
struct FtsFetchOutcome {
    atoms: Vec<Atom>,
    timeout: Option<LexicalTimeout>,
    state: LexicalCandidateState,
}

#[cfg(test)]
#[derive(Clone, Copy)]
struct FtsTestDeadlineAdvance {
    after_completed_terms: usize,
    by: std::time::Duration,
}

#[cfg(test)]
tokio::task_local! {
    static FTS_TEST_DEADLINE_ADVANCE: FtsTestDeadlineAdvance;
}

#[cfg(test)]
async fn advance_fts_test_deadline_after_term(completed_terms: usize) {
    let advance_by = FTS_TEST_DEADLINE_ADVANCE
        .try_with(|control| {
            (completed_terms == control.after_completed_terms).then_some(control.by)
        })
        .ok()
        .flatten();
    if let Some(advance_by) = advance_by {
        tokio::time::advance(advance_by).await;
    }
}

#[cfg(test)]
tokio::task_local! {
    static FTS_TEST_PROBE_DEADLINE_ADVANCE: FtsTestDeadlineAdvance;
}

/// Sibling of [`advance_fts_test_deadline_after_term`] for the rarity probe.
/// A SEPARATE task-local, not a shared counter: the probe loop and the
/// per-term fetch loop are different boundaries, and a test that wants the
/// probe to expire must not also move the fetch's clock.
#[cfg(test)]
async fn advance_fts_test_probe_deadline_after_term(completed_terms: usize) {
    let advance_by = FTS_TEST_PROBE_DEADLINE_ADVANCE
        .try_with(|control| {
            (completed_terms == control.after_completed_terms).then_some(control.by)
        })
        .ok()
        .flatten();
    if let Some(advance_by) = advance_by {
        tokio::time::advance(advance_by).await;
    }
}

#[cfg(test)]
pub(crate) async fn with_fts_probe_deadline_advance_after_term<F>(
    after_completed_terms: usize,
    by: std::time::Duration,
    future: F,
) -> F::Output
where
    F: std::future::Future,
{
    FTS_TEST_PROBE_DEADLINE_ADVANCE
        .scope(
            FtsTestDeadlineAdvance {
                after_completed_terms,
                by,
            },
            future,
        )
        .await
}

#[cfg(test)]
pub(crate) async fn with_fts_deadline_advance_after_term<F>(
    after_completed_terms: usize,
    by: std::time::Duration,
    future: F,
) -> F::Output
where
    F: std::future::Future,
{
    FTS_TEST_DEADLINE_ADVANCE
        .scope(
            FtsTestDeadlineAdvance {
                after_completed_terms,
                by,
            },
            future,
        )
        .await
}

fn is_timeout(e: &khive_storage::StorageError) -> bool {
    matches!(e, khive_storage::StorageError::Timeout { .. })
}

/// Same check, for the `RuntimeError` shape `?`-propagated storage timeouts
/// arrive in at the handler layer.
fn is_read_timeout(e: &RuntimeError) -> bool {
    matches!(
        e,
        RuntimeError::Storage(khive_storage::StorageError::Timeout { .. })
    )
}

/// Fetch a bounded lexical candidate pool.
///
/// Two-phase per term (issue #1930 Amendment 2). The original shape ordered
/// a full atom row — `content` included — per FTS5 match *before* its own
/// per-term `LIMIT`, so every match paid a scattered read against the whole
/// (potentially multi-gigabyte) atom table even though only the top few
/// hundred survived. Phase A instead enumerates bare rowids straight off
/// the `fts_knowledge` index, stopping before scoring the full match set;
/// phase B hydrates just the surviving
/// rowids from `knowledge_atoms` in chunks, applying namespace, soft-delete,
/// status, and type eligibility there.
///
/// Phase A carries no namespace predicate. `fts_knowledge.namespace` is
/// UNINDEXED on this external-content FTS5 table, so filtering on it (as the
/// original single query did) forces FTS5 to fetch the backing content row
/// per candidate — exactly the cost phase A exists to avoid. The namespace
/// check moves entirely to phase B, where the atom row is already being
/// read for its other eligibility columns. Overfetch and the scoped ceiling
/// fallback recover eligible rows beyond an ineligible prefix.
///
/// Phase A also drops the `a.slug` tie-break the old query used: `rowid` is
/// already stable and needs no join. `ORDER BY rowid` is consumed by FTS5,
/// so LIMIT can stop enumeration without a temporary full-match sort.
///
/// Replaces a single `ORDER BY bm25(...)` over one OR-joined match expression
/// (whose cost scales with the size of the entire match set — the #1930 read
/// timeout at ~94K atoms) with one bounded, independently-capped subquery per
/// term, unioned and deduplicated in application code. FTS remains only the
/// candidate generator; TF-IDF in `search_core` remains the ranker, so the
/// per-term merge order does not need to be a globally correct bm25 rank.
#[allow(clippy::too_many_arguments)]
async fn fetch_fts_candidates(
    runtime: &KhiveRuntime,
    ns: &str,
    raw_query: &str,
    type_filter: Option<&str>,
    statuses: &[String],
    exclude_statuses: &[&str],
    fetch_limit: usize,
    term_budget: &FtsTermBudget,
    mut stage: LexicalStage,
) -> Result<FtsFetchOutcome, RuntimeError> {
    let mut terms = term_budget.admit(fts5_candidate_terms(raw_query));
    if terms.is_empty() {
        return Ok(FtsFetchOutcome {
            atoms: Vec::new(),
            timeout: None,
            state: LexicalCandidateState::NoMatch,
        });
    }
    let sql = runtime.sql();
    let reader = match stage.read(LexicalPhase::ReaderOpen, sql.reader()).await {
        Ok(reader) => reader,
        Err(e) if is_timeout(&e) => {
            return Ok(FtsFetchOutcome {
                atoms: Vec::new(),
                timeout: stage.timeout,
                state: LexicalCandidateState::TimedOut,
            });
        }
        Err(e) => return Err(sql_err("search fts reader", e)),
    };

    #[cfg(test)]
    let reader = tests::record_term_probes(reader);
    let mut reader = reader;
    let type_clause = type_eligibility_sql(type_filter, "a");
    let per_term_limit = if terms.len() == 1 {
        fetch_limit
    } else {
        fetch_limit.clamp(1, FTS_TERM_LIMIT)
    };
    // `status_sql_clause`'s no-filter case still excludes `deprecated`, so
    // this is currently always true; kept explicit (not assumed) so a future
    // change that *can* return an empty clause degrades to no-overfetch
    // instead of silently keeping an overfetch with nothing to absorb.
    let has_eligibility_clause = !status_sql_clause(statuses, exclude_statuses, 1)
        .0
        .is_empty()
        || !type_clause.is_empty();
    let widen_ceiling = phase_a_widen_ceiling();
    let base_probe_limit = if has_eligibility_clause {
        per_term_limit
            .saturating_mul(PHASE_A_OVERFETCH_FACTOR)
            .min(widen_ceiling)
    } else {
        per_term_limit
    };

    // Set when the ordering probe below is cut off by its own deadline. The
    // per-term fetch has `term_query_timed_out` for the same purpose; this is a
    // second, independent way for the stage to have degraded, and the classifier
    // at the bottom has to see both or an expired probe reads as a clean miss.
    let mut rarity_probe_timed_out = false;
    if terms.len() > 1 {
        // The probe runs under its OWN, tighter deadline nested inside the
        // stage's. `scope_request_read_deadline` keeps whichever deadline is
        // earlier and restores the wider one on the way out, so this bounds
        // the probe and leaves the rest of the stage budget to the fetch.
        //
        // On expiry the terms are used in the order the candidate list
        // produced them. That order is not the caller's word order:
        // `fts5_candidate_terms` runs `expand_terms`, which sorts, so the
        // fallback is lexicographic and two spellings of the same query fall
        // back identically. It is the unoptimized path, not a failure path:
        // the ordering is a hint about which term to query first, and every
        // term is queried either way. The recorded timeout still rides out on
        // `stage.timeout`, so the expiry is disclosed rather than swallowed --
        // but it is disclosed as `degraded.lexical_ordering_probe_timeout`,
        // NOT as `degraded.lexical_timeout`, which stays the flag for a
        // candidate fetch that was actually cut short. Reporting both under
        // one flag is what issue #2879 measured: on one serving process 86 of
        // 196 timeout records were this graceful fallback, every one of them
        // at 500-532 ms against a 2000 ms stage budget that had not expired,
        // wearing the same flag and the same wording as a real cut.
        let arrival_order = terms.clone();
        let probe_budget = rarity_probe_budget();
        let probed = khive_storage::scope_request_read_deadline(probe_budget, async {
            rarest_fts_terms_first(reader.as_mut(), terms, &mut stage).await
        })
        .await;
        terms = match probed {
            Ok(terms) => terms,
            Err(e) if is_timeout(&e) => {
                rarity_probe_timed_out = true;
                arrival_order
            }
            Err(e) => return Err(sql_err("search fts term frequency probe", e)),
        };
    }

    // Query every matching term rather than stopping once `combined` reaches
    // `fetch_limit` — an early break made pool membership depend on query
    // word order (a fast-filling early term could starve every later term
    // of a query at all). Each term's rows are collected independently and
    // merged round-robin below, so no single term can crowd out the rest.
    // Rarest-first scheduling preserves useful narrow matches if a later
    // common term exhausts the independent stage deadline.
    let mut per_term_rows: Vec<Vec<Atom>> = Vec::with_capacity(terms.len());
    // Retain phase-A rowids to distinguish filtered local matches from a miss
    // without another FTS query or an unscoped existence probe.
    let mut term_probe_rowids: Vec<Vec<i64>> = Vec::with_capacity(terms.len());
    let mut unexhausted_terms = Vec::new();
    let mut term_query_timed_out = false;

    'terms: for term in &terms {
        let mut probe_limit = base_probe_limit;

        let (mut eligible, probed_rowids, exhausted): (Vec<Atom>, Vec<i64>, bool) = loop {
            let phase_a_rows = match stage
                .read(
                    LexicalPhase::PhaseARowids,
                    reader.query_all(phase_a_rowids_statement(term, probe_limit)),
                )
                .await
            {
                Ok(rows) => rows,
                Err(e) if is_timeout(&e) => {
                    term_query_timed_out = true;
                    break 'terms;
                }
                Err(e) => return Err(sql_err("search fts phase-a query", e)),
            };
            let rowids: Vec<i64> = phase_a_rows
                .iter()
                .filter_map(|r| row_i64(r, "rowid"))
                .collect();
            let phase_a_full = rowids.len() >= probe_limit;
            if rowids.is_empty() {
                break (Vec::new(), rowids, true);
            }

            let mut atoms_by_rowid: HashMap<i64, Atom> = HashMap::with_capacity(rowids.len());
            for chunk in rowids.chunks(HYDRATION_ID_CHUNK) {
                let statement = phase_b_hydration_statement(
                    ns,
                    chunk,
                    statuses,
                    exclude_statuses,
                    type_clause.as_str(),
                );
                let rows = match stage
                    .read(LexicalPhase::PhaseBHydration, reader.query_all(statement))
                    .await
                {
                    Ok(rows) => rows,
                    Err(e) if is_timeout(&e) => {
                        term_query_timed_out = true;
                        break 'terms;
                    }
                    Err(e) => return Err(sql_err("search fts phase-b hydration", e)),
                };
                for row in &rows {
                    if let (Some(atom), Some(rowid)) = (atom_from_row(row), row_i64(row, "rowid")) {
                        atoms_by_rowid.insert(rowid, atom);
                    }
                }
            }

            // Reassemble in phase A's rowid order; ineligible rows or intervening deletes drop out.
            // The reads share no snapshot: an intervening edit hydrates current text,
            // which the lexical scorer uses even if it no longer matches the term.
            let eligible_now: Vec<Atom> = rowids
                .iter()
                .filter_map(|rowid| atoms_by_rowid.get(rowid).cloned())
                .collect();

            // Widen only when phase A itself was the bottleneck (it returned
            // a full page, meaning more matches may exist beyond this
            // probe) and only up to the ceiling; a term that is genuinely
            // exhausted (phase A returned less than it asked for) has
            // nothing more to gain from a wider probe.
            if has_eligibility_clause && eligible_now.len() < per_term_limit && phase_a_full {
                if probe_limit < widen_ceiling {
                    probe_limit = probe_limit
                        .saturating_mul(PHASE_A_OVERFETCH_FACTOR)
                        .min(widen_ceiling);
                    continue;
                }

                // Ceiling exhausted and still short: more than `widen_ceiling`
                // ineligible top-ranked rows could still be hiding an
                // eligible one further down the rowid sequence than phase A
                // ever probed. Pay once for the pre-#2396-shape eligibility-
                // scoped join, bounded to this term's own `per_term_limit`,
                // so the ceiling bounds cost without letting an ineligible-
                // heavy match set hide a real candidate (issue #2396 fix 2).
                let (scoped_status_clause, scoped_status_params) =
                    status_sql_clause(statuses, exclude_statuses, 4);
                let scoped_sql = format!(
                    "SELECT a.* FROM fts_knowledge \
                     CROSS JOIN knowledge_atoms AS a ON a.rowid = fts_knowledge.rowid \
                     WHERE fts_knowledge MATCH ?1 \
                       AND +a.namespace = ?2 \
                       AND a.deleted_at IS NULL{scoped_status_clause}{type_clause} \
                     ORDER BY fts_knowledge.rowid \
                     LIMIT ?3"
                );
                let mut scoped_params = vec![
                    SqlValue::Text(term.clone()),
                    SqlValue::Text(ns.to_owned()),
                    SqlValue::Integer(per_term_limit as i64),
                ];
                scoped_params.extend(scoped_status_params);
                let scoped_rows = match stage
                    .read(
                        LexicalPhase::EligibilityFallback,
                        reader.query_all(SqlStatement {
                            sql: scoped_sql,
                            params: scoped_params,
                            label: None,
                        }),
                    )
                    .await
                {
                    Ok(rows) => rows,
                    Err(e) if is_timeout(&e) => {
                        term_query_timed_out = true;
                        break 'terms;
                    }
                    Err(e) => {
                        return Err(sql_err("search fts eligibility-scoped ceiling fallback", e));
                    }
                };
                break (
                    scoped_rows.iter().filter_map(atom_from_row).collect(),
                    rowids,
                    false,
                );
            }
            break (eligible_now, rowids, !phase_a_full);
        };

        eligible.truncate(per_term_limit);
        per_term_rows.push(eligible);
        term_probe_rowids.push(probed_rowids);
        if !exhausted {
            unexhausted_terms.push(term.clone());
        }
        #[cfg(test)]
        advance_fts_test_deadline_after_term(per_term_rows.len()).await;
    }

    let mut seen_ids: HashSet<Uuid> = HashSet::new();
    let mut combined: Vec<Atom> = Vec::new();
    let max_term_rows = per_term_rows.iter().map(Vec::len).max().unwrap_or(0);
    'merge: for i in 0..max_term_rows {
        for term_rows in &per_term_rows {
            if combined.len() >= fetch_limit {
                break 'merge;
            }
            if let Some(atom) = term_rows.get(i) {
                if seen_ids.insert(atom.id) {
                    combined.push(atom.clone());
                }
            }
        }
    }

    // Either degradation lands here. A cut-off ordering probe with candidates in
    // hand is `PartialTimeout`, which is what issue #2766 asks for: the lexical
    // arm survives and the degradation is still reported. With no candidates it
    // is `TimedOut` exactly as a per-term expiry is, because the alternative is
    // for the classifier below to call it a clean local miss, and a miss and a
    // stage that ran out of time are the two answers a caller must be able to
    // tell apart.
    if term_query_timed_out || rarity_probe_timed_out {
        return Ok(FtsFetchOutcome {
            state: if combined.is_empty() {
                LexicalCandidateState::TimedOut
            } else {
                LexicalCandidateState::PartialTimeout
            },
            atoms: combined,
            timeout: stage.timeout,
        });
    }

    if !combined.is_empty() {
        return Ok(FtsFetchOutcome {
            atoms: combined,
            timeout: None,
            state: LexicalCandidateState::Matched,
        });
    }

    // Classify empty candidates using only namespace-scoped evidence. A match
    // in another tenant must remain indistinguishable from a true local miss.
    // Reuse the bounded phase-A windows; never browse unrelated recent rows.
    let mut probe_rowids: Vec<i64> = term_probe_rowids.into_iter().flatten().collect();
    probe_rowids.sort_unstable();
    probe_rowids.dedup();

    let mut namespace_has_match = false;
    for chunk in probe_rowids.chunks(HYDRATION_ID_CHUNK) {
        let placeholders = chunk
            .iter()
            .enumerate()
            .map(|(i, _)| format!("?{}", i + 2))
            .collect::<Vec<_>>()
            .join(",");
        let mut params = vec![SqlValue::Text(ns.to_owned())];
        params.extend(chunk.iter().map(|rowid| SqlValue::Integer(*rowid)));
        let membership_sql = format!(
            "SELECT 1 AS present FROM knowledge_atoms \
             WHERE rowid IN ({placeholders}) AND namespace = ?1 LIMIT 1"
        );
        let row = match stage
            .read(
                LexicalPhase::NamespaceMembership,
                reader.query_row(SqlStatement {
                    sql: membership_sql,
                    params,
                    label: None,
                }),
            )
            .await
        {
            Ok(row) => row,
            Err(e) if is_timeout(&e) => {
                return Ok(FtsFetchOutcome {
                    atoms: Vec::new(),
                    timeout: stage.timeout,
                    state: LexicalCandidateState::TimedOut,
                });
            }
            Err(e) => return Err(sql_err("search fts namespace membership probe", e)),
        };
        if row.is_some() {
            namespace_has_match = true;
            break;
        }
    }
    // A capped global window cannot prove local absence: a foreign prefix may
    // hide local ineligible rows. Recover namespace-only existence for those
    // terms before exposing no_match, within the same lexical deadline.
    if !namespace_has_match {
        for term in unexhausted_terms {
            let row = match stage
                .read(
                    LexicalPhase::NamespaceExistence,
                    reader.query_row(SqlStatement {
                        sql: "SELECT 1 AS present FROM fts_knowledge \
                              CROSS JOIN knowledge_atoms AS a ON a.rowid = fts_knowledge.rowid \
                              WHERE fts_knowledge MATCH ?1 AND +a.namespace = ?2 LIMIT 1"
                            .into(),
                        params: vec![SqlValue::Text(term), SqlValue::Text(ns.to_owned())],
                        label: None,
                    }),
                )
                .await
            {
                Ok(row) => row,
                Err(e) if is_timeout(&e) => {
                    return Ok(FtsFetchOutcome {
                        atoms: Vec::new(),
                        timeout: stage.timeout,
                        state: LexicalCandidateState::TimedOut,
                    });
                }
                Err(e) => return Err(sql_err("search fts scoped namespace existence", e)),
            };
            if row.is_some() {
                namespace_has_match = true;
                break;
            }
        }
    }
    if namespace_has_match {
        return Ok(FtsFetchOutcome {
            atoms: Vec::new(),
            timeout: None,
            state: LexicalCandidateState::Filtered,
        });
    }

    let no_scoreable_terms = !matching::tokenize_field(raw_query)
        .iter()
        .any(|term| term.len() >= MIN_TERM_LEN && !is_stop(term));
    if no_scoreable_terms {
        match fetch_exact_name_candidate(
            reader.as_mut(),
            ns,
            raw_query,
            type_filter,
            statuses,
            exclude_statuses,
            &mut stage,
        )
        .await?
        {
            ExactNameProbe::Hit(atom) => {
                return Ok(FtsFetchOutcome {
                    atoms: vec![*atom],
                    timeout: None,
                    state: LexicalCandidateState::ExactName,
                })
            }
            ExactNameProbe::Filtered => {
                return Ok(FtsFetchOutcome {
                    atoms: Vec::new(),
                    timeout: None,
                    state: LexicalCandidateState::Filtered,
                })
            }
            ExactNameProbe::TimedOut => {
                return Ok(FtsFetchOutcome {
                    atoms: Vec::new(),
                    timeout: stage.timeout,
                    state: LexicalCandidateState::TimedOut,
                })
            }
            ExactNameProbe::Miss => {}
        }
    }

    Ok(FtsFetchOutcome {
        atoms: Vec::new(),
        timeout: None,
        state: LexicalCandidateState::NoMatch,
    })
}

fn exact_name_statement(
    ns: &str,
    slug: &str,
    type_filter: Option<&str>,
    statuses: &[String],
    exclude_statuses: &[&str],
) -> SqlStatement {
    let (status_clause, status_params) = status_sql_clause(statuses, exclude_statuses, 3);
    let type_clause = type_eligibility_sql(type_filter, "knowledge_atoms");
    let mut params = vec![
        SqlValue::Text(ns.to_owned()),
        SqlValue::Text(slug.to_owned()),
    ];
    params.extend(status_params);
    SqlStatement {
        sql: format!(
            "SELECT *, CASE WHEN 1{status_clause}{type_clause} THEN 1 ELSE 0 END AS exact_name_eligible \
             FROM knowledge_atoms \
             WHERE namespace = ?1 AND slug = ?2 AND deleted_at IS NULL LIMIT 1"
        ),
        params,
        label: Some("knowledge.exact_name".into()),
    }
}

/// Reuse the lexical pass's reader and remaining deadline: opening a fresh
/// stage here would give a short query a second, unaccounted retrieval budget.
/// The unique namespace/slug key bounds this to one row. Custom slugs outside
/// the import convention remain outside the exact-name recovery guarantee.
async fn fetch_exact_name_candidate(
    reader: &mut dyn khive_storage::SqlReader,
    ns: &str,
    raw_query: &str,
    type_filter: Option<&str>,
    statuses: &[String],
    exclude_statuses: &[&str],
    stage: &mut LexicalStage,
) -> Result<ExactNameProbe, RuntimeError> {
    let slug = to_slug(raw_query);
    if slug.is_empty() {
        return Ok(ExactNameProbe::Miss);
    }
    let row = stage
        .read(
            LexicalPhase::ExactNameProbe,
            reader.query_row(exact_name_statement(
                ns,
                &slug,
                type_filter,
                statuses,
                exclude_statuses,
            )),
        )
        .await;
    match row {
        Ok(Some(row)) if row_i64(&row, "exact_name_eligible") != Some(1) => {
            Ok(ExactNameProbe::Filtered)
        }
        Ok(Some(row)) => Ok(atom_from_row(&row).map_or(ExactNameProbe::Miss, |atom| {
            ExactNameProbe::Hit(Box::new(atom))
        })),
        Ok(None) => Ok(ExactNameProbe::Miss),
        Err(e) if is_timeout(&e) => Ok(ExactNameProbe::TimedOut),
        Err(e) => Err(sql_err("search exact-name query", e)),
    }
}

#[derive(Debug)]
enum ExactNameProbe {
    Hit(Box<Atom>),
    Miss,
    Filtered,
    TimedOut,
}

// ─── search context ───────────────────────────────────────────────────────────

struct SearchCtx<'a> {
    runtime: &'a KhiveRuntime,
    ns: &'a str,
    role: Option<&'a str>,
    type_filter: Option<&'a str>,
    min_score: f32,
    w: &'a Weights,
    fetch_limit: usize,
    statuses: &'a [String],
    exclude_statuses: &'a [&'a str],
    term_budget: &'a FtsTermBudget,
}

// ─── core single-pass search ──────────────────────────────────────────────────

/// `search_core`'s result plus any lexical/FTS read timeout diagnostics.
/// A caller sees `hits` possibly empty/partial and timeout details instead of an
/// `Err` — never a verb-level error for a genuine timeout.
struct SearchCoreOutcome {
    hits: Vec<ScoredHit>,
    lexical_timeouts: Vec<LexicalTimeout>,
    lexical_state: LexicalCandidateState,
}

async fn search_core(
    ctx: &SearchCtx<'_>,
    query: &str,
    pass: LexicalPass,
) -> Result<SearchCoreOutcome, RuntimeError> {
    let runtime = ctx.runtime;
    let ns = ctx.ns;
    let role = ctx.role;
    let type_filter = ctx.type_filter;
    let min_score = ctx.min_score;
    let w = ctx.w;
    let fetch_limit = ctx.fetch_limit;
    let raw_query = query.trim().to_string();
    if raw_query.is_empty() {
        return Ok(SearchCoreOutcome {
            hits: Vec::new(),
            lexical_timeouts: Vec::new(),
            lexical_state: LexicalCandidateState::NoMatch,
        });
    }

    let scored_query = match role {
        Some(r) if !r.trim().is_empty() => format!("{} {}", r.trim(), raw_query),
        _ => raw_query.clone(),
    };

    let (terms, original_terms, query_order, expanded) = {
        let raw_tokens: Vec<String> = matching::tokenize_field(&scored_query)
            .into_iter()
            .filter(|w| w.len() >= MIN_TERM_LEN && !is_stop(w))
            .collect();
        let mut seen = HashSet::new();
        let qo: Vec<String> = raw_tokens
            .iter()
            .filter(|w| seen.insert(w.as_str()))
            .cloned()
            .collect();
        let mut t = raw_tokens;
        t.sort();
        t.dedup();
        let originals = t.clone();
        let exp = expand_terms(&mut t);
        (t, originals, qo, exp)
    };
    // When all query tokens are shorter than MIN_TERM_LEN (e.g. "RAG", "GQA", "LoRA"),
    // fall through to exact-name-bonus-only scoring rather than returning early.
    let terms_only_exact = terms.is_empty();

    // The lexical stage owns an independent, narrower read-deadline budget
    // (issue #1930 Amendment 2): `scope_request_read_deadline` keeps
    // whichever deadline is earlier, so this only ever tightens the fetch's
    // effective deadline; once the fetch returns, the wider request
    // deadline governs everything that runs after it (rerank, body-line
    // counts, member sizing) — a lexical-stage timeout no longer spends the
    // whole request.
    let configured_budget = lexical_stage_budget_for_terms(
        lexical_stage_budget(),
        ctx.term_budget.available_for(&raw_query),
    );
    let stage_started = tokio::time::Instant::now();
    let FtsFetchOutcome {
        atoms,
        timeout,
        state: lexical_state,
    } = khive_storage::scope_request_read_deadline(configured_budget, async {
        let stage = LexicalStage::new(pass, stage_started, configured_budget);
        fetch_fts_candidates(
            runtime,
            ns,
            &raw_query,
            type_filter,
            ctx.statuses,
            ctx.exclude_statuses,
            CANDIDATE_POOL,
            ctx.term_budget,
            stage,
        )
        .await
    })
    .await?;
    let lexical_timeouts: Vec<_> = timeout.into_iter().collect();
    if atoms.is_empty() {
        return Ok(SearchCoreOutcome {
            hits: Vec::new(),
            lexical_timeouts,
            lexical_state,
        });
    }

    let candidates = load_candidates_from_atoms(&atoms, type_filter);
    if candidates.is_empty() {
        return Ok(SearchCoreOutcome {
            hits: Vec::new(),
            lexical_timeouts,
            lexical_state: if lexical_state == LexicalCandidateState::PartialTimeout {
                lexical_state
            } else {
                LexicalCandidateState::Filtered
            },
        });
    }

    let idf = compute_idf(&candidates, &terms, &expanded, w.expand_discount);
    let mut scored: Vec<(f32, &Candidate)> = candidates
        .iter()
        .filter_map(|cand| {
            let base = if lexical_state == LexicalCandidateState::ExactName {
                w.w_exact_name
            } else if terms_only_exact {
                exact_name_bonus(&cand.name_raw, &raw_query, w.w_exact_name)
            } else {
                score_candidate(
                    cand,
                    &terms,
                    &original_terms,
                    &query_order,
                    &idf,
                    &raw_query,
                    w,
                )
            };
            if base >= min_score {
                Some((base, cand))
            } else {
                None
            }
        })
        .collect();

    scored.sort_by(|a, b| {
        b.0.partial_cmp(&a.0)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.1.slug.cmp(&b.1.slug))
    });
    scored.truncate(fetch_limit);

    Ok(SearchCoreOutcome {
        hits: scored
            .into_iter()
            .map(|(score, cand)| ScoredHit {
                id: cand.id.clone(),
                slug: cand.slug.clone(),
                name: cand.name_raw.clone(),
                content: cand.content_raw.clone(),
                tags: cand.tags_raw.clone(),
                status: cand.status_raw.clone(),
                finalized: cand.finalized,
                is_domain: cand.is_domain,
                score,
                provenance: ScoreProvenance::lexical(),
            })
            .collect(),
        lexical_timeouts,
        lexical_state,
    })
}

// ─── decomposed search ───────────────────────────────────────────────────────

async fn search_decomposed(
    ctx: &SearchCtx<'_>,
    query: &str,
    intersection_bonus: f32,
) -> Result<SearchCoreOutcome, RuntimeError> {
    let non_stop: Vec<&str> = query
        .split_whitespace()
        .filter(|w| w.len() >= MIN_TERM_LEN && !is_stop(&w.to_lowercase()))
        .collect();

    let mid = non_stop.len() / 2;
    let sub_q1: String = non_stop[..mid].join(" ");
    let sub_q2: String = non_stop[mid..].join(" ");
    let sub_limit = ctx.fetch_limit.min(50);

    let SearchCoreOutcome {
        hits: full,
        mut lexical_timeouts,
        lexical_state: full_state,
    } = search_core(ctx, query, LexicalPass::Full).await?;
    let sub_ctx1 = SearchCtx {
        runtime: ctx.runtime,
        ns: ctx.ns,
        role: None,
        type_filter: ctx.type_filter,
        min_score: 0.0,
        w: ctx.w,
        fetch_limit: sub_limit,
        statuses: ctx.statuses,
        exclude_statuses: ctx.exclude_statuses,
        term_budget: ctx.term_budget,
    };
    let SearchCoreOutcome {
        hits: s1,
        lexical_timeouts: s1_timeouts,
        lexical_state: s1_state,
    } = search_core(&sub_ctx1, &sub_q1, LexicalPass::Subquery1).await?;
    let SearchCoreOutcome {
        hits: s2,
        lexical_timeouts: s2_timeouts,
        lexical_state: s2_state,
    } = search_core(&sub_ctx1, &sub_q2, LexicalPass::Subquery2).await?;
    lexical_timeouts.extend(s1_timeouts);
    lexical_timeouts.extend(s2_timeouts);

    Ok(SearchCoreOutcome {
        hits: merge_decomposed_hits(full, [s1, s2], intersection_bonus, ctx.fetch_limit),
        lexical_timeouts,
        lexical_state: LexicalCandidateState::merge(&[full_state, s1_state, s2_state]),
    })
}

fn merge_decomposed_hits(
    full: Vec<ScoredHit>,
    subqueries: [Vec<ScoredHit>; 2],
    intersection_bonus: f32,
    fetch_limit: usize,
) -> Vec<ScoredHit> {
    let mut scores: HashMap<String, f32> = HashMap::new();
    let mut data: HashMap<String, ScoredHit> = HashMap::new();

    for mut hit in full {
        scores.insert(hit.id.clone(), hit.score);
        if let Some(existing) = data.get(&hit.id) {
            hit.provenance.merge_sources(existing.provenance);
        }
        data.insert(hit.id.clone(), hit);
    }

    let mut sub_counts: HashMap<String, u32> = HashMap::new();
    for hits in subqueries {
        let mut seen: HashSet<String> = HashSet::new();
        for hit in hits {
            if let Some(existing) = data.get_mut(&hit.id) {
                existing.provenance.merge_sources(hit.provenance);
            }
            if !seen.insert(hit.id.clone()) {
                continue;
            }
            *sub_counts.entry(hit.id.clone()).or_default() += 1;
            if !data.contains_key(&hit.id) {
                scores.insert(hit.id.clone(), hit.score * 0.3);
                data.insert(hit.id.clone(), hit);
            }
        }
    }

    for (id, count) in &sub_counts {
        if *count >= 2 {
            if let Some(s) = scores.get_mut(id) {
                *s *= 1.0 + intersection_bonus * (*count as f32 - 1.0);
            }
        }
    }

    let mut ranked: Vec<ScoredHit> = data
        .into_values()
        .map(|mut h| {
            if let Some(&s) = scores.get(&h.id) {
                h.score = s;
            }
            h
        })
        .collect();
    ranked.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.slug.cmp(&b.slug))
    });
    ranked.truncate(fetch_limit);
    ranked
}

// ─── embedding rerank ────────────────────────────────────────────────────────

/// Request-local cache for the query's embedding vector(s), threaded through
/// search/suggest/compose so a query is embedded at most once per role it is
/// actually needed in.
///
/// `EmbeddingService::embed_query` and `::embed` are different provider
/// methods: instruction-tuned models (E5, Qwen) prepend a query prompt for
/// the former, so the two calls land in different sides of the retrieval
/// space for the identical text. `role_specific` holds the outcome of the
/// request's one attempt at `runtime.embed_query` (the ANN and KG-blend
/// dense-search path); `generic` holds the first slot of a combined
/// `runtime.embed_batch` rerank call. A `generic` vector is a valid stand-in
/// for `role_specific` in rerank cosine math (both are just "the query's
/// embedding" for a same-space comparison against candidates embedded the
/// same generic way), but it must never satisfy a caller that specifically
/// requires `role_specific` — passing it to the KG blend's `hybrid_search`
/// masks a real `embed_query` failure behind a same-shaped, wrong-space
/// vector (#2307).
#[derive(Debug, Default, Clone)]
struct QueryEmbeddingCache {
    role_specific: RoleSpecificEmbedding,
    generic: Option<Vec<f32>>,
}

/// Outcome of the request's (at most one) attempt to obtain the query's
/// role-specific (`embed_query`) vector.
///
/// A plain `Option<Vec<f32>>` cannot tell "never tried" from "tried and the
/// provider failed" — both read as `None`. That collapse is exactly what let
/// a failed attempt in one stage (e.g. `suggest`) get retried by a later
/// stage in the same request (e.g. `compose`'s KG-blend gate): the later
/// stage saw `None` and had no way to know an attempt, and a failure, had
/// already happened (#2307). `Failed` records that the attempt happened so
/// nothing downstream pays for a second failing provider call; only
/// `NotAttempted` authorizes a stage to try.
#[derive(Debug, Clone, Default, PartialEq)]
enum RoleSpecificEmbedding {
    #[default]
    NotAttempted,
    Failed,
    Vector(Vec<f32>),
}

impl RoleSpecificEmbedding {
    fn as_deref(&self) -> Option<&[f32]> {
        match self {
            Self::Vector(v) => Some(v.as_slice()),
            Self::NotAttempted | Self::Failed => None,
        }
    }

    fn is_not_attempted(&self) -> bool {
        matches!(self, Self::NotAttempted)
    }
}

impl QueryEmbeddingCache {
    fn any(&self) -> Option<&[f32]> {
        self.role_specific.as_deref().or(self.generic.as_deref())
    }
}

async fn embed_cosine_scores(
    runtime: &KhiveRuntime,
    query: &str,
    query_embedding: &mut QueryEmbeddingCache,
    candidate_texts: &[String],
) -> Result<Option<Vec<f32>>, RuntimeError> {
    if runtime.default_embedder_name().is_empty() || candidate_texts.is_empty() {
        return Ok(None);
    }

    // When nothing is cached yet, include the query in this one batch and
    // retain its vector as `generic` for downstream cosine math. Otherwise
    // embed only candidates; the query vector is request-local immutable data.
    let query_was_cached = query_embedding.any().is_some();
    let texts = if query_was_cached {
        candidate_texts.to_vec()
    } else {
        let mut texts = Vec::with_capacity(candidate_texts.len() + 1);
        texts.push(query.to_string());
        texts.extend_from_slice(candidate_texts);
        texts
    };
    // A request read-deadline timeout here degrades to "rerank did not run"
    // (`Ok(None)`) rather than propagating, same contract as every other
    // read in this module (issue #1930 Amendment 2): before the lexical
    // stage owned its own budget, this call was only ever reached when the
    // shared request deadline had *not* already expired, so a mid-flight
    // expiry racing this specific await was unreachable in practice. With
    // the stages decoupled, a lexical-only degradation with real time left
    // to spare now reaches this call normally, and the ordinary
    // async-scheduling race — the deadline elapsing while this embed_batch
    // is in flight — is reachable and must degrade, not hard-error.
    let embeddings = match khive_storage::await_request_read_phase(
        "knowledge.embedding_rerank",
        runtime.embed_batch(&texts),
    )
    .await
    {
        Ok(Ok(embeddings)) => embeddings,
        Ok(Err(_)) => return Ok(None),
        Err(e) if is_timeout(&e) => return Ok(None),
        Err(e) => return Err(e.into()),
    };
    if embeddings.len() != texts.len() {
        return Ok(None);
    }
    let candidate_embeddings = if query_was_cached {
        embeddings.as_slice()
    } else {
        query_embedding.generic = Some(embeddings[0].clone());
        &embeddings[1..]
    };
    let query_emb = query_embedding
        .any()
        .expect("query embedding was cached or populated from non-empty batch");
    Ok(Some(
        candidate_embeddings
            .iter()
            .map(|emb| cosine_similarity(query_emb, emb))
            .collect(),
    ))
}

async fn rerank_with_embeddings(
    runtime: &KhiveRuntime,
    query: &str,
    query_embedding: &mut QueryEmbeddingCache,
    hits: &mut [ScoredHit],
    alpha: f32,
) -> Result<bool, RuntimeError> {
    if hits.is_empty() {
        return Ok(false);
    }
    let texts: Vec<String> = hits
        .iter()
        .map(|h| format!("{} {}", h.name, h.content.as_deref().unwrap_or("")))
        .collect();
    if let Some(cosines) = embed_cosine_scores(runtime, query, query_embedding, &texts).await? {
        let max_tfidf = hits
            .iter()
            .map(|h| h.score)
            .fold(0.0f32, f32::max)
            .max(1e-6);
        for (hit, cos) in hits.iter_mut().zip(cosines.iter()) {
            let norm_tfidf = hit.score / max_tfidf;
            hit.score = alpha * norm_tfidf + (1.0 - alpha) * cos.max(0.0);
            hit.provenance.embedding_rerank = true;
        }
        hits.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.slug.cmp(&b.slug))
        });
        return Ok(true);
    }
    Ok(false)
}

fn cosine_similarity(a: &[f32], b: &[f32]) -> f32 {
    if a.len() != b.len() || a.is_empty() {
        return 0.0;
    }
    let mut dot = 0.0f32;
    let mut norm_a = 0.0f32;
    let mut norm_b = 0.0f32;
    for i in 0..a.len() {
        dot += a[i] * b[i];
        norm_a += a[i] * a[i];
        norm_b += b[i] * b[i];
    }
    let denom = norm_a.sqrt() * norm_b.sqrt();
    if denom < 1e-8 {
        0.0
    } else {
        dot / denom
    }
}

// ─── hit hydration ────────────────────────────────────────────────────────────

// Keep one namespace bind plus the ID binds comfortably below SQLite's
// portable 999-variable ceiling.
const HYDRATION_ID_CHUNK: usize = 900;

/// Build the atom hydration statement for one id chunk.
///
/// The `IN (...)` list runs off `knowledge_atoms`' primary key, so the
/// namespace predicate is deliberately kept out of index selection with
/// SQLite's unary `+` (`+namespace`): a scratch or freshly vacuumed store has
/// no `sqlite_stat1`, and without statistics the planner's default guess for
/// an indexed namespace equality (~10 rows) beats a 250+ id primary-key
/// probe, so it picks `idx_knowledge_atoms_ns_created` and walks the whole
/// namespace once per chunk instead of doing 250 point lookups. `+namespace`
/// removes the column from consideration as an index term so the primary key
/// wins regardless of table size or missing statistics. Do not remove it.
fn hydrate_atoms_statement(ns: &str, ids: &[String]) -> SqlStatement {
    let placeholders = ids
        .iter()
        .enumerate()
        .map(|(i, _)| format!("?{}", i + 2))
        .collect::<Vec<_>>()
        .join(",");
    let mut params = vec![SqlValue::Text(ns.to_owned())];
    params.extend(ids.iter().cloned().map(SqlValue::Text));
    SqlStatement {
        sql: format!(
            "SELECT id, slug, name, content, tags, finalized, status FROM knowledge_atoms \
             WHERE id IN ({placeholders}) AND +namespace = ?1 AND deleted_at IS NULL"
        ),
        params,
        label: None,
    }
}

/// Build the domain hydration statement for one id chunk.
///
/// Same primary-key-first shape as [`hydrate_atoms_statement`], for the same
/// reason: `knowledge_domains` also carries a namespace index
/// (`idx_knowledge_domains_ns`) that the no-statistics planner would
/// otherwise prefer over the primary key on a large id list.
fn hydrate_domains_statement(ns: &str, ids: &[String]) -> SqlStatement {
    let placeholders = ids
        .iter()
        .enumerate()
        .map(|(i, _)| format!("?{}", i + 2))
        .collect::<Vec<_>>()
        .join(",");
    let mut params = vec![SqlValue::Text(ns.to_owned())];
    params.extend(ids.iter().cloned().map(SqlValue::Text));
    SqlStatement {
        sql: format!(
            "SELECT id, slug, name, description, tags, status FROM knowledge_domains \
             WHERE id IN ({placeholders}) AND +namespace = ?1 AND deleted_at IS NULL"
        ),
        params,
        label: None,
    }
}

/// Build the phase-B hydration statement for one chunk of phase-A rowids
/// (issue #2396 fix 5).
///
/// `+a.namespace = ?1` (not a bare equality) is deliberate — same reason and
/// shape as [`hydrate_atoms_statement`]/[`hydrate_domains_statement`]:
/// without table statistics (this codebase never runs `ANALYZE` on
/// `knowledge_atoms`), SQLite's planner prefers `idx_knowledge_atoms_ns` over
/// the integer primary key for a large `rowid IN (...)` list, turning an
/// O(chunk) rowid seek into an O(matching-namespace-rows) index scan per
/// chunk. Verified with `EXPLAIN QUERY PLAN` against a freshly loaded,
/// unanalyzed `knowledge_atoms` table at a 900-row chunk (this statement's
/// own `HYDRATION_ID_CHUNK`): without the unary plus the planner chose
/// `SEARCH a USING INDEX idx_knowledge_atoms_ns (namespace=? AND rowid=?)`;
/// with it, `SEARCH a USING INTEGER PRIMARY KEY (rowid=?)`. The unary plus
/// defeats the index without changing the predicate's meaning.
fn phase_b_hydration_statement(
    ns: &str,
    rowids: &[i64],
    statuses: &[String],
    exclude_statuses: &[&str],
    type_clause: &str,
) -> SqlStatement {
    let rowid_placeholders = rowids
        .iter()
        .enumerate()
        .map(|(i, _)| format!("?{}", i + 2))
        .collect::<Vec<_>>()
        .join(",");
    let (status_clause, status_params) =
        status_sql_clause(statuses, exclude_statuses, 2 + rowids.len());
    let mut params = vec![SqlValue::Text(ns.to_owned())];
    params.extend(rowids.iter().map(|rowid| SqlValue::Integer(*rowid)));
    params.extend(status_params);
    SqlStatement {
        sql: format!(
            "SELECT a.*, a.rowid AS rowid FROM knowledge_atoms AS a \
             WHERE a.rowid IN ({rowid_placeholders}) \
               AND +a.namespace = ?1 \
               AND a.deleted_at IS NULL{status_clause}{type_clause}"
        ),
        params,
        label: None,
    }
}

/// Hydrate ANN-only hit shells from the canonical corpus tables.
///
/// Returns the number of candidate rows that could not be hydrated. Missing
/// rows (for example a stale ANN id) and storage-read failures both degrade the
/// candidate pool instead of failing an otherwise-useful lexical response, but
/// unresolved shells are always removed and the count is surfaced to callers.
async fn hydrate_empty_hits(runtime: &KhiveRuntime, ns: &str, hits: &mut Vec<ScoredHit>) -> usize {
    let ids: Vec<String> = hits
        .iter()
        .filter(|hit| hit.slug.is_empty())
        .map(|hit| hit.id.clone())
        .collect();
    if ids.is_empty() {
        return 0;
    }

    let sql = runtime.sql();
    let mut reader = match sql.reader().await {
        Ok(r) => r,
        Err(error) => {
            tracing::warn!(
                namespace = ns,
                requested = ids.len(),
                error = %error,
                "knowledge candidate hydration could not acquire a reader"
            );
            hits.retain(|hit| !hit.slug.is_empty());
            return ids.len();
        }
    };

    let mut atom_rows = Vec::new();
    for chunk in ids.chunks(HYDRATION_ID_CHUNK) {
        match reader.query_all(hydrate_atoms_statement(ns, chunk)).await {
            Ok(rows) => atom_rows.extend(rows),
            Err(error) => {
                tracing::warn!(
                    namespace = ns,
                    requested = chunk.len(),
                    error = %error,
                    "knowledge atom candidate hydration chunk degraded"
                );
            }
        }
    }

    let mut atom_rows_by_id: HashMap<String, khive_storage::types::SqlRow> = HashMap::new();
    for row in atom_rows {
        if let Some(id) = row_str(&row, "id") {
            atom_rows_by_id.insert(id, row);
        }
    }

    for hit in hits.iter_mut().filter(|hit| hit.slug.is_empty()) {
        if let Some(row) = atom_rows_by_id.get(&hit.id) {
            hit.slug = row_str(row, "slug").unwrap_or_default();
            hit.name = row_str(row, "name").unwrap_or_default();
            hit.content = row_str(row, "content");
            hit.tags = row_str(row, "tags");
            hit.finalized = row_bool(row, "finalized");
            hit.status = row_str(row, "status");
            let tags_arr: Vec<String> = hit
                .tags
                .as_deref()
                .and_then(|tags| serde_json::from_str(tags).ok())
                .unwrap_or_default();
            hit.is_domain = tags_arr.iter().any(|t| t == "type:domain");
        }
    }

    let missing_ids: Vec<String> = hits
        .iter()
        .filter(|hit| hit.slug.is_empty())
        .map(|hit| hit.id.clone())
        .collect();
    if missing_ids.is_empty() {
        return 0;
    }

    let mut domain_rows = Vec::new();
    for chunk in missing_ids.chunks(HYDRATION_ID_CHUNK) {
        match reader.query_all(hydrate_domains_statement(ns, chunk)).await {
            Ok(rows) => domain_rows.extend(rows),
            Err(error) => {
                tracing::warn!(
                    namespace = ns,
                    requested = chunk.len(),
                    error = %error,
                    "knowledge domain candidate hydration chunk degraded"
                );
            }
        }
    }

    let mut domain_rows_by_id: HashMap<String, khive_storage::types::SqlRow> = HashMap::new();
    for row in domain_rows {
        if let Some(id) = row_str(&row, "id") {
            domain_rows_by_id.insert(id, row);
        }
    }

    for hit in hits.iter_mut().filter(|hit| hit.slug.is_empty()) {
        if let Some(row) = domain_rows_by_id.get(&hit.id) {
            hit.slug = row_str(row, "slug").unwrap_or_default();
            hit.name = row_str(row, "name").unwrap_or_default();
            hit.content = row_str(row, "description");
            hit.tags = row_str(row, "tags");
            hit.finalized = false;
            hit.is_domain = true;
            hit.status = row_str(row, "status");
        }
    }

    let failed = hits.iter().filter(|hit| hit.slug.is_empty()).count();
    hits.retain(|hit| !hit.slug.is_empty());
    if failed > 0 {
        tracing::warn!(
            namespace = ns,
            requested = ids.len(),
            failed,
            "knowledge candidate hydration returned a degraded pool"
        );
    }
    failed
}

/// Add hydration degradation to a response without disturbing another
/// degradation diagnostic (for example suggest's ANN-unavailable object).
fn attach_hydration_degradation(out: &mut Value, hydration_failures: usize) {
    if hydration_failures == 0 {
        return;
    }

    if !out
        .get("degraded")
        .is_some_and(serde_json::Value::is_object)
    {
        out["degraded"] = json!({});
    }
    out["degraded"]["hydration_failures"] = json!(hydration_failures);
}

/// Flag that the lexical/FTS candidate fetch hit the request read deadline
/// (issue #1930). Set alongside whatever ANN-backed results (if any) still
/// made it into the response — a timed-out lexical stage degrades the
/// response, it never fails the verb outright.
fn attach_lexical_timeout_degradation(out: &mut Value, timeouts: &[LexicalTimeout]) {
    if timeouts.is_empty() {
        return;
    }
    if !out
        .get("degraded")
        .is_some_and(serde_json::Value::is_object)
    {
        out["degraded"] = json!({});
    }

    // `lexical_timeout` STAYS COARSE: any record at all sets it, exactly as
    // before. It is tempting to narrow it to "a candidate fetch was cut", and
    // issue #2879 asked for that, but it cannot be done without turning this
    // boolean into a cross-namespace disclosure channel.
    //
    // The later phases (`phase_a_rowids`, `phase_b_hydration`,
    // `eligibility_fallback`, the namespace probes) are reachable only when the
    // GLOBAL index matched, which can happen on another namespace's rows when
    // the local ones do not match at all. That is why their records are
    // operator-only and withheld from `lexical_timeout_details`. A boolean that
    // is true when one of them timed out and false when only the ordering probe
    // did would republish the very fact the detail list is censored to hide:
    // the caller would learn that a foreign row matched by observing a flag
    // appear. Measured by
    // `mixed_pass_capability_marker_does_not_reveal_foreign_matches`, which is
    // the guard that catches exactly this and did.
    //
    // So the coarse flag is load-bearing PRECISELY because it is coarse, and
    // the ordering-probe fallback is reported ADDITIVELY beside it instead.
    out["degraded"]["lexical_timeout"] = json!(true);
    out["degraded"]["lexical_timeout_instrumented"] = json!(true);

    if timeouts
        .iter()
        .any(|detail| detail.bound == LexicalBound::OrderingProbe)
    {
        // The ordering hint was skipped and the terms were queried in arrival
        // order. Safe to publish, and this is the reason it is a separate key
        // rather than a narrowing of the one above: the probe runs in
        // `term_frequency`, a PUBLIC phase whose entry does not depend on corpus
        // contents, so its presence is already disclosed in the detail list and
        // this flag reveals nothing new. A flag keyed on the later phases would
        // not have that property.
        out["degraded"]["lexical_ordering_probe_timeout"] = json!(true);
    }

    // ONE details list, with the population it always had. Splitting the
    // BOOLEANS is the fix; splitting the disclosure would have been a
    // regression, because `term_frequency` is one of only two public phases and
    // is by far the most common, so a separate list would have emptied the
    // public timing surface for the majority of timeouts. Each record now
    // carries `bound`, which is what lets a caller tell the two apart without
    // losing the timings.
    let details: Vec<_> = timeouts
        .iter()
        .filter(|detail| detail.phase.public())
        .take(3)
        .collect();
    if !details.is_empty() {
        out["degraded"]["lexical_timeout_details"] = json!(details);
    }
}

/// Flag that the best-effort body-line aggregate hit the request read
/// deadline after the search itself completed. The ranked hits are kept and
/// their atom rows report `body_lines: null`; the timeout degrades metadata,
/// it never fails the verb outright.
fn attach_body_lines_timeout_degradation(out: &mut Value) {
    if !out
        .get("degraded")
        .is_some_and(serde_json::Value::is_object)
    {
        out["degraded"] = json!({});
    }
    out["degraded"]["body_lines_timeout"] = json!(true);
}

/// Report unmeasured domains under the stable `member_sizing_timeout` key,
/// whether sizing timed out or the canonical domain row could not be measured.
/// Every affected domain is withheld from `results` — never left in with a
/// `size` the caller cannot price — and listed here instead, as
/// `{id, name, rank, score}`, so the caller sees exactly which ranked hits
/// were excluded and why. `suggest`'s documented contract (issue #105) is
/// that `results` feeds `knowledge.fold`'s `candidates` unmodified;
/// withholding the unpriced domain keeps that passthrough valid instead of
/// turning one unmeasured domain into a hard parse error for the whole fold
/// request.
fn attach_member_sizing_timeout_degradation(out: &mut Value, excluded: &[Value]) {
    if excluded.is_empty() {
        return;
    }

    if !out
        .get("degraded")
        .is_some_and(serde_json::Value::is_object)
    {
        out["degraded"] = json!({});
    }
    out["degraded"]["member_sizing_timeout"] = json!({
        "excluded": excluded,
        "note": "no measurement was produced (timeout or missing canonical domain), so these domains \
                 were withheld from `results` — their cost is unknown and a \
                 budgeted knowledge.fold selection cannot safely admit an unpriced \
                 item. Each entry keeps its id/name/rank/score for reference; \
                 measure size separately before folding one of these in.",
    });
}

struct EligibleAnnSearchState {
    hits: Vec<ScoredHit>,
    availability: AnnAvailability,
    hydration_failures: usize,
}

/// Retrieve an ANN pool whose bounded, rank-preserving truncation happens only
/// after canonical hydration and caller eligibility.
///
/// Vamana has no metadata predicate, so a selective status/kind filter may
/// consume the first raw top-k. Widen exponentially and re-evaluate the full
/// deterministic prefix until the eligible target is filled or the vector
/// corpus is exhausted. The common case performs one ANN search and one
/// hydration pass; only filtered/invalid prefixes pay for widening.
async fn search_eligible_ann_with_refill(
    ctx: &SearchCtx<'_>,
    token: &NamespaceToken,
    ann: &vamana::SharedAnn,
    key: &vamana::AnnKey,
    query_embedding: &[f32],
    target_eligible: usize,
    initial_k: usize,
) -> Result<EligibleAnnSearchState, RuntimeError> {
    let runtime = ctx.runtime;
    let target_eligible = target_eligible.max(1);
    let mut request_k = initial_k.max(target_eligible).max(1);

    loop {
        khive_storage::ensure_request_read_active("knowledge.search")?;
        let AnnSearchState {
            hits: raw_hits,
            availability,
            source_exhausted,
        } = search_ann_with_warm_wait(runtime, token, ann, key, query_embedding, request_k).await;

        let mut seen = HashSet::with_capacity(raw_hits.len());
        let mut hits: Vec<ScoredHit> = raw_hits
            .into_iter()
            .filter(|(id, _)| seen.insert(*id))
            .map(|(id, score)| ScoredHit {
                id: id.to_string(),
                slug: String::new(),
                name: String::new(),
                content: None,
                tags: None,
                finalized: false,
                is_domain: false,
                status: None,
                score,
                provenance: ScoreProvenance::ann(),
            })
            .collect();

        let hydration_failures = hydrate_empty_hits(runtime, ctx.ns, &mut hits).await;
        khive_storage::ensure_request_read_active("knowledge.search")?;
        filter_hits_by_status(&mut hits, ctx.statuses, ctx.exclude_statuses);
        filter_hits_by_type(&mut hits, ctx.type_filter);

        if hits.len() >= target_eligible || source_exhausted {
            hits.truncate(target_eligible);
            return Ok(EligibleAnnSearchState {
                hits,
                availability,
                hydration_failures,
            });
        }

        // The live vector-store count is not a sound upper bound for a serving
        // bridge: a fresh delete removes the canonical vector before its tail
        // tombstone is merged into that older bridge. Widen until the ANN
        // source itself proves exhaustion.
        let next_k = request_k.saturating_mul(2);
        if next_k == request_k {
            hits.truncate(target_eligible);
            return Ok(EligibleAnnSearchState {
                hits,
                availability,
                hydration_failures,
            });
        }
        request_k = next_k;
    }
}

struct CandidateStageOutcome {
    ann_hits: Vec<ScoredHit>,
    ann_availability: Option<AnnAvailability>,
    hydration_failures: usize,
    query_embedding: QueryEmbeddingCache,
}

struct CandidateStageOptions {
    query_embedding: QueryEmbeddingCache,
    ann_target: usize,
    ann_initial_k: usize,
    operation: &'static str,
}

async fn run_candidate_stages<F>(
    ctx: &SearchCtx<'_>,
    token: &NamespaceToken,
    ann: &vamana::SharedAnn,
    raw_query: &str,
    options: CandidateStageOptions,
    lexical: F,
) -> Result<(SearchCoreOutcome, CandidateStageOutcome), RuntimeError>
where
    F: std::future::Future<Output = Result<SearchCoreOutcome, RuntimeError>>,
{
    vamana::ensure_ann_background(ctx.runtime, token, ann);
    let ann_stage = async {
        let mut query_embedding = options.query_embedding;
        let mut ann_hits = Vec::new();
        let mut ann_availability = None;
        let mut hydration_failures = 0;

        if query_embedding.role_specific.is_not_attempted() {
            query_embedding.role_specific = match khive_storage::await_request_read_phase(
                options.operation,
                ctx.runtime.embed_query(raw_query),
            )
            .await
            {
                Ok(Ok(vector)) => RoleSpecificEmbedding::Vector(vector),
                Ok(Err(_)) => RoleSpecificEmbedding::Failed,
                Err(error) if is_timeout(&error) => RoleSpecificEmbedding::Failed,
                Err(error) => return Err(error.into()),
            };
        }

        if let Some(vector) = query_embedding.role_specific.as_deref() {
            let key = vamana::AnnKey::new(ctx.ns, ctx.runtime.default_embedder_name());
            match khive_storage::await_request_read_phase(
                options.operation,
                search_eligible_ann_with_refill(
                    ctx,
                    token,
                    ann,
                    &key,
                    vector,
                    options.ann_target,
                    options.ann_initial_k,
                ),
            )
            .await
            {
                Ok(Ok(state)) => {
                    ann_hits = state.hits;
                    ann_availability = Some(state.availability);
                    hydration_failures = state.hydration_failures;
                }
                Ok(Err(error)) if is_read_timeout(&error) => {}
                Ok(Err(error)) => return Err(error),
                Err(error) if is_timeout(&error) => {}
                Err(error) => return Err(error.into()),
            }
        }

        Ok(CandidateStageOutcome {
            ann_hits,
            ann_availability,
            hydration_failures,
            query_embedding,
        })
    };

    let (ann_result, lexical_result) = tokio::join!(ann_stage, lexical);
    let ann_result = ann_result?;
    Ok((lexical_result?, ann_result))
}

// ─── compose helpers ──────────────────────────────────────────────────────────

struct ScoredTextItem {
    id: String,
    slug: String,
    name: String,
    text: String,
    score: f32,
}

async fn load_domain_by_id_or_slug(
    runtime: &KhiveRuntime,
    ns: &str,
    id_or_slug: &str,
) -> Result<Domain, RuntimeError> {
    let sql = runtime.sql();
    let mut reader = sql
        .reader()
        .await
        .map_err(|e| sql_err("compose domain reader", e))?;
    let id = id_or_slug.trim().to_string();
    let row = if id.parse::<Uuid>().is_ok() {
        reader
            .query_row(SqlStatement {
                sql: "SELECT * FROM knowledge_domains WHERE id = ?1 AND namespace = ?2 AND deleted_at IS NULL LIMIT 1".into(),
                params: vec![SqlValue::Text(id.clone()), SqlValue::Text(ns.to_owned())],
                label: None,
            })
            .await
            .map_err(|e| sql_err("compose domain by id", e))?
    } else {
        let by_slug = reader
            .query_row(SqlStatement {
                sql: "SELECT * FROM knowledge_domains WHERE slug = ?1 AND namespace = ?2 AND deleted_at IS NULL LIMIT 1".into(),
                params: vec![SqlValue::Text(id.clone()), SqlValue::Text(ns.to_owned())],
                label: None,
            })
            .await
            .map_err(|e| sql_err("compose domain by slug", e))?;
        if by_slug.is_some() {
            by_slug
        } else {
            let is_hex = id.len() >= 8
                && id.len() <= 36
                && id.chars().all(|c| c.is_ascii_hexdigit() || c == '-');
            if is_hex {
                let pattern = format!("{}%", hex_prefix_to_uuid_pattern(&id));
                let rows = reader
                    .query_all(SqlStatement {
                        sql: "SELECT * FROM knowledge_domains WHERE id LIKE ?1 AND namespace = ?2 AND deleted_at IS NULL LIMIT 2".into(),
                        params: vec![
                            SqlValue::Text(pattern),
                            SqlValue::Text(ns.to_owned()),
                        ],
                        label: None,
                    })
                    .await
                    .map_err(|e| sql_err("compose domain by prefix", e))?;
                if rows.len() > 1 {
                    return Err(RuntimeError::InvalidInput(format!(
                        "ambiguous domain prefix {id:?} matches multiple domains"
                    )));
                }
                rows.into_iter().next()
            } else {
                None
            }
        }
    };
    row.and_then(|r| domain_from_row(&r))
        .ok_or_else(|| RuntimeError::NotFound(format!("domain not found: {id:?}")))
}

async fn load_atom_by_id_or_slug(
    runtime: &KhiveRuntime,
    ns: &str,
    id_or_slug: &str,
) -> Result<Atom, RuntimeError> {
    let sql = runtime.sql();
    let mut reader = sql
        .reader()
        .await
        .map_err(|e| sql_err("compose atom reader", e))?;
    let id = id_or_slug.trim().to_string();
    let row = if id.parse::<Uuid>().is_ok() {
        reader
            .query_row(SqlStatement {
                sql: "SELECT * FROM knowledge_atoms WHERE id = ?1 AND namespace = ?2 AND deleted_at IS NULL LIMIT 1".into(),
                params: vec![SqlValue::Text(id.clone()), SqlValue::Text(ns.to_owned())],
                label: None,
            })
            .await
            .map_err(|e| sql_err("compose atom by id", e))?
    } else {
        let by_slug = reader
            .query_row(SqlStatement {
                sql: "SELECT * FROM knowledge_atoms WHERE slug = ?1 AND namespace = ?2 AND deleted_at IS NULL LIMIT 1".into(),
                params: vec![SqlValue::Text(id.clone()), SqlValue::Text(ns.to_owned())],
                label: None,
            })
            .await
            .map_err(|e| sql_err("compose atom by slug", e))?;
        if by_slug.is_some() {
            by_slug
        } else {
            let is_hex = id.len() >= 8
                && id.len() <= 36
                && id.chars().all(|c| c.is_ascii_hexdigit() || c == '-');
            if is_hex {
                let pattern = format!("{}%", hex_prefix_to_uuid_pattern(&id));
                let rows = reader
                    .query_all(SqlStatement {
                        sql: "SELECT * FROM knowledge_atoms WHERE id LIKE ?1 AND namespace = ?2 AND deleted_at IS NULL LIMIT 2".into(),
                        params: vec![
                            SqlValue::Text(pattern),
                            SqlValue::Text(ns.to_owned()),
                        ],
                        label: None,
                    })
                    .await
                    .map_err(|e| sql_err("compose atom by prefix", e))?;
                if rows.len() > 1 {
                    return Err(RuntimeError::InvalidInput(format!(
                        "ambiguous atom prefix {id:?} matches multiple atoms"
                    )));
                }
                rows.into_iter().next()
            } else {
                None
            }
        }
    };
    row.and_then(|r| atom_from_row(&r))
        .ok_or_else(|| RuntimeError::NotFound(format!("atom not found: {id:?}")))
}

fn parse_domain_members(domain: &Domain) -> Result<Vec<String>, RuntimeError> {
    if domain.members.is_empty() || domain.members == "[]" {
        return Ok(Vec::new());
    }
    serde_json::from_str::<Vec<String>>(&domain.members).map_err(|e| {
        RuntimeError::Internal(format!(
            "domain {:?} has invalid members JSON: {e}",
            domain.slug
        ))
    })
}

#[derive(Debug, Default)]
struct DomainMemberSizing {
    tokens: usize,
    live_members: usize,
}

/// Member-token sizing is best-effort: a request read-deadline timeout on
/// reader checkout or the query returns an empty map and `true`, not `Err`.
/// One `query_all` has no partial-completion state, so the flag covers the batch.
/// Every live canonical domain enters the map, with zero size and members
/// when no live member joins. Only absent domains stay unmeasured.
async fn load_domain_member_token_sizes(
    runtime: &KhiveRuntime,
    ns: &str,
    domain_ids: &[String],
) -> Result<(HashMap<String, DomainMemberSizing>, bool), RuntimeError> {
    let mut sizes: HashMap<String, DomainMemberSizing> = HashMap::new();
    if domain_ids.is_empty() {
        return Ok((sizes, false));
    }

    let placeholders = domain_ids
        .iter()
        .enumerate()
        .map(|(i, _)| format!("?{}", i + 2))
        .collect::<Vec<_>>()
        .join(",");
    let mut params = vec![SqlValue::Text(ns.to_owned())];
    params.extend(domain_ids.iter().cloned().map(SqlValue::Text));

    let sql = runtime.sql();
    let mut reader = match sql.reader().await {
        Ok(reader) => reader,
        Err(e) if is_timeout(&e) => return Ok((sizes, true)),
        Err(e) => return Err(sql_err("suggest member size reader", e)),
    };
    let rows = match reader
        .query_all(SqlStatement {
            // Keep atom identity in DISTINCT: repeated members count once, while
            // different atoms with identical names and content still count separately.
            sql: format!(
                "SELECT DISTINCT d.id AS domain_id, a.id AS atom_id, a.name, a.content \
                 FROM knowledge_domains AS d \
                 LEFT JOIN json_each(d.members) AS member ON 1 = 1 \
                 LEFT JOIN knowledge_atoms AS a \
                   ON a.namespace = d.namespace \
                  AND a.slug = member.value \
                  AND a.deleted_at IS NULL \
                 WHERE d.namespace = ?1 \
                   AND d.id IN ({placeholders}) \
                   AND d.deleted_at IS NULL"
            ),
            params,
            label: None,
        })
        .await
    {
        Ok(rows) => rows,
        Err(e) if is_timeout(&e) => return Ok((sizes, true)),
        Err(e) => return Err(sql_err("suggest member size query", e)),
    };

    for row in rows {
        let Some(domain_id) = row_str(&row, "domain_id") else {
            continue;
        };
        let sizing = sizes.entry(domain_id).or_default();
        let Some(content) = row_str(&row, "content") else {
            continue;
        };
        let name = row_str(&row, "name").unwrap_or_default();
        sizing.tokens = sizing
            .tokens
            .saturating_add(estimate_compose_item_tokens(&name, &content));
        sizing.live_members = sizing.live_members.saturating_add(1);
    }

    Ok((sizes, false))
}

/// Body-line metadata is best-effort: a request read-deadline timeout on
/// either the reader checkout or the aggregate query returns `Ok(None)` —
/// the already-ranked hits report `body_lines: null` with a degradation
/// flag instead of the whole search failing. Non-timeout storage errors
/// still propagate.
///
/// The line count follows `str::lines()` semantics: a terminal newline does
/// not add a line, blank interior lines count, and empty content is 0.
async fn load_atom_body_line_counts(
    runtime: &KhiveRuntime,
    ns: &str,
    atom_ids: &[String],
) -> Result<Option<HashMap<String, usize>>, RuntimeError> {
    let mut counts: HashMap<String, usize> = atom_ids.iter().map(|id| (id.clone(), 0)).collect();
    if atom_ids.is_empty() {
        return Ok(Some(counts));
    }

    let placeholders = atom_ids
        .iter()
        .enumerate()
        .map(|(i, _)| format!("?{}", i + 2))
        .collect::<Vec<_>>()
        .join(",");
    let mut params = vec![SqlValue::Text(ns.to_owned())];
    params.extend(atom_ids.iter().cloned().map(SqlValue::Text));

    let sql = runtime.sql();
    let mut reader = match sql.reader().await {
        Ok(reader) => reader,
        Err(e) if is_timeout(&e) => return Ok(None),
        Err(e) => return Err(sql_err("search body line count reader", e)),
    };
    let rows = match reader
        .query_all(SqlStatement {
            sql: format!(
                "SELECT atom_id, \
                        SUM(CASE WHEN content = '' THEN 0 \
                                 ELSE length(content) \
                                      - length(replace(content, char(10), '')) \
                                      + (CASE WHEN substr(content, -1) = char(10) \
                                              THEN 0 ELSE 1 END) \
                            END) AS body_lines \
                 FROM knowledge_sections \
                 WHERE namespace = ?1 AND atom_id IN ({placeholders}) \
                 GROUP BY atom_id"
            ),
            params,
            label: None,
        })
        .await
    {
        Ok(rows) => rows,
        Err(e) if is_timeout(&e) => return Ok(None),
        Err(e) => return Err(sql_err("search body line count query", e)),
    };

    for row in rows {
        let Some(atom_id) = row_str(&row, "atom_id") else {
            continue;
        };
        let Some(body_lines) = row_i64(&row, "body_lines") else {
            continue;
        };
        if let Ok(body_lines) = usize::try_from(body_lines) {
            counts.insert(atom_id, body_lines);
        }
    }

    Ok(Some(counts))
}

async fn rerank_text_items(
    runtime: &KhiveRuntime,
    query: &str,
    query_embedding: &mut QueryEmbeddingCache,
    items: &mut [ScoredTextItem],
) -> Result<(), RuntimeError> {
    if items.is_empty() {
        return Ok(());
    }
    let texts: Vec<String> = items.iter().map(|item| item.text.clone()).collect();
    if let Some(cosines) = embed_cosine_scores(runtime, query, query_embedding, &texts).await? {
        for (item, cos) in items.iter_mut().zip(cosines.iter()) {
            item.score = cos.max(0.0);
        }
        items.sort_by(|a, b| {
            b.score
                .partial_cmp(&a.score)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then_with(|| a.slug.cmp(&b.slug))
        });
    }
    Ok(())
}

// ─── KG entity blending (ADR-051 Amendment 1) ─────────────────────────────────

/// The KG entity kinds `knowledge.compose` blends into a briefing. Concepts
/// and documents are the kinds that carry the measured, expert-curated
/// content (algorithms, papers, ADRs) that outranks generic lore atoms on
/// sharply technical queries — see ADR-051 Amendment 1.
const KG_BLEND_ENTITY_KINDS: [&str; 2] = ["concept", "document"];

/// Cap on blended KG entities per briefing, so entities stay a supplementary
/// "Knowledge graph" section and atoms remain the body of the briefing.
const KG_BLEND_CAP: usize = 5;

/// A `concept`/`document` KG entity blended into a compose briefing.
struct KgEntityHit {
    id: String,
    kind: String,
    name: String,
    description: String,
    score: f32,
}

/// Finds `concept`/`document` KG entities relevant to `query`, reranked with
/// the same embedding-cosine signal `rerank_text_items` uses for atom bodies
/// (embed `name + description`, cosine against the query embedding). Because
/// both pools are scored with the identical metric against the identical
/// query embedding, the resulting scores land on the same 0..1 scale as
/// atom/section scores — direct comparison, not a separate rank-fusion step,
/// is what makes them a valid blended candidate pool.
///
/// Candidate discovery itself reuses `KhiveRuntime::hybrid_search` — the same
/// FTS+ANN RRF-fused retrieval path `kg.search(kind="entity")` dispatches to
/// (`khive-pack-kg`'s `handle_search` calls the identical method) — so this
/// does not stand up a parallel retrieval stack; only the final relevance
/// score is recomputed, to land on the atom-comparable scale.
///
/// `min_score` is the self-calibrating inclusion floor (ADR-051 Amendment
/// 1): only hits scoring at or above it survive, applied after rerank and
/// before the `cap` truncation. Callers derive it from the minimum rerank
/// score among the atoms that made the final compose body.
async fn search_kg_entities(
    runtime: &KhiveRuntime,
    token: &NamespaceToken,
    ns: &str,
    query: &str,
    query_embedding: &mut QueryEmbeddingCache,
    cap: usize,
    min_score: f32,
) -> Result<Vec<KgEntityHit>, RuntimeError> {
    // KG discovery has two kind-specific hybrid searches. Both are gated on
    // `role_specific` specifically, never `generic`: a vector produced by
    // the rerank's combined batch (`embed_batch`) lands in a different
    // embedding space than `embed_query` for asymmetric-prompt models, so it
    // must never stand in for a role-specific vector here — doing so would
    // mask a real `embed_query` failure behind a same-shaped wrong-space
    // vector instead of degrading to the atom-only briefing (#2307). No
    // role-specific vector (never attempted, or attempted and failed) means
    // the dense blend is unavailable and the caller safely keeps its
    // already-complete atom-only briefing.
    let Some(query_vector) = query_embedding.role_specific.as_deref() else {
        return Ok(Vec::new());
    };
    let candidate_k = ((cap * 4) as u32).max(20);
    let mut candidate_ids: Vec<Uuid> = Vec::new();
    let mut seen: HashSet<Uuid> = HashSet::new();
    for kind in KG_BLEND_ENTITY_KINDS {
        let hits = runtime
            .hybrid_search(
                token,
                query,
                Some(query_vector.to_vec()),
                candidate_k,
                Some(kind),
                None,
                &[],
                None,
            )
            .await?;
        for hit in hits {
            if seen.insert(hit.entity_id) {
                candidate_ids.push(hit.entity_id);
            }
        }
    }
    if candidate_ids.is_empty() {
        return Ok(Vec::new());
    }

    let visible_ns: Vec<String> = token
        .visible_namespace_strs()
        .iter()
        .map(|s| s.to_string())
        .collect();
    let entities_page = runtime
        .entities(token)?
        .query_entities(
            ns,
            EntityFilter {
                ids: candidate_ids.clone(),
                kinds: KG_BLEND_ENTITY_KINDS
                    .iter()
                    .map(|k| k.to_string())
                    .collect(),
                namespaces: visible_ns,
                ..EntityFilter::default()
            },
            PageRequest {
                offset: 0,
                limit: candidate_ids.len() as u32,
            },
        )
        .await?;

    if entities_page.items.is_empty() {
        return Ok(Vec::new());
    }

    let texts: Vec<String> = entities_page
        .items
        .iter()
        .map(|e| format!("{} {}", e.name, e.description.as_deref().unwrap_or("")))
        .collect();
    let cosines = match embed_cosine_scores(runtime, query, query_embedding, &texts).await? {
        Some(c) => c,
        None => return Ok(Vec::new()),
    };

    let mut hits: Vec<KgEntityHit> = entities_page
        .items
        .iter()
        .zip(cosines.iter())
        .map(|(e, &score)| KgEntityHit {
            id: e.id.to_string(),
            kind: e.kind.clone(),
            name: e.name.clone(),
            description: e.description.clone().unwrap_or_default(),
            score: score.max(0.0),
        })
        .collect();

    hits.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.id.cmp(&b.id))
    });
    // Self-calibrating inclusion floor (ADR-051 Amendment 1): an entity only
    // blends in if it outranks the weakest atom that made the final body —
    // no fixed score constant. Applied after rerank, before the cap, so a
    // query with many strong entities doesn't starve out a marginal one that
    // still clears the floor.
    hits.retain(|h| h.score >= min_score);
    hits.truncate(cap);
    Ok(hits)
}

const KG_ENTITIES_HEADING: &str = "\n---\n\n## Knowledge graph\n\n";

fn format_kg_entity_line(entity: &KgEntityHit) -> String {
    let mut line = format!("- **{}** ({})", entity.name, entity.kind);
    if !entity.description.is_empty() {
        line.push_str(&format!(" — {}", entity.description));
    }
    line.push('\n');
    line
}

/// The supplementary KG block has its own heading. Price the exact bytes
/// rendered, and skip a too-large hit so smaller lower-ranked hits can fit.
fn trim_kg_entities_to_budget(hits: Vec<KgEntityHit>, remaining_budget: usize) -> Vec<KgEntityHit> {
    let mut used = 0usize;
    hits.into_iter()
        .filter(|h| {
            let heading = if used == 0 {
                KG_ENTITIES_HEADING.len()
            } else {
                0
            };
            let cost = heading + format_kg_entity_line(h).len();
            if cost > remaining_budget.saturating_sub(used) {
                false
            } else {
                used += cost;
                true
            }
        })
        .collect()
}

fn format_kg_entities_markdown(entities: &[KgEntityHit]) -> String {
    let mut out = String::from(KG_ENTITIES_HEADING);
    for e in entities {
        out.push_str(&format_kg_entity_line(e));
    }
    out
}

fn format_compose_atom_heading(atom: &Atom) -> String {
    format!("\n## {}\n\nSource: {}\n", atom.name, atom.slug)
}

fn format_compose_section(section: &super::compose::ComposeSectionResult, explain: bool) -> String {
    let mut out = if explain {
        format!(
            "\n### {} (score: {:.4})\n\n",
            section.heading, section.score
        )
    } else {
        format!("\n### {}\n\n", section.heading)
    };
    if !section.content.is_empty() {
        out.push_str(&section.content);
        out.push('\n');
    }
    out
}

fn format_compose_whole_atom(atom: &Atom, score: f32, explain: bool) -> String {
    let mut out = format_compose_atom_heading(atom);
    if explain {
        out.push_str(&format!("Score: {score:.4}\n"));
    }
    if !atom.content.is_empty() {
        out.push('\n');
        out.push_str(&atom.content);
        out.push('\n');
    }
    out
}

fn format_compose_domain_footer(domains: &[Domain]) -> String {
    if domains.is_empty() {
        return String::new();
    }
    let names: Vec<&str> = domains.iter().map(|d| d.name.as_str()).collect();
    format!("\n---\n\nDomains: {}\n", names.join(", "))
}

/// A composed body and the exact records that made it into that body.
struct PackedCompose<'a> {
    markdown: String,
    sections: Vec<&'a super::compose::ComposeSectionResult>,
    included_atom_ids: HashSet<String>,
}

/// Greedily pack ranked sections, then whole atoms that have no sections.
/// When no section fits, retain the historical whole-atom fallback. Costs use
/// the same fragments as rendering, including shared headings and metadata.
fn pack_compose_markdown<'a>(
    query: &str,
    domains: &[Domain],
    atoms: &'a [Atom],
    items: &[ScoredTextItem],
    sections: &'a [super::compose::ComposeSectionResult],
    explain: bool,
    char_budget: usize,
) -> PackedCompose<'a> {
    const PREFIX: &str = "# Knowledge Briefing\n\nQuery: ";
    let mut footer = format_compose_domain_footer(domains);
    if PREFIX.len() + 1 + footer.len() > char_budget {
        // Full domain metadata remains in `data.domains`; omit an oversized
        // display footer rather than letting it consume the entire briefing.
        footer.clear();
    }
    let query_budget = char_budget - PREFIX.len() - 1 - footer.len();
    let mut query_end = query.len().min(query_budget);
    while !query.is_char_boundary(query_end) {
        query_end -= 1;
    }
    let mut markdown = format!("{PREFIX}{}\n", &query[..query_end]);
    let mut body_used = 0usize;
    let body_budget = char_budget - markdown.len() - footer.len();
    let by_id: HashMap<String, &Atom> = atoms.iter().map(|a| (a.id.to_string(), a)).collect();
    let sectioned_atom_ids: HashSet<&str> = sections.iter().map(|s| s.atom_id.as_str()).collect();
    let mut selected_by_atom: HashMap<&str, Vec<&super::compose::ComposeSectionResult>> =
        HashMap::new();
    let mut selected_sections = Vec::new();
    let mut included_atom_ids = HashSet::new();
    for section in sections {
        let Some(atom) = by_id.get(&section.atom_id) else {
            continue;
        };
        let atom_header_cost = if selected_by_atom.contains_key(section.atom_id.as_str()) {
            0
        } else {
            format_compose_atom_heading(atom).len()
        };
        let cost = atom_header_cost + format_compose_section(section, explain).len();
        if cost > body_budget.saturating_sub(body_used) {
            continue;
        }
        body_used += cost;
        selected_by_atom
            .entry(section.atom_id.as_str())
            .or_default()
            .push(section);
        included_atom_ids.insert(section.atom_id.clone());
        selected_sections.push(section);
    }

    let mut whole_atoms = Vec::new();
    for item in items {
        if !selected_sections.is_empty() && sectioned_atom_ids.contains(item.id.as_str()) {
            continue;
        }
        let Some(atom) = by_id.get(&item.id) else {
            continue;
        };
        let fragment = format_compose_whole_atom(atom, item.score, explain);
        if fragment.len() > body_budget.saturating_sub(body_used) {
            continue;
        }
        body_used += fragment.len();
        included_atom_ids.insert(item.id.clone());
        whole_atoms.push(fragment);
    }

    // Sections retain their existing per-atom presentation order. The
    // sectionless whole-atom tail follows the atom rerank order.
    for atom in atoms {
        let atom_id = atom.id.to_string();
        if let Some(secs) = selected_by_atom.get(atom_id.as_str()) {
            markdown.push_str(&format_compose_atom_heading(atom));
            for section in secs {
                markdown.push_str(&format_compose_section(section, explain));
            }
        }
    }
    for fragment in whole_atoms {
        markdown.push_str(&fragment);
    }
    markdown.push_str(&footer);
    debug_assert_eq!(markdown.len(), char_budget - body_budget + body_used);
    PackedCompose {
        markdown,
        sections: selected_sections,
        included_atom_ids,
    }
}

#[cfg(test)]
mod compose_packing_tests {
    use super::super::compose::{ComposeSectionResult, ScoreBreakdown};
    use super::*;

    fn atom(number: u128, name: &str, content: String) -> Atom {
        Atom {
            id: Uuid::from_u128(number),
            namespace: "local".into(),
            slug: format!("atom-{number}"),
            name: name.into(),
            content,
            tags: "[]".into(),
            properties: None,
            status: Some("reviewed".into()),
            source_uri: None,
            source_type: None,
            finalized: true,
            created_at: 0,
            updated_at: 0,
            deleted_at: None,
        }
    }

    fn item(atom: &Atom, score: f32) -> ScoredTextItem {
        ScoredTextItem {
            id: atom.id.to_string(),
            slug: atom.slug.clone(),
            name: atom.name.clone(),
            text: atom.content.clone(),
            score,
        }
    }

    fn domain(name: String) -> Domain {
        Domain {
            id: Uuid::from_u128(999),
            namespace: "local".into(),
            slug: "test-domain".into(),
            name,
            description: None,
            tags: "[]".into(),
            members: "[]".into(),
            created_at: 0,
            updated_at: 0,
            deleted_at: None,
        }
    }

    fn section(atom: &Atom, heading: &str, content: String, score: f32) -> ComposeSectionResult {
        ComposeSectionResult {
            section_id: Uuid::new_v4().to_string(),
            atom_id: atom.id.to_string(),
            section_type: "overview".into(),
            heading: heading.into(),
            content,
            score,
            score_breakdown: ScoreBreakdown {
                section_cosine: score,
                section_bm25: 0.0,
                atom_cosine: score,
                domain_score: 0.0,
                type_weight: 0.0,
            },
        }
    }

    #[test]
    fn actual_markdown_budget_prices_query_domain_and_explain_in_both_modes() {
        let query = "q".repeat(300);
        let domains = vec![domain("long-domain-".repeat(15))];
        let atom = atom(1, "Source Atom", "a".repeat(1_530));
        let atoms = vec![atom.clone()];
        let items = vec![item(&atom, 0.9)];
        let whole = pack_compose_markdown(&query, &domains, &atoms, &items, &[], true, 2_000);
        assert!(whole.markdown.len() <= 2_000);
        assert!(
            whole.included_atom_ids.is_empty(),
            "long atom must not overflow"
        );

        let sections = vec![section(&atom, "Summary", "s".repeat(1_530), 0.9)];
        let sectioned =
            pack_compose_markdown(&query, &domains, &atoms, &items, &sections, true, 2_000);
        assert!(sectioned.markdown.len() <= 2_000);
        assert!(
            sectioned.sections.is_empty(),
            "long section must not overflow"
        );

        // Even a query longer than the entire budget has a bounded display;
        // the response's structured `query` field still carries the full text.
        let long_query = "é".repeat(1_500);
        let bounded =
            pack_compose_markdown(&long_query, &domains, &atoms, &items, &[], false, 2_000);
        assert!(bounded.markdown.len() <= 2_000);
        assert!(bounded.markdown.is_char_boundary(bounded.markdown.len()));
    }

    #[test]
    fn atom_only_packing_skips_oversized_first_hit_and_keeps_smaller_hits() {
        let atoms = vec![
            atom(1, "Too Large", "x".repeat(3_000)),
            atom(2, "Small Two", "y".repeat(300)),
            atom(3, "Small Three", "z".repeat(300)),
        ];
        let items: Vec<_> = atoms
            .iter()
            .zip([0.9, 0.8, 0.7])
            .map(|(a, s)| item(a, s))
            .collect();
        let packed = pack_compose_markdown("query", &[], &atoms, &items, &[], false, 2_000);
        assert!(!packed.markdown.contains("Too Large"));
        assert!(packed.markdown.contains("Small Two"));
        assert!(packed.markdown.contains("Small Three"));
        assert_eq!(packed.included_atom_ids.len(), 2);
    }

    #[test]
    fn mixed_section_and_sectionless_atoms_both_survive() {
        let atoms = vec![
            atom(1, "Sectioned", "source body".into()),
            atom(2, "Sectionless", "whole atom body".into()),
        ];
        let items = vec![item(&atoms[0], 0.9), item(&atoms[1], 0.8)];
        let sections = vec![section(&atoms[0], "Overview", "section body".into(), 0.9)];
        let packed = pack_compose_markdown("query", &[], &atoms, &items, &sections, true, 2_000);
        assert!(packed.markdown.contains("section body"));
        assert!(packed.markdown.contains("whole atom body"));
        assert_eq!(packed.sections.len(), 1);
        assert_eq!(packed.included_atom_ids.len(), 2);
    }

    #[test]
    fn kg_tail_skips_oversized_hit_and_prices_heading_exactly() {
        let hits = vec![
            KgEntityHit {
                id: "large".into(),
                kind: "concept".into(),
                name: "large".into(),
                description: "x".repeat(3_000),
                score: 0.9,
            },
            KgEntityHit {
                id: "small".into(),
                kind: "concept".into(),
                name: "small".into(),
                description: "short".into(),
                score: 0.8,
            },
        ];
        let kept = trim_kg_entities_to_budget(hits, 80);
        assert_eq!(kept.len(), 1);
        assert_eq!(kept[0].id, "small");
        assert!(format_kg_entities_markdown(&kept).len() <= 80);
    }
}

// ─── handler impls ────────────────────────────────────────────────────────────

impl KnowledgeHandlers {
    pub(crate) async fn search(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
        ann: &vamana::SharedAnn,
    ) -> Result<Value, RuntimeError> {
        khive_storage::ensure_request_read_active("knowledge.search")?;
        let p: SearchParams = deser(params)?;
        let raw_query = p.query.trim().to_string();
        if raw_query.is_empty() {
            return Err(RuntimeError::InvalidInput("query must not be empty".into()));
        }

        if let Some(ms) = p.min_score {
            if !ms.is_finite() {
                return Err(RuntimeError::InvalidInput(
                    "min_score must be a finite number".into(),
                ));
            }
        }
        if let Some(ib) = p.intersection_bonus {
            if !ib.is_finite() {
                return Err(RuntimeError::InvalidInput(
                    "intersection_bonus must be a finite number".into(),
                ));
            }
        }
        if let Some(ra) = p.rerank_alpha {
            if !ra.is_finite() {
                return Err(RuntimeError::InvalidInput(
                    "rerank_alpha must be a finite number".into(),
                ));
            }
        }
        if let Some(ref w) = p.weights {
            let pairs: &[(&str, Option<f64>)] = &[
                ("w_exact_name", w.w_exact_name),
                ("w_name", w.w_name),
                ("w_tags", w.w_tags),
                ("w_content", w.w_content),
                ("expand_discount", w.expand_discount),
                ("coverage_alpha", w.coverage_alpha),
                ("w_bigram", w.w_bigram),
            ];
            for (name, val) in pairs {
                if let Some(v) = val {
                    if !v.is_finite() {
                        return Err(RuntimeError::InvalidInput(format!(
                            "weights.{name} must be a finite number"
                        )));
                    }
                }
            }
        }

        let limit = p.limit.unwrap_or(10).clamp(1, 100);
        let min_score = p.min_score.unwrap_or(0.0) as f32;
        let w = Weights::from_opts(&p);
        if let Some(kind) = p.kind.as_deref() {
            if !matches!(kind, "atom" | "domain") {
                return Err(RuntimeError::InvalidInput(format!(
                    "kind must be one of: atom, domain; got {kind:?}"
                )));
            }
        }
        let type_filter = p.kind.as_deref();
        let do_decompose = p.decompose.unwrap_or(false);
        let decompose_threshold = p.decompose_threshold.unwrap_or(4);
        let intersection_bonus = p.intersection_bonus.unwrap_or(0.25) as f32;
        let requested_rerank = p.rerank.unwrap_or(true);
        let do_rerank = requested_rerank && !runtime.default_embedder_name().is_empty();
        let rerank_alpha = p.rerank_alpha.unwrap_or(0.7) as f32;
        let fetch_limit = if do_rerank { limit * 3 } else { limit }.min(100);

        let non_stop_count = raw_query
            .split_whitespace()
            .filter(|w| w.len() >= MIN_TERM_LEN && !is_stop(&w.to_lowercase()))
            .count();

        let ns = token.namespace().as_str().to_owned();
        let requested_statuses = status_values(p.status.as_ref());

        // Normalize exclude_status once: trim whitespace, treat blank as absent.
        // This single normalized value feeds both the SQL predicate (via SearchCtx)
        // and the ANN post-hydration filter, ensuring both result sources see the
        // identical exclusion set regardless of how the caller formatted the value.
        let exclude_status_normalized: Option<&str> = p
            .exclude_status
            .as_deref()
            .map(str::trim)
            .filter(|s| !s.is_empty());
        if let Some(status) = exclude_status_normalized {
            if !matches!(status, "draft" | "reviewed" | "deprecated") {
                return Err(RuntimeError::InvalidInput(format!(
                    "exclude_status must be one of: draft, reviewed, deprecated; got {status:?}"
                )));
            }
        }

        // Precedence (highest to lowest, matches ADR-047 §Status filtering):
        //   1. explicit status=  → no exclusion; SQL and hydrated ANN use the allowlist
        //   2. no status=, explicit exclude_status= (non-blank) → use that exclusion
        //   3. no status=, include_drafts=true → exclude only deprecated
        //   4. default (no status params / blank exclude_status) → exclude draft and deprecated
        let effective_exclude_statuses: Vec<&str> = if !requested_statuses.is_empty() {
            // Caller specified exact status; the shared allowlist wins.
            vec![]
        } else if let Some(ex) = exclude_status_normalized {
            vec![ex]
        } else {
            let include_drafts = p.include_drafts.unwrap_or(false);
            if include_drafts {
                vec!["deprecated"]
            } else {
                vec!["draft", "deprecated"]
            }
        };
        // The zero multiplier for deprecated is also a final eligibility gate.
        // Resolve its override from the same precedence policy used before FTS
        // caps and ANN refill; otherwise explicit exclude_status can admit a
        // row early only for the multiplier stage to remove it later.
        let allow_deprecated =
            deprecated_allowed_by_status_policy(&requested_statuses, &effective_exclude_statuses);

        let term_budget = FtsTermBudget::new();
        let ctx = SearchCtx {
            runtime,
            ns: &ns,
            role: p.role.as_deref(),
            type_filter,
            min_score,
            w: &w,
            fetch_limit,
            statuses: &requested_statuses,
            exclude_statuses: &effective_exclude_statuses,
            term_budget: &term_budget,
        };

        let ann_k = fetch_limit.max(20);
        let (
            SearchCoreOutcome {
                mut hits,
                lexical_timeouts,
                lexical_state,
            },
            CandidateStageOutcome {
                ann_hits,
                ann_availability,
                hydration_failures,
                mut query_embedding,
            },
        ) = run_candidate_stages(
            &ctx,
            token,
            ann,
            &raw_query,
            CandidateStageOptions {
                query_embedding: QueryEmbeddingCache::default(),
                ann_target: ann_k,
                ann_initial_k: ann_k,
                operation: "knowledge.search",
            },
            async {
                if do_decompose && non_stop_count >= decompose_threshold {
                    search_decomposed(&ctx, &raw_query, intersection_bonus).await
                } else {
                    search_core(&ctx, &raw_query, LexicalPass::Full).await
                }
            },
        )
        .await?;

        let mut ann_unavailable = false;
        if !ann_hits.is_empty() {
            fuse_ann_hits(&mut hits, &ann_hits, min_score);
        }
        // FTS hits remain valid partial results. Preserve the existing
        // advisory only for a non-empty corpus with no lexical fallback.
        if matches!(
            ann_availability,
            Some(AnnAvailability::WarmingTimedOut {
                corpus_non_empty: true
            })
        ) && hits.is_empty()
        {
            ann_unavailable = true;
        }
        // Apply shared eligibility unconditionally so every source observes the
        // same final status and kind contract even when ANN did not run.
        filter_hits_by_status(&mut hits, &requested_statuses, &effective_exclude_statuses);
        filter_hits_by_type(&mut hits, type_filter);

        // The lexical stage now owns its own budget (issue #1930 Amendment
        // 2), so `lexical_timeout` no longer implies the request read
        // deadline is spent — only that stage's narrower budget is. Gate on
        // the live ambient deadline instead: a lexical-only degradation
        // with request time left to spare still gets its embedding rerank.
        if do_rerank && !hits.is_empty() && !khive_storage::request_read_is_cancelled() {
            rerank_with_embeddings(
                runtime,
                &raw_query,
                &mut query_embedding,
                &mut hits,
                rerank_alpha,
            )
            .await?;
        }

        apply_status_multipliers(&mut hits, allow_deprecated);
        enforce_min_score_floor(&mut hits, min_score);
        hits.truncate(limit);

        let atom_ids: Vec<String> = hits
            .iter()
            .filter(|hit| !hit.is_domain)
            .map(|hit| hit.id.clone())
            .collect();
        let mut body_lines_timed_out = false;
        let body_line_counts = if khive_storage::request_read_is_cancelled() {
            None
        } else {
            match load_atom_body_line_counts(runtime, &ns, &atom_ids).await? {
                Some(counts) => Some(counts),
                None => {
                    body_lines_timed_out = true;
                    None
                }
            }
        };

        let results: Vec<Value> = hits
            .iter()
            .map(|h| {
                let body_lines = if h.is_domain {
                    None
                } else {
                    body_line_counts
                        .as_ref()
                        .and_then(|counts| counts.get(&h.id).copied())
                };
                json!({
                    "id": h.id,
                    "slug": h.slug,
                    "name": h.name,
                    "content": h.content,
                    "body_lines": body_lines,
                    "tags": h.tags,
                    "status": h.status,
                    "finalized": h.finalized,
                    "kind": if h.is_domain { "domain" } else { "atom" },
                    "score": h.score,
                    "score_provenance": h.provenance.to_json(),
                })
            })
            .collect();
        let count = results.len();

        let mut out = json!({
            "results": results,
            "total": count,
            "candidate_provenance": {
                "lexical": lexical_state.as_str(),
                "fallback": candidate_fallback(&hits),
                "terms_truncated": term_budget.truncated(),
            },
        });
        if ann_unavailable {
            out["ann_unavailable"] = json!(true);
        }
        attach_lexical_timeout_degradation(&mut out, &lexical_timeouts);
        if body_lines_timed_out {
            attach_body_lines_timeout_degradation(&mut out);
        }
        attach_hydration_degradation(&mut out, hydration_failures);
        // The lexical stage's own budget no longer implies the request
        // deadline is spent (issue #1930 Amendment 2), so this last check
        // re-reads the live ambient deadline rather than the stage-local
        // flags: skip only when the request has actually stopped, never a
        // verb-level error for a degradation already reported above.
        if !khive_storage::request_read_is_cancelled() {
            khive_storage::ensure_request_read_active("knowledge.search")?;
        }
        Ok(out)
    }

    /// Suggest domains with measured compose-member costs and live member counts.
    /// Present domains without live members have size zero and members zero.
    /// Every unmeasured domain is withheld under the stable
    /// `degraded.member_sizing_timeout.excluded` key, whether sizing timed out or not.
    pub(crate) async fn suggest(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
        ann: &vamana::SharedAnn,
    ) -> Result<Value, RuntimeError> {
        let (out, _) = Self::suggest_with_query_embedding(
            runtime,
            token,
            params,
            ann,
            QueryEmbeddingCache::default(),
        )
        .await?;
        Ok(out)
    }

    /// Internal suggest path that accepts and returns the request's cached
    /// query vector. Auto-compose calls this directly so its suggest, atom,
    /// section, and KG stages all share one successful query embedding.
    async fn suggest_with_query_embedding(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
        ann: &vamana::SharedAnn,
        query_embedding: QueryEmbeddingCache,
    ) -> Result<(Value, QueryEmbeddingCache), RuntimeError> {
        khive_storage::ensure_request_read_active("knowledge.suggest")?;
        let p: SuggestParams = deser(params)?;
        let raw_query = p.query.trim().to_string();
        if raw_query.is_empty() {
            return Err(RuntimeError::InvalidInput("query must not be empty".into()));
        }
        let word_count = raw_query.split_whitespace().count();
        if word_count < 5 {
            return Err(RuntimeError::InvalidInput(format!(
                "suggest query must be at least 5 words for meaningful domain matching \
                 (got {word_count}). Use knowledge.search for short keyword queries."
            )));
        }
        let limit = p.limit.unwrap_or(8).clamp(1, 100);
        let ns = token.namespace().as_str().to_owned();

        // Exclude draft and deprecated domain atoms by default — same quality
        // default as knowledge.search.  Draft domain atoms are incomplete and
        // should not drive auto-compose or agent orientation.
        const SUGGEST_EXCLUDE: &[&str] = &["draft", "deprecated"];

        let term_budget = FtsTermBudget::new();
        let ctx = SearchCtx {
            runtime,
            ns: &ns,
            role: p.role.as_deref(),
            type_filter: Some("domain"),
            min_score: 0.0,
            w: &Weights::default(),
            fetch_limit: limit * 3,
            statuses: &[],
            exclude_statuses: SUGGEST_EXCLUDE,
            term_budget: &term_budget,
        };

        // Over-fetch aggressively: the corpus is ~27% domains / ~73% atoms, so
        // limit*3 would return mostly atoms that all get dropped after type filtering.
        // 50× over-fetch (floor 200) gives domains a fair chance to appear in the
        // top ANN neighbors before the type gate discards atom hits.
        let ann_k = (limit * 50).max(200);
        let (
            SearchCoreOutcome {
                mut hits,
                lexical_timeouts,
                ..
            },
            CandidateStageOutcome {
                ann_hits,
                ann_availability,
                hydration_failures,
                mut query_embedding,
            },
        ) = run_candidate_stages(
            &ctx,
            token,
            ann,
            &raw_query,
            CandidateStageOptions {
                query_embedding,
                ann_target: ctx.fetch_limit,
                ann_initial_k: ann_k,
                operation: "knowledge.suggest",
            },
            search_core(&ctx, &raw_query, LexicalPass::Full),
        )
        .await?;

        let mut ann_unavailable = false;
        if !ann_hits.is_empty() {
            fuse_ann_hits(&mut hits, &ann_hits, 0.0);
        }
        // Suggest always reports degraded candidate recall for a
        // non-empty corpus, even when lexical candidates survived.
        if let Some(AnnAvailability::WarmingTimedOut { corpus_non_empty }) = ann_availability {
            ann_unavailable = corpus_non_empty;
        }

        filter_hits_by_status(&mut hits, &[], SUGGEST_EXCLUDE);
        filter_hits_by_type(&mut hits, Some("domain"));

        // The lexical stage now owns its own budget (issue #1930 Amendment
        // 2), so `lexical_timeout` no longer implies the request read
        // deadline is spent — only that stage's narrower budget is. Gate on
        // the live ambient deadline instead: a lexical-only degradation
        // with request time left to spare still gets its embedding rerank.
        let fresh_rerank_applied = if khive_storage::request_read_is_cancelled() {
            false
        } else {
            rerank_with_embeddings(
                runtime,
                &raw_query,
                &mut query_embedding,
                &mut hits,
                D_SUGGEST_RERANK_ALPHA,
            )
            .await?
        };

        // Safety net: retain only domain hits in case any non-domain survived above.
        hits.retain(|h| h.is_domain);
        hits.truncate(limit);

        let domain_ids: Vec<String> = hits.iter().map(|h| h.id.clone()).collect();
        // A cancelled ambient deadline skips the call the same way an
        // internal timeout inside it does — both leave every domain in this
        // batch unmeasured, never a measured member cost
        // (issue #2396 fix 3).
        let (member_token_sizes, member_sizing_timed_out) =
            if khive_storage::request_read_is_cancelled() {
                (HashMap::new(), !domain_ids.is_empty())
            } else {
                #[cfg(test)]
                let measured = if MEMBER_SIZING_READ_TIMEOUT.try_with(|_| ()).is_ok() {
                    khive_storage::scope_request_read_deadline(
                        std::time::Duration::ZERO,
                        load_domain_member_token_sizes(runtime, &ns, &domain_ids),
                    )
                    .await
                } else {
                    load_domain_member_token_sizes(runtime, &ns, &domain_ids).await
                };
                #[cfg(not(test))]
                let measured = load_domain_member_token_sizes(runtime, &ns, &domain_ids).await;
                measured?
            };
        if !khive_storage::request_read_is_cancelled() {
            khive_storage::ensure_request_read_active("knowledge.suggest")?;
        }
        // A domain the sizing pass returned no row for is unmeasured as well:
        // a missing entry never defaults to a fabricated zero.
        let unmeasured_domain_ids: HashSet<&str> = domain_ids
            .iter()
            .map(String::as_str)
            .filter(|id| member_sizing_timed_out || !member_token_sizes.contains_key(*id))
            .collect();

        // Price the member atom bodies that compose expands, not the much smaller
        // domain mirror description used for retrieval. The batched join keeps the
        // suggest -> fold budget in compose's estimated-token unit without an N+1
        // hydration pass. A domain whose members were not measured is withheld
        // from `results` entirely and reported under
        // `degraded.member_sizing_timeout.excluded` instead — `suggest`'s
        // documented contract (issue #105) is that `results` feeds
        // `knowledge.fold`'s `candidates` unmodified, and `FoldCandidate::size`
        // is a non-optional `usize`, so leaving an unpriced item in `results`
        // (as `size: null`, issue #2396 fix 3) turned one unmeasured domain into
        // a hard parse error for the whole fold request. Exclusion keeps the
        // passthrough valid while still refusing to let an unpriced domain enter
        // a budgeted fold selection for free.
        let results: Vec<Value> = hits
            .iter()
            .filter(|h| !unmeasured_domain_ids.contains(h.id.as_str()))
            .filter_map(|h| {
                let sizing = member_token_sizes.get(&h.id)?;
                Some(json!({
                    "id": h.id,
                    "name": h.name,
                    "score": h.score,
                    "size": sizing.tokens,
                    "members": sizing.live_members,
                }))
            })
            .collect();
        let count = results.len();
        let excluded: Vec<Value> = hits
            .iter()
            .enumerate()
            .filter(|(_, h)| unmeasured_domain_ids.contains(h.id.as_str()))
            .map(|(i, h)| {
                json!({
                    "id": h.id,
                    "name": h.name,
                    "rank": i + 1,
                    "score": h.score,
                })
            })
            .collect();

        let mut out = json!({ "results": results, "total": count });
        if ann_unavailable {
            // issue #91: escalate degradation to a top-level, self-explaining
            // signal instead of a bare total:0 or an unflagged partial list.
            // `ann_unavailable` is kept unchanged for existing callers; `degraded`
            // states the consequence so a caller does not have to infer it.
            out["ann_unavailable"] = json!(true);
            let (mode, note): (&str, &str) = match (count, fresh_rerank_applied) {
                (0, _) => (
                    "no_match",
                    "ANN index unavailable and lexical/FTS matching also found no \
                     domain for this query. This does NOT confirm the corpus has \
                     nothing relevant — only that this call could not find one. \
                     Do not cache as an absence; retry once the index is healthy.",
                ),
                (_, true) => (
                    "ann_candidates_degraded",
                    "ANN index unavailable: candidate retrieval used lexical/FTS \
                     matching, but fresh embedding cosine reranking was applied to \
                     those candidates. Final ranking includes a dense signal, while \
                     topically relevant domains outside the lexical candidate set may \
                     still be missing. Do not cache; retry once the index is healthy.",
                ),
                (_, false) => (
                    "lexical_only",
                    "ANN index unavailable and fresh embedding reranking did not run: \
                     these results were ranked by lexical/FTS matching only. Ranking \
                     may be less precise than a healthy call, and topically relevant \
                     domains outside the lexical match may be missing. Do not cache; \
                     retry once the index is healthy.",
                ),
            };
            out["degraded"] = json!({
                "reason": "ann_unavailable",
                "mode": mode,
                "cache_safe": false,
                "note": note,
            });
        }
        attach_lexical_timeout_degradation(&mut out, &lexical_timeouts);
        attach_hydration_degradation(&mut out, hydration_failures);
        attach_member_sizing_timeout_degradation(&mut out, &excluded);
        // The lexical stage's own budget no longer implies the request
        // deadline is spent (issue #1930 Amendment 2), so this last check
        // re-reads the live ambient deadline rather than the stage-local
        // flag: skip only when the request has actually stopped, never a
        // verb-level error for a degradation already reported above.
        if !khive_storage::request_read_is_cancelled() {
            khive_storage::ensure_request_read_active("knowledge.suggest")?;
        }
        Ok((out, query_embedding))
    }

    pub(crate) async fn compose(
        runtime: &KhiveRuntime,
        token: &NamespaceToken,
        params: Value,
        ann: &vamana::SharedAnn,
        type_weights: HashMap<String, f32>,
    ) -> Result<Value, RuntimeError> {
        let p: ComposeParams = deser(params)?;

        // Registry dispatch already mints an exact token for an explicit
        // namespace. Direct handler callers must provide that same authorized
        // token; never turn an untrusted business parameter into a stronger
        // namespace capability here.
        let effective_token = match p.namespace.as_deref() {
            Some(ns_str) => {
                let ns = Namespace::parse(ns_str).map_err(|e| {
                    RuntimeError::InvalidInput(format!("invalid namespace {ns_str:?}: {e}"))
                })?;
                if &ns != token.namespace() {
                    return Err(RuntimeError::InvalidInput(
                        "knowledge.compose namespace does not match authorized token namespace"
                            .to_string(),
                    ));
                }
                // Equality above makes this a safe exact-scope narrowing of
                // any broader direct-call token.
                token.with_namespace(ns)
            }
            None => token.clone(),
        };
        let token = &effective_token;

        let raw_query = p.query.trim().to_string();
        if raw_query.is_empty() {
            return Err(RuntimeError::InvalidInput("query must not be empty".into()));
        }
        let explain = p.explain.unwrap_or(false);

        let mut domain_ids: Vec<String> = p
            .domain_ids
            .unwrap_or_default()
            .into_iter()
            .filter(|s| !s.trim().is_empty())
            .collect();
        let atom_ids: Vec<String> = p
            .atom_ids
            .unwrap_or_default()
            .into_iter()
            .filter(|s| !s.trim().is_empty())
            .collect();

        let is_auto = domain_ids.is_empty() && atom_ids.is_empty();
        // `atom_ids`-only calls (caller pinned exact atoms, no domain_ids) never
        // blend KG entities — the caller opted into exactly those atoms. Auto and
        // explicit-domain_ids calls both blend (ADR-051 Amendment 1).
        let atom_ids_only = domain_ids.is_empty() && !atom_ids.is_empty();
        let blend_kg = p.blend_kg.unwrap_or(true) && !atom_ids_only;
        let mut suggest_ann_unavailable = false;
        let mut suggest_hydration_failures = 0usize;
        let mut query_embedding = QueryEmbeddingCache::default();
        if is_auto {
            let word_count = raw_query.split_whitespace().count();
            if word_count < 10 {
                return Err(RuntimeError::InvalidInput(format!(
                    "auto-compose query must be at least 10 words for effective domain selection \
                     (got {word_count}). Provide explicit domain_ids/atom_ids for shorter queries."
                )));
            }
        }

        // #887: unconditional per-stage timing, WARN-on-slow and
        // WARN-on-abandoned. See `super::compose::ComposeTiming` for the
        // full rationale and the completion-contract every early return
        // below must honor (`finish()` before returning, or route the error
        // through `try_or_finish!`). Each `begin(Phase::X)` fires *before*
        // the phase's (possibly fallible, possibly long-running) work — not
        // after — so an in-flight phase is never lost from the breakdown if
        // the request errors, is cancelled, or is abandoned mid-phase.
        use super::compose::Phase;
        let mut timing = super::compose::ComposeTiming::start(&raw_query, is_auto);
        macro_rules! try_or_finish {
            ($e:expr) => {
                match $e {
                    Ok(v) => v,
                    Err(e) => {
                        timing.finish(0);
                        return Err(e.into());
                    }
                }
            };
        }
        try_or_finish!(timing.begin(Phase::Suggest));

        if is_auto {
            let auto_limit = p.auto_limit.unwrap_or(5).clamp(1, 20);
            let suggest_attempt = Self::suggest_with_query_embedding(
                runtime,
                token,
                json!({ "query": &raw_query, "limit": auto_limit }),
                ann,
                std::mem::take(&mut query_embedding),
            )
            .await;
            try_or_finish!(khive_storage::ensure_request_read_active(
                "knowledge.compose"
            ));
            let suggest_result = match suggest_attempt {
                Ok((v, reused_query_embedding)) => {
                    query_embedding = reused_query_embedding;
                    suggest_ann_unavailable = v
                        .get("ann_unavailable")
                        .and_then(|f| f.as_bool())
                        .unwrap_or(false);
                    suggest_hydration_failures = v
                        .pointer("/degraded/hydration_failures")
                        .and_then(Value::as_u64)
                        .and_then(|count| usize::try_from(count).ok())
                        .unwrap_or(0);
                    v
                }
                Err(e) => {
                    try_or_finish!(khive_storage::ensure_request_read_active(
                        "knowledge.compose"
                    ));
                    tracing::warn!(error = %e, "auto-compose: internal suggest failed, returning empty");
                    let response = json!({
                        "status": "ok",
                        "data": {
                            "query": raw_query,
                            "markdown": "# Knowledge Briefing\n\nDomain suggestion unavailable.",
                            "domains": [],
                            "atoms": [],
                            "count": 0,
                            "suggest_error": e.to_string(),
                        },
                    });
                    try_or_finish!(khive_storage::ensure_request_read_active(
                        "knowledge.compose"
                    ));
                    timing.finish(0);
                    return Ok(response);
                }
            };
            if let Some(results) = suggest_result.get("results").and_then(|v| v.as_array()) {
                for r in results.iter().filter(|r| r["members"] != 0) {
                    if let Some(id) = r.get("id").and_then(|v| v.as_str()) {
                        domain_ids.push(id.to_string());
                    }
                }
            }
            if domain_ids.is_empty() {
                let mut data = json!({
                    "query": raw_query,
                    "markdown": "# Knowledge Briefing\n\nNo matching domains found for auto-suggest.",
                    "domains": [],
                    "atoms": [],
                    "count": 0,
                });
                if suggest_ann_unavailable {
                    data["ann_unavailable"] = json!(true);
                }
                attach_hydration_degradation(&mut data, suggest_hydration_failures);
                let response = json!({ "status": "ok", "data": data });
                try_or_finish!(khive_storage::ensure_request_read_active(
                    "knowledge.compose"
                ));
                timing.finish(0);
                return Ok(response);
            }
        }
        try_or_finish!(timing.begin(Phase::Fetch));

        let ns = token.namespace().as_str().to_owned();

        let mut resolved_domains: Vec<Domain> = Vec::new();
        let mut member_slugs: Vec<String> = Vec::new();

        for id in &domain_ids {
            try_or_finish!(khive_storage::ensure_request_read_active(
                "knowledge.compose"
            ));
            let domain = try_or_finish!(load_domain_by_id_or_slug(runtime, &ns, id).await);
            let members = try_or_finish!(parse_domain_members(&domain));
            member_slugs.extend(members);
            resolved_domains.push(domain);
        }

        let mut seen_ids: HashSet<String> = HashSet::new();
        let mut ordered_atoms: Vec<Atom> = Vec::new();
        let mut omitted_members: Vec<String> = Vec::new();

        for slug in &member_slugs {
            try_or_finish!(khive_storage::ensure_request_read_active(
                "knowledge.compose"
            ));
            let atom = match load_atom_by_id_or_slug(runtime, &ns, slug).await {
                Ok(atom) => atom,
                // Domain membership is not rewritten when an atom is deleted.
                // A stale member must not discard the remaining briefing.
                Err(RuntimeError::NotFound(_)) => {
                    omitted_members.push(slug.clone());
                    continue;
                }
                Err(e) => {
                    timing.finish(0);
                    return Err(e);
                }
            };
            if seen_ids.insert(atom.id.to_string()) {
                ordered_atoms.push(atom);
            }
        }
        for id in &atom_ids {
            try_or_finish!(khive_storage::ensure_request_read_active(
                "knowledge.compose"
            ));
            let atom = try_or_finish!(load_atom_by_id_or_slug(runtime, &ns, id).await);
            if seen_ids.insert(atom.id.to_string()) {
                ordered_atoms.push(atom);
            }
        }

        // Auto-compose inherits the same quality default as knowledge.search and
        // knowledge.suggest: draft and deprecated atoms are excluded unless the caller
        // explicitly provided atom_ids (which is an opt-in to whatever those IDs hold).
        if is_auto {
            const COMPOSE_EXCLUDE: &[&str] = &["draft", "deprecated"];
            ordered_atoms.retain(|a| {
                let status = a.status.as_deref().unwrap_or("");
                !COMPOSE_EXCLUDE.contains(&status)
            });
        }

        if ordered_atoms.is_empty() {
            try_or_finish!(khive_storage::ensure_request_read_active(
                "knowledge.compose"
            ));
            let mut data = json!({
                "query": raw_query,
                "markdown": "# Knowledge Briefing\n\nNo atoms found.",
                "domains": [],
                "atoms": [],
                "count": 0,
            });
            if suggest_ann_unavailable {
                data["ann_unavailable"] = json!(true);
            }
            if !omitted_members.is_empty() {
                data["omissions"] = json!(omitted_members);
            }
            attach_hydration_degradation(&mut data, suggest_hydration_failures);
            let response = json!({ "status": "ok", "data": data });
            try_or_finish!(khive_storage::ensure_request_read_active(
                "knowledge.compose"
            ));
            timing.finish(0);
            return Ok(response);
        }

        let mut items: Vec<ScoredTextItem> = ordered_atoms
            .iter()
            .map(|a| ScoredTextItem {
                id: a.id.to_string(),
                slug: a.slug.clone(),
                name: a.name.clone(),
                text: atom_embed_text(a),
                score: 1.0,
            })
            .collect();

        try_or_finish!(timing.begin(Phase::Rerank));
        // The KG blend below requires a role-specific vector (search_kg_entities
        // gates on it, never a generic one — #2307). When this compose call can
        // reach the blend, attempt embed_query directly so a real failure keeps
        // the blend on its degradation path; rerank_text_items's own
        // combined-batch fallback still covers the failure case below. When the
        // blend cannot run anyway (blend_kg is off, or atom_ids_only), skip the
        // solo call and let rerank_text_items embed query + candidates in one
        // combined batch, matching the pre-cache single-job cost.
        if blend_kg
            && query_embedding.role_specific.is_not_attempted()
            && !runtime.default_embedder_name().is_empty()
        {
            let embedded = try_or_finish!(
                khive_storage::await_request_read_phase(
                    "knowledge.compose",
                    runtime.embed_query(&raw_query),
                )
                .await
            );
            query_embedding.role_specific = match embedded {
                Ok(v) => RoleSpecificEmbedding::Vector(v),
                Err(_) => RoleSpecificEmbedding::Failed,
            };
        }
        try_or_finish!(
            rerank_text_items(runtime, &raw_query, &mut query_embedding, &mut items,).await
        );

        let atom_ids: Vec<String> = ordered_atoms.iter().map(|a| a.id.to_string()).collect();
        let atom_cosine_scores: HashMap<String, f32> = items
            .iter()
            .map(|item| (item.id.clone(), item.score))
            .collect();

        try_or_finish!(timing.begin(Phase::Fetch));
        let section_map =
            try_or_finish!(super::compose::load_sections(runtime, &ns, &atom_ids).await);

        let has_sections = !section_map.is_empty();
        try_or_finish!(timing.begin(Phase::Rerank));

        let section_results = if has_sections {
            let domain_member_ids: HashSet<String> = member_slugs
                .iter()
                .filter_map(|slug| {
                    ordered_atoms
                        .iter()
                        .find(|a| a.slug == *slug)
                        .map(|a| a.id.to_string())
                })
                .collect();

            let domain_scores: HashMap<String, f32> = ordered_atoms
                .iter()
                .map(|a| {
                    let id = a.id.to_string();
                    let score = if domain_member_ids.contains(&id) {
                        1.0
                    } else {
                        0.0
                    };
                    (id, score)
                })
                .collect();

            try_or_finish!(khive_storage::ensure_request_read_active(
                "knowledge.compose"
            ));

            if let Some(qe) = query_embedding.any() {
                try_or_finish!(super::compose::score_sections(
                    &raw_query,
                    qe,
                    &atom_cosine_scores,
                    &section_map,
                    &domain_scores,
                    &type_weights,
                    &super::compose::ComposeScoreWeights::default(),
                ))
            } else {
                Vec::new()
            }
        } else {
            Vec::new()
        };
        try_or_finish!(timing.begin(Phase::Trim));

        let max_tokens = p.max_tokens.unwrap_or(8000).clamp(500, 100_000);
        let char_budget = max_tokens * CHARS_PER_TOKEN;

        let packed = pack_compose_markdown(
            &raw_query,
            &resolved_domains,
            &ordered_atoms,
            &items,
            &section_results,
            explain,
            char_budget,
        );
        let section_json: Vec<Value> = if explain {
            packed
                .sections
                .iter()
                .map(|s| {
                        json!({
                            "section_id": s.section_id,
                            "atom_id": s.atom_id,
                            "section_type": s.section_type,
                            "heading": s.heading,
                            "score": (s.score * 10000.0).round() / 10000.0,
                            "breakdown": {
                                "section_cosine": (s.score_breakdown.section_cosine * 10000.0).round() / 10000.0,
                                "section_bm25": (s.score_breakdown.section_bm25 * 10000.0).round() / 10000.0,
                                "atom_cosine": (s.score_breakdown.atom_cosine * 10000.0).round() / 10000.0,
                                "domain_score": (s.score_breakdown.domain_score * 10000.0).round() / 10000.0,
                                "type_weight": (s.score_breakdown.type_weight * 10000.0).round() / 10000.0,
                            },
                        })
                })
                .collect()
        } else {
            Vec::new()
        };

        // KG entity blend (ADR-051 Amendment 1): additive "Knowledge graph"
        // section, trimmed against whatever budget the atom/section body left
        // over. Runs after the body is finalized so entities never displace an
        // atom or section — see `trim_kg_entities_to_budget`.
        //
        // Self-calibrating inclusion floor: an entity only blends in if its
        // rerank score clears the minimum rerank score among the atoms that
        // actually made the final body. A compose whose final body has zero
        // atoms (everything trimmed by `max_tokens`) has no floor to
        // calibrate against, so it blends no entities at all (ADR-051
        // Amendment 1, zero-atom edge case).
        let entity_score_floor: Option<f32> = packed
            .included_atom_ids
            .iter()
            .filter_map(|id| atom_cosine_scores.get(id).copied())
            .fold(None, |acc, s| Some(acc.map_or(s, |a: f32| a.min(s))));
        let mut markdown = packed.markdown;
        let mut kg_entities_json: Vec<Value> = Vec::new();
        if blend_kg {
            if let Some(floor) = entity_score_floor {
                // Discovery/hydration failures degrade to an atom-only
                // response instead of aborting the whole compose — the
                // finalized atom/section body above is still a valid,
                // useful briefing even without the supplementary KG section.
                // KG entities live on the core (main) backend; on a
                // secondary-assigned pack runtime this search would silently
                // blend against an empty graph (ADR-073).
                match search_kg_entities(
                    &runtime.core(),
                    token,
                    &ns,
                    &raw_query,
                    &mut query_embedding,
                    KG_BLEND_CAP,
                    floor,
                )
                .await
                {
                    Ok(kg_hits) => {
                        let remaining_budget = char_budget.saturating_sub(markdown.len());
                        let kg_hits = trim_kg_entities_to_budget(kg_hits, remaining_budget);
                        if !kg_hits.is_empty() {
                            let kg_markdown = format_kg_entities_markdown(&kg_hits);
                            if kg_markdown.len() <= remaining_budget {
                                markdown.push_str(&kg_markdown);
                                kg_entities_json = kg_hits
                                    .iter()
                                    .map(|e| {
                                        json!({
                                            "id": e.id,
                                            "kind": e.kind,
                                            "name": e.name,
                                            "score": (e.score * 10000.0).round() / 10000.0,
                                        })
                                    })
                                    .collect();
                            }
                        }
                    }
                    Err(e) => {
                        try_or_finish!(khive_storage::ensure_request_read_active(
                            "knowledge.compose"
                        ));
                        tracing::warn!(
                            error = %e,
                            "knowledge.compose: KG entity blend failed, continuing with atom-only response"
                        );
                    }
                }
            }
        }

        try_or_finish!(khive_storage::ensure_request_read_active(
            "knowledge.compose"
        ));

        let atom_json: Vec<Value> = items
            .iter()
            .filter(|item| packed.included_atom_ids.contains(&item.id))
            .map(|item| {
                json!({
                    "id": item.id,
                    "slug": item.slug,
                    "name": item.name,
                    "score": (item.score * 10000.0).round() / 10000.0,
                })
            })
            .collect();

        let domain_json: Vec<Value> = resolved_domains
            .iter()
            .map(|d| json!({ "id": d.id.to_string(), "slug": d.slug, "name": d.name }))
            .collect();

        let count = atom_json.len();

        let mut data = json!({
            "query": raw_query,
            "markdown": markdown,
            "domains": domain_json,
            "atoms": atom_json,
            "count": count,
        });
        if explain && !section_json.is_empty() {
            data["sections"] = json!(section_json);
            data["section_count"] = json!(section_json.len());
        }
        if !kg_entities_json.is_empty() {
            data["entities"] = json!(kg_entities_json);
        }
        if suggest_ann_unavailable {
            data["ann_unavailable"] = json!(true);
        }
        if !omitted_members.is_empty() {
            data["omissions"] = json!(omitted_members);
        }
        attach_hydration_degradation(&mut data, suggest_hydration_failures);

        let response = json!({
            "status": "ok",
            "data": data,
        });
        try_or_finish!(khive_storage::ensure_request_read_active(
            "knowledge.compose"
        ));
        timing.finish(count);
        Ok(response)
    }
}

/// Seeds `n` atoms whose content each carries exactly one term from a
/// `vocab_size`-word vocabulary (`term0`..`term{vocab_size-1}`), so an
/// OR-joined query over `k` of those terms matches roughly `k/vocab_size`
/// of the corpus while any single term matches roughly `1/vocab_size` — the
/// same low-overlap shape that makes the OR-joined bm25 sort in the
/// pre-#1930 query cost far more than any one term's bounded subquery.
/// `pub(crate)` (not scoped to `mod tests` below) so the handler-level
/// degrade tests in `ann_degrade_tests.rs` can reuse the same corpus shape.
#[cfg(test)]
pub(crate) async fn seed_low_overlap_corpus(runtime: &KhiveRuntime, n: u32, vocab_size: u32) {
    let y_stride: u32 = 100;
    assert_eq!(
        n % y_stride,
        0,
        "seed_low_overlap_corpus requires n a multiple of 100"
    );
    let x_max = n / y_stride - 1;
    let y_max = y_stride - 1;

    let access = runtime.sql();
    let mut writer = access.writer().await.expect("writer");
    writer
        .execute(SqlStatement {
            sql: format!(
                "WITH RECURSIVE x(n) AS ( \
                     VALUES(0) UNION ALL SELECT n + 1 FROM x WHERE n < {x_max} \
                 ), y(n) AS ( \
                     VALUES(0) UNION ALL SELECT n + 1 FROM y WHERE n < {y_max} \
                 ) \
                 INSERT INTO knowledge_atoms ( \
                     id, namespace, slug, name, content, tags, properties, finalized, \
                     status, source_uri, source_type, created_at, updated_at, deleted_at \
                 ) \
                 SELECT \
                     printf('80000000-0000-0000-0000-%012d', x.n * {y_stride} + y.n), \
                     'local', printf('lowoverlap-%06d', x.n * {y_stride} + y.n), \
                     printf('Low Overlap %06d', x.n * {y_stride} + y.n), \
                     'synthetic corpus content entry ' || (x.n * {y_stride} + y.n) || \
                     ' discusses topic term' || ((x.n * {y_stride} + y.n) % {vocab_size}) || \
                     ' with padding context sentence for realistic length and additional filler', \
                     '[]', NULL, 1, 'reviewed', NULL, NULL, \
                     x.n * {y_stride} + y.n, x.n * {y_stride} + y.n, NULL \
                 FROM x CROSS JOIN y WHERE x.n * {y_stride} + y.n < {n}"
            ),
            params: Vec::new(),
            label: None,
        })
        .await
        .expect("seed low-overlap corpus");
}

#[cfg(test)]
#[path = "lexical_timeout_tests.rs"]
mod lexical_timeout_tests;

#[cfg(test)]
mod tests {
    use super::*;
    use khive_storage::types::{SqlRow, StorageResult};
    use std::sync::{Arc, Mutex};

    tokio::task_local! {
        static TERM_PROBES: Arc<Mutex<Vec<SqlStatement>>>;
    }

    struct TermRecordingReader {
        inner: Box<dyn khive_storage::SqlReader>,
        probes: Arc<Mutex<Vec<SqlStatement>>>,
    }

    impl TermRecordingReader {
        fn record(&self, statement: &SqlStatement) {
            if statement.sql.contains("fts_knowledge MATCH") {
                self.probes
                    .lock()
                    .expect("term probes")
                    .push(statement.clone());
            }
        }
    }

    #[async_trait::async_trait]
    impl khive_storage::SqlReader for TermRecordingReader {
        async fn query_row(&mut self, statement: SqlStatement) -> StorageResult<Option<SqlRow>> {
            self.record(&statement);
            self.inner.query_row(statement).await
        }

        async fn query_all(&mut self, statement: SqlStatement) -> StorageResult<Vec<SqlRow>> {
            self.record(&statement);
            self.inner.query_all(statement).await
        }

        async fn query_scalar(
            &mut self,
            statement: SqlStatement,
        ) -> StorageResult<Option<SqlValue>> {
            self.record(&statement);
            self.inner.query_scalar(statement).await
        }

        async fn explain(&mut self, statement: SqlStatement) -> StorageResult<Vec<SqlRow>> {
            self.inner.explain(statement).await
        }
    }

    pub(super) fn record_term_probes(
        inner: Box<dyn khive_storage::SqlReader>,
    ) -> Box<dyn khive_storage::SqlReader> {
        match TERM_PROBES.try_with(Arc::clone) {
            Ok(probes) => Box::new(TermRecordingReader { inner, probes }),
            Err(_) => inner,
        }
    }

    fn distinct_term_query(count: usize) -> String {
        (0..count)
            .map(|index| format!("distinctterm{index}"))
            .collect::<Vec<_>>()
            .join(" ")
    }

    fn probed_term(statement: &SqlStatement) -> &str {
        match &statement.params[0] {
            SqlValue::Text(term) => term,
            other => panic!("expected bound FTS term, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn distinct_term_fan_out_is_bounded_and_reports_truncation() {
        let runtime = KhiveRuntime::memory().expect("runtime");
        let token = runtime.authorize(Namespace::local()).expect("token");
        for query in [
            distinct_term_query(FTS_TERM_COUNT_LIMIT * 2),
            "alpha beta gamma".into(),
        ] {
            let terms = fts5_candidate_terms(&query);
            let probes = Arc::new(Mutex::new(Vec::new()));
            let response = TERM_PROBES
                .scope(
                    probes.clone(),
                    KnowledgeHandlers::search(
                        &runtime,
                        &token,
                        json!({"query": query, "rerank": false}),
                        &vamana::new_shared(),
                    ),
                )
                .await
                .expect("bounded search");
            let probes = probes.lock().expect("term probes");
            assert_eq!(probes.len(), terms.len().min(FTS_TERM_COUNT_LIMIT));
            assert_eq!(
                probes.iter().map(probed_term).collect::<Vec<_>>(),
                terms
                    .iter()
                    .take(FTS_TERM_COUNT_LIMIT)
                    .map(String::as_str)
                    .collect::<Vec<_>>(),
                "admission must precede even the rarity-frequency probes"
            );
            assert_eq!(
                response["candidate_provenance"]["terms_truncated"],
                terms.len() > FTS_TERM_COUNT_LIMIT
            );
            assert_eq!(response["candidate_provenance"]["lexical"], "no_match");
        }
    }

    #[tokio::test]
    async fn term_budget_is_shared_across_decomposed_sub_queries() {
        let runtime = KhiveRuntime::memory().expect("runtime");
        let token = runtime.authorize(Namespace::local()).expect("token");
        // Ten raw terms expand to twenty: the full query fits, but the
        // combined work of all three passes must still consume one budget.
        for count in [10, FTS_TERM_COUNT_LIMIT + 18] {
            let probes = Arc::new(Mutex::new(Vec::new()));
            let response = TERM_PROBES.scope(probes.clone(), KnowledgeHandlers::search(
                &runtime, &token,
                json!({"query": distinct_term_query(count), "decompose": true, "rerank": false}),
                &vamana::new_shared(),
            )).await.expect("decomposed bounded search");
            assert_eq!(
                probes.lock().expect("term probes").len(),
                FTS_TERM_COUNT_LIMIT
            );
            assert_eq!(response["candidate_provenance"]["terms_truncated"], true);
        }
    }

    #[tokio::test]
    async fn term_bound_covers_staged_fallback_and_namespace_probes() {
        let runtime = KhiveRuntime::memory().expect("runtime");
        let query = distinct_term_query(FTS_TERM_COUNT_LIMIT * 2);
        let terms = fts5_candidate_terms(&query);
        let content = terms
            .iter()
            .map(|term| term.trim_matches('"'))
            .collect::<Vec<_>>()
            .join(" ");
        let sql = runtime.sql();
        let mut writer = sql.writer().await.expect("writer");
        for index in 0..4 {
            let (namespace, content) = if index < 3 {
                ("foreign", content.as_str())
            } else {
                ("local", terms.last().unwrap().trim_matches('"'))
            };
            writer.execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms (id, namespace, slug, name, content, tags, finalized, status, created_at, updated_at) VALUES (?1, ?2, ?3, ?3, ?4, '[]', 1, 'reviewed', 0, 0)".into(),
                params: vec![
                    SqlValue::Text(Uuid::new_v4().to_string()),
                    SqlValue::Text(namespace.into()),
                    SqlValue::Text(format!("term-bound-{index}")),
                    SqlValue::Text(content.into()),
                ],
                label: None,
            }).await.expect("seed bounded-stage fixture");
        }
        drop(writer);
        let budget = FtsTermBudget::new();
        let probes = Arc::new(Mutex::new(Vec::new()));
        let outcome = TERM_PROBES
            .scope(
                probes.clone(),
                with_phase_a_widen_ceiling_override(
                    2,
                    super::fetch_fts_candidates(
                        &runtime,
                        "local",
                        &query,
                        None,
                        &[],
                        &[],
                        5,
                        &budget,
                        LexicalStage::new(
                            LexicalPass::Full,
                            tokio::time::Instant::now(),
                            lexical_stage_budget(),
                        ),
                    ),
                ),
            )
            .await
            .expect("bounded staged fetch");
        assert_eq!(outcome.state, LexicalCandidateState::NoMatch);
        assert!(outcome.atoms.is_empty() && outcome.timeout.is_none());
        assert!(budget.truncated());
        let probes = probes.lock().expect("term probes");
        let allowed: HashSet<_> = terms
            .iter()
            .take(FTS_TERM_COUNT_LIMIT)
            .map(String::as_str)
            .collect();
        assert!(probes
            .iter()
            .all(|statement| allowed.contains(probed_term(statement))));
        assert_eq!(
            probes
                .iter()
                .filter(|statement| statement.sql.starts_with("SELECT rowid"))
                .count(),
            FTS_TERM_COUNT_LIMIT
        );
        assert_eq!(
            probes
                .iter()
                .filter(|statement| statement.sql.starts_with("SELECT count(*) AS frequency"))
                .count(),
            FTS_TERM_COUNT_LIMIT
        );
        assert_eq!(
            probes
                .iter()
                .filter(|statement| statement.sql.starts_with("SELECT a.*"))
                .count(),
            FTS_TERM_COUNT_LIMIT
        );
        assert_eq!(
            probes
                .iter()
                .filter(|statement| statement
                    .sql
                    .starts_with("SELECT 1 AS present FROM fts_knowledge"))
                .count(),
            FTS_TERM_COUNT_LIMIT
        );
    }

    #[test]
    fn lexical_candidate_state_merge_preserves_completed_and_timed_out_passes() {
        use LexicalCandidateState::*;
        for (states, expected) in [
            (vec![], NoMatch),
            (vec![NoMatch, NoMatch], NoMatch),
            (vec![NoMatch, Filtered], Filtered),
            (vec![Filtered, Matched], Matched),
            (vec![TimedOut, TimedOut], TimedOut),
            (vec![TimedOut, NoMatch], PartialTimeout),
            (vec![Matched, TimedOut], PartialTimeout),
            (vec![PartialTimeout, Matched], PartialTimeout),
        ] {
            assert_eq!(
                LexicalCandidateState::merge(&states),
                expected,
                "{states:?}"
            );
            let reversed: Vec<_> = states.into_iter().rev().collect();
            assert_eq!(LexicalCandidateState::merge(&reversed), expected);
        }
    }

    async fn seed_candidate_state_fixture(runtime: &KhiveRuntime) {
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer.execute(SqlStatement {
            sql: "INSERT INTO knowledge_atoms \
                  (id, namespace, slug, name, content, tags, finalized, status, created_at, updated_at) \
                  VALUES \
                  ('92700000-0000-0000-0000-000000000001', 'local', 'newest-unrelated', \
                   'Newest Unrelated', 'ordinary background content', '[]', 1, 'reviewed', 20, 20), \
                  ('92700000-0000-0000-0000-000000000002', 'local', 'filtered-match', \
                   'Filtered Match', 'zzfilteredzz', '[]', 0, 'draft', 10, 10)".into(),
            params: Vec::new(),
            label: None,
        }).await.expect("seed candidate state rows");
    }

    #[tokio::test]
    async fn true_lexical_miss_does_not_return_newest_rows() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        seed_candidate_state_fixture(&runtime).await;
        let query = "zzgenuinelyabsentzz";
        let outcome = fetch_fts_candidates(&runtime, "local", query, None, &[], &[], 5)
            .await
            .expect("true lexical miss");
        assert!(
            outcome.atoms.is_empty(),
            "a true FTS miss must not return recent rows"
        );
        assert_eq!(outcome.state, LexicalCandidateState::NoMatch);
        assert!(outcome.timeout.is_none());
        let token = runtime.authorize(Namespace::local()).expect("local token");
        let response = KnowledgeHandlers::search(
            &runtime,
            &token,
            json!({"query": query, "rerank": false}),
            &vamana::new_shared(),
        )
        .await
        .expect("public search");
        assert_eq!(
            response,
            json!({
                "results": [], "total": 0,
                "candidate_provenance": {"lexical": "no_match", "fallback": "none", "terms_truncated": false},
            })
        );
        let lexical = KnowledgeHandlers::search(
            &runtime,
            &token,
            json!({"query": "ordinary", "rerank": false}),
            &vamana::new_shared(),
        )
        .await
        .expect("matching lexical control");
        assert_eq!(
            lexical["candidate_provenance"],
            json!({"lexical": "matched", "fallback": "none", "terms_truncated": false})
        );
        assert_eq!(lexical["results"][0]["slug"], "newest-unrelated");
        assert_eq!(
            lexical["results"][0]["score_provenance"],
            json!({
                "sources": ["lexical"], "embedding_rerank": false,
                "normalization": "s_over_s_plus_1", "calibrated": false,
            })
        );
    }

    #[tokio::test]
    async fn lexical_candidate_state_distinguishes_filtered_match() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        seed_candidate_state_fixture(&runtime).await;
        let token = runtime.authorize(Namespace::local()).expect("local token");
        let ann = vamana::new_shared();
        for (include_drafts, state, total) in [(false, "filtered", 0), (true, "matched", 1)] {
            let response = KnowledgeHandlers::search(
                &runtime,
                &token,
                json!({"query": "zzfilteredzz", "rerank": false, "include_drafts": include_drafts}),
                &ann,
            )
            .await
            .expect("filtered search");
            assert_eq!(
                response["candidate_provenance"],
                json!({"lexical": state, "fallback": "none", "terms_truncated": false})
            );
            assert_eq!(response["total"], total);
            if include_drafts {
                assert_eq!(response["results"][0]["slug"], "filtered-match");
            }
        }
    }

    async fn fetch_fts_candidates(
        runtime: &KhiveRuntime,
        ns: &str,
        raw_query: &str,
        type_filter: Option<&str>,
        statuses: &[String],
        exclude_statuses: &[&str],
        fetch_limit: usize,
    ) -> Result<FtsFetchOutcome, RuntimeError> {
        super::fetch_fts_candidates(
            runtime,
            ns,
            raw_query,
            type_filter,
            statuses,
            exclude_statuses,
            fetch_limit,
            &FtsTermBudget::new(),
            LexicalStage::new(
                LexicalPass::Full,
                tokio::time::Instant::now(),
                lexical_stage_budget(),
            ),
        )
        .await
    }

    struct ProbeRecordingReader {
        inner: Box<dyn khive_storage::SqlReader>,
        probes: Vec<(SqlStatement, Vec<SqlRow>)>,
    }

    #[async_trait::async_trait]
    impl khive_storage::SqlReader for ProbeRecordingReader {
        async fn query_row(&mut self, statement: SqlStatement) -> StorageResult<Option<SqlRow>> {
            self.inner.query_row(statement).await
        }

        async fn query_all(&mut self, statement: SqlStatement) -> StorageResult<Vec<SqlRow>> {
            let rows = self.inner.query_all(statement.clone()).await?;
            self.probes.push((statement, rows.clone()));
            Ok(rows)
        }

        async fn query_scalar(
            &mut self,
            statement: SqlStatement,
        ) -> StorageResult<Option<SqlValue>> {
            self.inner.query_scalar(statement).await
        }

        async fn explain(&mut self, statement: SqlStatement) -> StorageResult<Vec<SqlRow>> {
            self.inner.explain(statement).await
        }
    }

    #[tokio::test]
    async fn compose_direct_handler_rejects_namespace_token_mismatch() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let token = runtime.authorize(Namespace::local()).expect("local token");
        let ann = vamana::new_shared();

        let err = KnowledgeHandlers::compose(
            &runtime,
            &token,
            json!({
                "namespace": "bench-arm-a",
                "query": "must reject before reading",
            }),
            &ann,
            HashMap::new(),
        )
        .await
        .expect_err("a local token must not elevate into a measurement arm");

        assert!(
            matches!(err, RuntimeError::InvalidInput(ref msg) if msg.contains("does not match authorized token namespace")),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn fts_candidate_terms_recalls_non_contiguous_terms() {
        assert_eq!(
            fts5_candidate_terms("alpha beta alpha and").join(" OR "),
            "\"alpha\" OR \"alphas\" OR \"beta\" OR \"betas\""
        );
        assert_eq!(
            fts5_candidate_terms("RAG").join(" OR "),
            "\"rag\" OR \"rags\""
        );
        assert_eq!(
            fts5_candidate_terms("the and").join(" OR "),
            "\"the and\"",
            "stop-only queries retain the exact-phrase fallback"
        );
    }

    #[tokio::test]
    async fn rarity_probes_are_capped_and_sort_rare_terms_before_common_terms() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        seed_low_overlap_corpus(&runtime, 1_100, 20).await;
        let mut reader = ProbeRecordingReader {
            inner: runtime.sql().reader().await.expect("reader"),
            probes: Vec::new(),
        };
        let terms = [
            "\"term1\"",
            "\"term18\"",
            "\"missing\"",
            "\"term11\"",
            "\"synthetic\"",
        ];
        let ordered = rarest_fts_terms_first(
            &mut reader,
            terms.iter().map(|term| (*term).to_string()).collect(),
            &mut LexicalStage::new(
                LexicalPass::Full,
                tokio::time::Instant::now(),
                lexical_stage_budget(),
            ),
        )
        .await
        .expect("frequency probes");
        assert_eq!(
            ordered,
            ["\"term11\"", "\"term18\"", "\"synthetic\"", "\"term1\""]
        );
        assert_eq!(reader.probes.len(), terms.len());
        assert_eq!(
            reader
                .probes
                .iter()
                .map(|(_, rows)| rows.len())
                .collect::<Vec<_>>(),
            [1; 5],
            "each probe must materialize one aggregate row, including zero matches"
        );
        assert_eq!(
            reader
                .probes
                .iter()
                .map(|(_, rows)| row_i64(&rows[0], "frequency").expect("frequency"))
                .collect::<Vec<_>>(),
            [501, 55, 0, 55, 501],
            "rare counts stay exact and both common terms tie at the cap"
        );
        for (statement, rows) in &reader.probes {
            assert!(matches!(statement.params[1], SqlValue::Integer(501)));
            assert_eq!(rows[0].columns.len(), 1);
        }
    }

    #[tokio::test]
    async fn fts_candidates_pin_the_rowid_prefix_boundary() {
        for (regular_count, best_is_admitted) in [
            (FTS_TERM_LIMIT * PHASE_A_OVERFETCH_FACTOR, false),
            (FTS_TERM_LIMIT - 1, true),
        ] {
            let runtime = KhiveRuntime::memory().expect("in-memory runtime");
            let access = runtime.sql();
            let mut writer = access.writer().await.expect("writer");
            writer
                .execute(SqlStatement {
                    sql: "WITH RECURSIVE entries(n) AS ( \
                              VALUES(1) UNION ALL SELECT n + 1 FROM entries WHERE n < ?1 \
                          ) \
                          INSERT INTO knowledge_atoms ( \
                              rowid, id, namespace, slug, name, content, tags, finalized, \
                              status, created_at, updated_at \
                          ) \
                          SELECT n, printf('92700000-0000-0000-0000-%012d', n), \
                              'local', printf('prefix-%06d', n), 'Prefix Document', \
                              'zzprefixzz padding padding padding padding padding padding padding', \
                              '[]', 1, 'reviewed', 0, 0 FROM entries"
                        .into(),
                    params: vec![SqlValue::Integer(regular_count as i64)],
                    label: None,
                })
                .await
                .expect("seed early matches");
            writer
                .execute(SqlStatement {
                    sql: "INSERT INTO knowledge_atoms ( \
                              rowid, id, namespace, slug, name, content, tags, finalized, \
                              status, created_at, updated_at \
                          ) VALUES ( \
                              ?1, '92700000-0000-0000-0001-000000000000', 'local', \
                              'zzprefix-best', 'Prefix Document', ?2, '[]', 1, 'reviewed', 0, 0)"
                        .into(),
                    params: vec![
                        SqlValue::Integer((regular_count + 1) as i64),
                        SqlValue::Text("zzprefixzz ".repeat(8)),
                    ],
                    label: None,
                })
                .await
                .expect("seed late repeated match");
            drop(writer);

            let mut reader = access.reader().await.expect("reader");
            let best = reader
                .query_row(SqlStatement {
                    sql: "SELECT a.rowid, a.slug FROM fts_knowledge \
                          JOIN knowledge_atoms AS a ON a.rowid = fts_knowledge.rowid \
                          WHERE fts_knowledge MATCH ?1 AND a.namespace = 'local' \
                            AND a.deleted_at IS NULL \
                          ORDER BY bm25(fts_knowledge), a.slug LIMIT 1"
                        .into(),
                    params: vec![SqlValue::Text("\"zzprefixzz\"".into())],
                    label: None,
                })
                .await
                .expect("BM25 control query")
                .expect("BM25 match");
            assert_eq!(row_str(&best, "slug").as_deref(), Some("zzprefix-best"));
            assert_eq!(row_i64(&best, "rowid"), Some((regular_count + 1) as i64));
            drop(reader);

            let outcome = fetch_fts_candidates(
                &runtime,
                "local",
                "zzprefixzz",
                None,
                &[],
                &[],
                FTS_TERM_LIMIT,
            )
            .await
            .expect("bounded candidate fetch");
            assert!(outcome.timeout.is_none());
            assert_eq!(outcome.atoms.len(), FTS_TERM_LIMIT);
            assert_eq!(
                outcome.atoms.iter().any(|atom| atom.slug == "zzprefix-best"),
                best_is_admitted,
                "BM25-best row admission must follow the rowid window; regular_count={regular_count}"
            );
        }
    }

    #[tokio::test]
    async fn phase_a_limit_uses_index_order_without_sorting_matches() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        seed_low_overlap_corpus(&runtime, 1_000, 20).await;
        let access = runtime.sql();
        let mut reader = access.reader().await.expect("reader");
        let statement = phase_a_rowids_statement("\"term1\"", 3);
        for bounded in [statement.clone(), term_frequency_statement("\"term1\"")] {
            for (query, should_sort) in [
                (bounded.sql.clone(), false),
                (
                    bounded
                        .sql
                        .replace("ORDER BY rowid", "ORDER BY bm25(fts_knowledge), rowid"),
                    true,
                ),
            ] {
                let plan = reader
                    .query_all(SqlStatement {
                        sql: format!("EXPLAIN QUERY PLAN {query}"),
                        params: bounded.params.clone(),
                        label: None,
                    })
                    .await
                    .expect("query plan");
                assert!(!plan.is_empty());
                assert!(plan.iter().any(|row| {
                    row_str(row, "detail")
                        .is_some_and(|detail| detail.contains("fts_knowledge VIRTUAL TABLE INDEX"))
                }));
                let sorts = plan.iter().any(|row| {
                    row_str(row, "detail").is_some_and(|detail| detail.contains("TEMP B-TREE"))
                });
                assert_eq!(sorts, should_sort, "plan: {plan:?}");
            }
        }
        let rows = reader.query_all(statement).await.expect("bounded rowids");
        let ids: Vec<_> = rows
            .iter()
            .map(|row| row_i64(row, "rowid").unwrap())
            .collect();
        assert_eq!(ids.len(), 3);
        assert!(ids.windows(2).all(|pair| pair[0] < pair[1]));
    }

    /// Issue #2766. `rarest_fts_terms_first` fetches no candidates — it sorts
    /// the terms — and before this bound it ran against the whole lexical
    /// stage budget, after which the caller returned an EMPTY candidate list
    /// for a stage that had not yet asked for a candidate. The probe now has
    /// its own quarter-budget and its expiry falls back to the arrival order.
    ///
    /// This arm fails on the unpatched code, where `atoms` is empty and the
    /// state is `TimedOut`.
    #[tokio::test(start_paused = true)]
    async fn rarity_probe_expiry_keeps_the_lexical_arm() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        seed_low_overlap_corpus(&runtime, 1_000, 20).await;
        let stage_budget = std::time::Duration::from_secs(1);

        let outcome = with_lexical_stage_budget_override_ms(
            1_000,
            khive_storage::scope_request_read_deadline(
                stage_budget,
                // Past the quarter-budget (250 ms) after the first probe, and
                // short of the stage budget, so only the probe is cut off.
                with_fts_probe_deadline_advance_after_term(
                    1,
                    std::time::Duration::from_millis(300),
                    fetch_fts_candidates(
                        &runtime,
                        "local",
                        "term1 term18",
                        None,
                        &[],
                        &[],
                        CANDIDATE_POOL,
                    ),
                ),
            ),
        )
        .await
        .expect("a cut-off ordering probe must not fail the fetch");

        assert!(
            !outcome.atoms.is_empty(),
            "the ordering probe timing out must not discard the lexical arm"
        );
        assert!(
            outcome.timeout.is_some(),
            "the degradation must still be reported, not swallowed"
        );
        assert_eq!(
            outcome.state,
            LexicalCandidateState::PartialTimeout,
            "candidates in hand with a recorded timeout is partial, never clean"
        );
        let detail = outcome.timeout.expect("recorded timeout");
        assert_eq!(
            detail.phase,
            LexicalPhase::TermFrequency,
            "the reported phase must name the probe, not the fetch"
        );
    }

    /// The pairing that shows the fallback IS the candidate-list order and
    /// that the probe is what produced the rarest-first ordering. One arm
    /// cannot show both, so both run here over the same corpus and the same
    /// per-term expiry, differing only in whether the probe was allowed to
    /// finish.
    ///
    /// The fallback order is NOT the caller's word order, and this arm is
    /// written the way it is because the first version of it assumed that and
    /// failed: `fts5_candidate_terms` ends in `expand_terms`, which sorts
    /// (`scoring.rs`), so the candidate list is lexicographic whatever the
    /// caller wrote. Both spellings therefore fall back to `term1` first, and
    /// running both is the evidence for that rather than a repetition.
    ///
    /// The term pair is chosen, not incidental. The corpus writes
    /// `discusses topic termN` for N in 0..20, so every token matches 50 rows
    /// EXCEPT `term1`, whose FTS prefix family also covers `term10`..`term19`
    /// and therefore matches about 550. `term1` is the only common token
    /// available, and it has to be paired with a token OUTSIDE its own prefix
    /// family or the two match sets are nested and no assertion can separate
    /// them. `term7` qualifies; `term18` does not, which is what an earlier
    /// version of this arm got wrong.
    ///
    /// The reading instrument is the FIRST atom. The merge loop walks the
    /// per-term row vectors in order, so `atoms[0]` is the first row of the
    /// first term the fetch actually queried, whatever the candidate cap does
    /// to the rest.
    #[tokio::test(start_paused = true)]
    async fn rarity_probe_decides_the_order_and_its_expiry_falls_back_to_arrival() {
        let stage_budget = std::time::Duration::from_secs(1);

        // Anchored on the corpus's own surrounding words: a bare `term1` needle
        // is a prefix of `term18` and of `term10`, and would match rows the
        // assertion means to exclude.
        let topic = |term: &str| format!("topic {term} ");
        // Lexicographically first in the candidate list, hence first in the
        // fallback; `term7` is the rarer one, hence first when the probe runs.
        let fallback_first_term = "term1";
        for query in ["term1 term7", "term7 term1"] {
            // Probe allowed to finish: the RARE term is queried first whatever
            // the caller wrote.
            let runtime = KhiveRuntime::memory().expect("in-memory runtime");
            seed_low_overlap_corpus(&runtime, 1_000, 20).await;
            let ordered = with_lexical_stage_budget_override_ms(
                1_000,
                khive_storage::scope_request_read_deadline(
                    stage_budget,
                    with_fts_deadline_advance_after_term(
                        1,
                        stage_budget,
                        fetch_fts_candidates(
                            &runtime,
                            "local",
                            query,
                            None,
                            &[],
                            &[],
                            CANDIDATE_POOL,
                        ),
                    ),
                ),
            )
            .await
            .expect("partial fetch");
            let ordered_first = ordered
                .atoms
                .first()
                .map(|atom| atom.content.clone())
                .expect("the probe-intact fetch must produce candidates");
            assert!(
                ordered_first.contains(&topic("term7")),
                "with the probe intact the rarer term is queried first whatever the \
                 caller wrote ({query}); got {} atoms, first content {ordered_first:?}",
                ordered.atoms.len()
            );

            // Probe cut off: the order is the one the caller wrote.
            let runtime = KhiveRuntime::memory().expect("in-memory runtime");
            seed_low_overlap_corpus(&runtime, 1_000, 20).await;
            let fallback = with_lexical_stage_budget_override_ms(
                1_000,
                khive_storage::scope_request_read_deadline(
                    stage_budget,
                    with_fts_probe_deadline_advance_after_term(
                        1,
                        std::time::Duration::from_millis(300),
                        with_fts_deadline_advance_after_term(
                            1,
                            stage_budget,
                            fetch_fts_candidates(
                                &runtime,
                                "local",
                                query,
                                None,
                                &[],
                                &[],
                                CANDIDATE_POOL,
                            ),
                        ),
                    ),
                ),
            )
            .await
            .expect("partial fetch");
            assert!(
                !fallback.atoms.is_empty(),
                "the fallback must still produce candidates ({query})"
            );
            let fallback_first = fallback
                .atoms
                .first()
                .map(|atom| atom.content.clone())
                .expect("the fallback must still produce candidates");
            assert!(
                fallback_first.contains(&topic(fallback_first_term)),
                "with the probe cut off the fetch must use the candidate-list \
                 order, expected {fallback_first_term} first ({query}); got {} \
                 atoms, first content {fallback_first:?}",
                fallback.atoms.len()
            );
            // And the degradation is still reported rather than read as a miss.
            assert!(
                fallback.timeout.is_some(),
                "a cut-off probe must still be reported ({query})"
            );
        }
    }

    #[tokio::test(start_paused = true)]
    async fn rare_term_survives_stage_expiry_independent_of_query_order() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        seed_low_overlap_corpus(&runtime, 1_000, 20).await;
        let deadline = std::time::Duration::from_secs(1);
        for query in ["term1 term18", "term18 term1"] {
            let outcome = khive_storage::scope_request_read_deadline(
                deadline,
                FTS_TEST_DEADLINE_ADVANCE.scope(
                    FtsTestDeadlineAdvance {
                        after_completed_terms: 1,
                        by: deadline,
                    },
                    fetch_fts_candidates(&runtime, "local", query, None, &[], &[], CANDIDATE_POOL),
                ),
            )
            .await
            .expect("partial fetch");
            assert!(outcome.timeout.is_some());
            assert_eq!(outcome.state, LexicalCandidateState::PartialTimeout);
            assert_eq!(
                outcome.atoms.len(),
                50,
                "the rarer term must complete first"
            );
            assert!(outcome
                .atoms
                .iter()
                .all(|atom| atom.content.contains("term18")));
        }
    }

    /// Issue #1930: the old OR-joined query returned an all-or-nothing error
    /// when it crossed the request deadline. The per-term fetch must instead
    /// keep candidates from a completed term and report `timed_out`. Paused
    /// Tokio time and the test-only per-term deadline control place expiry
    /// exactly between two queries, so the assertion never depends on corpus
    /// work taking longer than a machine-specific wall-clock budget.
    ///
    /// Scope: this covers the per-term BOUNDARY only. Advancing only the
    /// async clock means the post-boundary term is refused by the
    /// pre-registration deadline check, never by an in-flight SQLite
    /// interrupt — that path has its own wall-clock test below. The old
    /// wall-clock old-query oracle (running the pre-fix OR-joined SQL over
    /// this corpus against a tuned budget) is deliberately retired with the
    /// machine-timing flake it depended on; the all-or-nothing behavior of a
    /// single statement crossing its deadline is what the in-flight test
    /// below pins.
    #[tokio::test(start_paused = true)]
    async fn per_term_fetch_degrades_at_controlled_deadline_boundary() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        const N: u32 = 1_000;
        const VOCAB: u32 = 20;
        seed_low_overlap_corpus(&runtime, N, VOCAB).await;

        let query = "term0 term1";
        let deadline = std::time::Duration::from_millis(650);

        let new_result = khive_storage::scope_request_read_deadline(
            deadline,
            FTS_TEST_DEADLINE_ADVANCE.scope(
                FtsTestDeadlineAdvance {
                    after_completed_terms: 1,
                    by: deadline,
                },
                fetch_fts_candidates(&runtime, "local", query, None, &[], &[], CANDIDATE_POOL),
            ),
        )
        .await;
        let outcome = new_result.expect(
            "the per-term fetch must return partial degradation when the controlled deadline \
             expires between term queries",
        );
        assert!(
            outcome.timeout.is_some(),
            "the controlled deadline must be observed"
        );
        assert_eq!(outcome.state, LexicalCandidateState::PartialTimeout);
        assert!(
            !outcome.atoms.is_empty(),
            "candidates from the completed term must survive degradation"
        );
        assert!(
            outcome.atoms.len() <= CANDIDATE_POOL,
            "partial pool must respect the fetch cap; got {}",
            outcome.atoms.len()
        );
    }

    /// Companion to the boundary test above: prove that a wall-clock
    /// deadline expiring during this pack's read path surfaces the typed
    /// `StorageError::Timeout` — never an untyped error — end to end through
    /// the runtime's reader surface. The statement is structurally slow (a
    /// 1000^3 cross join — billions of row operations on any machine), so
    /// the deadline expires long before it could complete.
    ///
    /// Scope: which arm of the deadline machinery fires is scheduling-
    /// dependent — the deadline can latch at reader checkout, at read
    /// registration, or mid-statement via the progress handler — and every
    /// arm must yield the same typed timeout, which is exactly this test's
    /// assertion. The mid-statement arm specifically (progress-handler
    /// interrupt of an executing statement, proven by a probe that counts
    /// progress callbacks) is deterministically covered where the mechanism
    /// lives: `request_deadline_interrupts_statement_without_outer_timeout`
    /// in `crates/khive-db/src/sql_bridge.rs`, whose probe assertion fails
    /// if SQLite work never started. This test does not re-prove the
    /// in-flight arm; it pins the pack-visible contract over all arms.
    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn wall_clock_deadline_on_pack_read_path_surfaces_typed_timeout() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let deadline = std::time::Duration::from_millis(50);
        let result = khive_storage::scope_request_read_deadline(deadline, async {
            let sql = runtime.sql();
            let mut reader = sql.reader().await.expect("reader");
            reader
                .query_all(SqlStatement {
                    sql: "WITH RECURSIVE numbers(value) AS (\
                          SELECT 1 UNION ALL SELECT value + 1 FROM numbers WHERE value < 1000\
                          ) SELECT SUM(a.value * b.value * c.value) \
                          FROM numbers AS a CROSS JOIN numbers AS b CROSS JOIN numbers AS c"
                        .into(),
                    params: vec![],
                    label: Some("knowledge-deadline-probe".into()),
                })
                .await
        })
        .await;
        assert!(
            matches!(result, Err(khive_storage::StorageError::Timeout { .. })),
            "a read crossing the wall-clock deadline must surface the typed \
             timeout whichever deadline arm fires; got {result:?}"
        );
    }

    /// Issue #1930 rework: the per-term loop used to `break` as soon as the
    /// merged pool reached `fetch_limit`, checked *before* querying the next
    /// term. A term that sorts first and alone has more matches than
    /// `fetch_limit` then fills the pool on its own turn, so every later
    /// term never gets queried at all — pool membership depended on query
    /// word order. This seeds "alpha" with more rows than `fetch_limit` and
    /// a disjoint, small "beta" set, then asserts beta's rows survive into
    /// the returned pool. Against the pre-fix early-break loop this must
    /// FAIL: alpha's own per-term query (capped at `fetch_limit`) already
    /// fills `combined` to `fetch_limit` before the loop reaches "beta", so
    /// "beta" is never queried and none of its rows can appear.
    #[tokio::test]
    async fn round_robin_merge_keeps_later_term_candidates_from_starving() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        {
            let access = runtime.sql();
            let mut writer = access.writer().await.expect("writer");
            writer
                .execute(SqlStatement {
                    sql: "WITH RECURSIVE x(n) AS ( \
                              VALUES(0) UNION ALL SELECT n + 1 FROM x WHERE n < 9 \
                          ) \
                          INSERT INTO knowledge_atoms ( \
                              id, namespace, slug, name, content, tags, properties, finalized, \
                              status, source_uri, source_type, created_at, updated_at, deleted_at \
                          ) \
                          SELECT \
                              printf('90000000-0000-0000-0000-%012d', x.n), \
                              'local', printf('alpha-%02d', x.n), printf('Alpha %02d', x.n), \
                              'synthetic content about alpha only', '[]', NULL, 1, \
                              'reviewed', NULL, NULL, x.n, x.n, NULL \
                          FROM x"
                        .to_string(),
                    params: Vec::new(),
                    label: None,
                })
                .await
                .expect("seed alpha rows");
            writer
                .execute(SqlStatement {
                    sql: "WITH RECURSIVE x(n) AS ( \
                              VALUES(0) UNION ALL SELECT n + 1 FROM x WHERE n < 2 \
                          ) \
                          INSERT INTO knowledge_atoms ( \
                              id, namespace, slug, name, content, tags, properties, finalized, \
                              status, source_uri, source_type, created_at, updated_at, deleted_at \
                          ) \
                          SELECT \
                              printf('91000000-0000-0000-0000-%012d', x.n), \
                              'local', printf('beta-%02d', x.n), printf('Beta %02d', x.n), \
                              'synthetic content about beta only', '[]', NULL, 1, \
                              'reviewed', NULL, NULL, x.n, x.n, NULL \
                          FROM x"
                        .to_string(),
                    params: Vec::new(),
                    label: None,
                })
                .await
                .expect("seed beta rows");
        }

        let fetch_limit = 5;
        let outcome =
            fetch_fts_candidates(&runtime, "local", "alpha beta", None, &[], &[], fetch_limit)
                .await
                .expect("fetch must not error");
        assert!(outcome.timeout.is_none());
        assert_eq!(outcome.state, LexicalCandidateState::Matched);
        assert_eq!(outcome.atoms.len(), fetch_limit);

        let beta_present = outcome
            .atoms
            .iter()
            .any(|atom| atom.slug.starts_with("beta-"));
        assert!(
            beta_present,
            "round-robin merge must keep the second term's candidates in the pool \
             even though the first term alone has more matches than fetch_limit; \
             got {:?}",
            outcome
                .atoms
                .iter()
                .map(|a| a.slug.as_str())
                .collect::<Vec<_>>()
        );
    }

    /// Issue #1930 Amendment 2: the lexical stage's own budget must not
    /// cancel the rest of the request when it expires. Paused Tokio time
    /// plus the existing per-term deadline control place the expiry
    /// deterministically between two term queries, inside a nested
    /// `scope_request_read_deadline` call mirroring exactly what
    /// `search_core` does around `fetch_fts_candidates` (a narrow stage
    /// scope nested inside a much longer outer one).
    ///
    /// Before this change, `search_core` called `fetch_fts_candidates`
    /// directly under whatever deadline the caller installed, so this same
    /// expiry — with no separate inner scope to pop back out of — left the
    /// *outer* deadline expired too, and `ensure_request_read_active`
    /// called afterward, still nested in that one shared scope, returned
    /// `Err`. Confirmed by running this test against the fetch called
    /// directly (no stage-budget wrap) before adding the wrap: `still_active`
    /// came back `Err(Timeout { .. })` — this assertion is the red-before
    /// case for that call shape; the wrap makes it green.
    #[tokio::test(start_paused = true)]
    async fn lexical_stage_budget_expiry_does_not_cancel_the_request() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        const N: u32 = 1_000;
        const VOCAB: u32 = 20;
        seed_low_overlap_corpus(&runtime, N, VOCAB).await;

        let query = "term0 term1";
        // This test wraps `fetch_fts_candidates` in its own explicit
        // `scope_request_read_deadline`, exactly mirroring what `search_core`
        // does around it in production — it never goes through
        // `lexical_stage_budget()`'s override seam, so a literal duration is
        // enough here.
        let budget = std::time::Duration::from_millis(50);
        let outer_deadline = std::time::Duration::from_secs(60);

        let (fetch, still_active) =
            khive_storage::scope_request_read_deadline(outer_deadline, async {
                let fetch = khive_storage::scope_request_read_deadline(
                    budget,
                    FTS_TEST_DEADLINE_ADVANCE.scope(
                        FtsTestDeadlineAdvance {
                            after_completed_terms: 1,
                            by: budget,
                        },
                        fetch_fts_candidates(
                            &runtime,
                            "local",
                            query,
                            None,
                            &[],
                            &[],
                            CANDIDATE_POOL,
                        ),
                    ),
                )
                .await
                .expect("the fetch must not hard-error on its own stage budget");

                let still_active =
                    khive_storage::ensure_request_read_active("test.lexical_stage_budget");
                (fetch, still_active)
            })
            .await;

        assert!(
            fetch.timeout.is_some(),
            "the lexical stage's own narrower budget must be observed"
        );
        assert!(
            !fetch.atoms.is_empty(),
            "candidates from the completed term must survive the stage degradation"
        );
        assert!(
            still_active.is_ok(),
            "the outer request deadline must still be active once the lexical \
             stage's own budget expires and its scope returns; got {still_active:?}"
        );
    }

    #[test]
    fn lexical_stage_allowance_scales_only_with_admitted_terms_and_is_capped() {
        let base = lexical_stage_budget();
        let budget = FtsTermBudget::new();
        assert_eq!(
            lexical_stage_budget_for_terms(base, budget.available_for("zzmass")),
            base,
        );
        assert_eq!(
            lexical_stage_budget_for_terms(base, budget.available_for("zzmass zzlass")),
            std::time::Duration::from_millis(2_500),
        );
        let many = distinct_term_query(FTS_TERM_COUNT_LIMIT * 2);
        assert_eq!(
            lexical_stage_budget_for_terms(base, budget.available_for(&many)),
            std::time::Duration::from_millis(8_000),
        );
        budget.admit(fts5_candidate_terms(&many));
        assert_eq!(budget.available_for("zzmass zzlass"), 0);
        assert_eq!(lexical_stage_budget_for_terms(base, 0), base);
    }

    /// A second bounded term read must have time to run after the original
    /// 2 s single-term allowance has elapsed. The clock moves only after the
    /// first term's rows are collected, so the old fixed 2 s stage returned a
    /// partial timeout here even though both local terms have cheap matches.
    #[tokio::test(start_paused = true)]
    async fn multi_term_search_keeps_lexical_candidates_after_single_term_budget() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms \
                      (id, namespace, slug, name, content, tags, finalized, status, created_at, updated_at) \
                      VALUES \
                      ('92700000-0000-0000-0000-000000000011', 'local', 'zzmass-row', \
                       'First term', 'zzmass content', '[]', 1, 'reviewed', 0, 0), \
                      ('92700000-0000-0000-0000-000000000012', 'local', 'zzlass-row', \
                       'Second term', 'zzlass content', '[]', 1, 'reviewed', 0, 0)"
                    .into(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed two independently matching terms");
        drop(writer);

        let token = runtime.authorize(Namespace::local()).expect("local token");
        let response = with_fts_deadline_advance_after_term(
            1,
            std::time::Duration::from_millis(2_100),
            KnowledgeHandlers::search(
                &runtime,
                &token,
                json!({"query": "zzmass zzlass", "rerank": false}),
                &vamana::new_shared(),
            ),
        )
        .await
        .expect("multi-term search");
        assert_eq!(response["candidate_provenance"]["lexical"], "matched");
        assert_eq!(response["total"], 2);
    }

    /// Companion pair for issue #1930 Amendment 2's phase-A overfetch/widen
    /// behavior. A term whose top bm25/rowid page is entirely status-
    /// ineligible must still surface its eligible rows once widening looks
    /// past that page — 30 `deprecated` rows are inserted first (lower
    /// rowids, so they sort first at equal bm25) and 3 `reviewed` rows
    /// inserted after (higher rowids). `fetch_limit=5` with a single real
    /// term gives `per_term_limit=5` and a first-round probe of `5*4=20`,
    /// which the 30 deprecated rows alone fill — round one must see zero
    /// eligible rows, forcing the widen arm to reach the 3 reviewed rows in
    /// round two (probe 80, corpus only has 33 total so phase A returns
    /// fewer than it asked for, correctly stopping further widening).
    #[tokio::test]
    async fn phase_b_widening_recovers_eligible_rows_behind_an_ineligible_top_page() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "WITH RECURSIVE x(n) AS ( \
                          VALUES(0) UNION ALL SELECT n + 1 FROM x WHERE n < 29 \
                      ) \
                      INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) \
                      SELECT \
                          printf('92000000-0000-0000-0000-%012d', x.n), \
                          'local', printf('zzwidenzz-dep-%02d', x.n), printf('Widen Dep %02d', x.n), \
                          'synthetic content about zzwidenzz only', '[]', NULL, 1, \
                          'deprecated', NULL, NULL, x.n, x.n, NULL \
                      FROM x"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed deprecated widen rows");
        writer
            .execute(SqlStatement {
                sql: "WITH RECURSIVE x(n) AS ( \
                          VALUES(0) UNION ALL SELECT n + 1 FROM x WHERE n < 2 \
                      ) \
                      INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) \
                      SELECT \
                          printf('92100000-0000-0000-0000-%012d', x.n), \
                          'local', printf('zzwidenzz-ok-%02d', x.n), printf('Widen Ok %02d', x.n), \
                          'synthetic content about zzwidenzz only', '[]', NULL, 1, \
                          'reviewed', NULL, NULL, 100 + x.n, 100 + x.n, NULL \
                      FROM x"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed reviewed widen rows");
        drop(writer);

        let outcome = fetch_fts_candidates(&runtime, "local", "zzwidenzz", None, &[], &[], 5)
            .await
            .expect("fetch must not error");

        assert!(outcome.timeout.is_none());
        assert_eq!(
            outcome.atoms.len(),
            3,
            "only the 3 reviewed rows are eligible; widening must have looked \
             past the all-deprecated first page to find them: {:?}",
            outcome
                .atoms
                .iter()
                .map(|a| a.slug.as_str())
                .collect::<Vec<_>>()
        );
        assert!(
            outcome
                .atoms
                .iter()
                .all(|a| a.slug.starts_with("zzwidenzz-ok-")),
            "no deprecated row may survive into the eligible set: {:?}",
            outcome
                .atoms
                .iter()
                .map(|a| a.slug.as_str())
                .collect::<Vec<_>>()
        );
    }

    /// Control for the widening test above: a term with genuinely fewer
    /// matches than `per_term_limit` (2 reviewed rows, cap 5) must return
    /// exactly those 2 without fabricating more. Phase A's first probe
    /// (`5*4=20`) already exceeds the corpus size for this term, so it
    /// returns short on round one and widening never triggers at all — this
    /// is what proves `phase_a_full` correctly detects exhaustion instead
    /// of retrying up to the ceiling.
    #[tokio::test]
    async fn phase_b_accepts_a_genuine_shortfall_without_widening() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) VALUES \
                      ('92200000-0000-0000-0000-000000000000', 'local', 'zzsparsezz-00', \
                       'Sparse 00', 'synthetic content about zzsparsezz only', '[]', NULL, 1, \
                       'reviewed', NULL, NULL, 0, 0, NULL), \
                      ('92200000-0000-0000-0000-000000000001', 'local', 'zzsparsezz-01', \
                       'Sparse 01', 'synthetic content about zzsparsezz only', '[]', NULL, 1, \
                       'reviewed', NULL, NULL, 1, 1, NULL)"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed sparse rows");
        drop(writer);

        let outcome = fetch_fts_candidates(&runtime, "local", "zzsparsezz", None, &[], &[], 5)
            .await
            .expect("fetch must not error");

        assert!(outcome.timeout.is_none());
        assert_eq!(
            outcome.atoms.len(),
            2,
            "a term with only 2 genuinely eligible matches must return exactly \
             those, not fabricate more via widening: {:?}",
            outcome
                .atoms
                .iter()
                .map(|a| a.slug.as_str())
                .collect::<Vec<_>>()
        );
    }

    /// Phase A carries no namespace predicate (it is index-only); the
    /// namespace check moves entirely to phase B's hydration query. Seed a
    /// matching row in another namespace and confirm it is hydrated out —
    /// never returned — even though phase A's rowid list spans both
    /// namespaces.
    #[tokio::test]
    async fn phase_a_cross_namespace_matches_are_hydrated_out() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) VALUES \
                      ('92300000-0000-0000-0000-000000000000', 'local', 'zzcrossns-local', \
                       'Cross NS Local', 'synthetic content about zzcrossns only', '[]', NULL, 1, \
                       'reviewed', NULL, NULL, 0, 0, NULL), \
                      ('92300000-0000-0000-0000-000000000001', 'other', 'zzcrossns-other', \
                       'Cross NS Other', 'synthetic content about zzcrossns only', '[]', NULL, 1, \
                       'reviewed', NULL, NULL, 1, 1, NULL)"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed cross-namespace rows");
        drop(writer);

        let outcome = fetch_fts_candidates(&runtime, "local", "zzcrossns", None, &[], &[], 10)
            .await
            .expect("fetch must not error");

        assert!(outcome.timeout.is_none());
        assert_eq!(
            outcome.atoms.len(),
            1,
            "only the local-namespace row is eligible: {:?}",
            outcome
                .atoms
                .iter()
                .map(|a| (a.slug.as_str(), a.namespace.as_str()))
                .collect::<Vec<_>>()
        );
        assert_eq!(outcome.atoms[0].namespace, "local");
        assert_eq!(outcome.atoms[0].slug, "zzcrossns-local");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    #[ignore = "manual 200000-row lexical namespace measurement"]
    async fn measure_cross_namespace_lexical_work() {
        async fn seed_namespace(
            runtime: &KhiveRuntime,
            ns: &str,
            id_prefix: &str,
            rows: i64,
            matching_rows: i64,
        ) {
            let access = runtime.sql();
            let mut writer = access.writer().await.expect("writer");
            writer
                .execute(SqlStatement {
                    sql: "WITH RECURSIVE seq(n) AS ( \
                              VALUES(0) UNION ALL SELECT n + 1 FROM seq WHERE n + 1 < ?3 \
                          ) \
                          INSERT INTO knowledge_atoms ( \
                              id, namespace, slug, name, content, tags, finalized, \
                              status, created_at, updated_at \
                          ) \
                          SELECT printf('%s-%012d', ?2, n), ?1, \
                                 printf('measurement-%06d', n), 'Measurement Row', \
                                 CASE WHEN n < ?4 THEN \
                                     'namespacechannel content with ordinary padding text' \
                                 ELSE 'unrelated content with ordinary padding text' END, \
                                 '[]', 1, 'reviewed', n, n FROM seq"
                        .into(),
                    params: vec![
                        SqlValue::Text(ns.into()),
                        SqlValue::Text(id_prefix.into()),
                        SqlValue::Integer(rows),
                        SqlValue::Integer(matching_rows),
                    ],
                    label: None,
                })
                .await
                .expect("seed namespace corpus");
        }

        for local_matches in [0, 3] {
            for foreign_present in [true, false] {
                let runtime = KhiveRuntime::memory().expect("in-memory runtime");
                if foreign_present {
                    seed_namespace(
                        &runtime,
                        "tenant-a",
                        "92500000-0000-0000-0000",
                        200_000,
                        200_000,
                    )
                    .await;
                }
                seed_namespace(
                    &runtime,
                    "tenant-b",
                    "92600000-0000-0000-0000",
                    10,
                    local_matches,
                )
                .await;

                for (mode, query) in [
                    ("single", "namespacechannel"),
                    ("multi", "namespacechannel absentchannel"),
                ] {
                    let start = std::time::Instant::now();
                    let outcome = khive_storage::scope_request_read_deadline(
                        lexical_stage_budget(),
                        fetch_fts_candidates(
                            &runtime,
                            "tenant-b",
                            query,
                            None,
                            &[],
                            &[],
                            CANDIDATE_POOL,
                        ),
                    )
                    .await
                    .expect("bounded lexical fetch");
                    let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
                    assert!(outcome
                        .atoms
                        .iter()
                        .all(|atom| atom.namespace == "tenant-b"));
                    println!(
                        "LEXICAL_NAMESPACE mode={mode} foreign_present={foreign_present} local_matches={local_matches} rows={} lexical_elapsed_ms={elapsed_ms:.3} lexical_timeout={}",
                        outcome.atoms.len(),
                        outcome.timeout.is_some(),
                    );
                }
            }
        }
    }

    /// Foreign FTS matches must not change the public candidate state or
    /// admit unrelated local rows. This retains the #2396 namespace boundary
    /// after removing the recent-row fallback.
    #[tokio::test]
    async fn empty_result_fallback_never_leaks_a_foreign_namespace_match() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) VALUES \
                      ('92400000-0000-0000-0000-000000000000', 'local', 'unrelated-local-atom', \
                       'Unrelated Local Atom', 'generic filler text with no special term', \
                       '[]', NULL, 1, 'reviewed', NULL, NULL, 0, 0, NULL), \
                      ('92400000-0000-0000-0000-000000000001', 'tenant-b', 'foreign-term-atom', \
                       'Foreign Term Atom', 'synthetic content about zzoraclezz only', '[]', NULL, 1, \
                       'reviewed', NULL, NULL, 1, 1, NULL)"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed oracle rows");
        drop(writer);

        let foreign_match =
            fetch_fts_candidates(&runtime, "local", "zzoraclezz", None, &[], &[], 5)
                .await
                .expect("fetch must not error");
        let no_match =
            fetch_fts_candidates(&runtime, "local", "zzoracleabsentzz", None, &[], &[], 5)
                .await
                .expect("fetch must not error");

        assert!(foreign_match.timeout.is_none());
        assert!(no_match.timeout.is_none());
        assert_eq!(foreign_match.state, LexicalCandidateState::NoMatch);
        assert_eq!(foreign_match.state, no_match.state);
        let foreign_slugs: Vec<&str> = foreign_match
            .atoms
            .iter()
            .map(|a| a.slug.as_str())
            .collect();
        let absent_slugs: Vec<&str> = no_match.atoms.iter().map(|a| a.slug.as_str()).collect();
        assert_eq!(
            foreign_slugs, absent_slugs,
            "a term matching only in another namespace must produce the exact \
             same response as a term matching nowhere at all — any \
             difference is a cross-namespace existence oracle"
        );
        assert!(
            foreign_slugs.is_empty(),
            "unrelated recent rows are not candidates"
        );
    }

    /// A real indexed match survives, without unrelated recent rows.
    #[tokio::test]
    async fn empty_result_fallback_control_index_match_skips_fallback() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) VALUES \
                      ('92400000-0000-0000-0000-000000000002', 'local', 'indexed-term-atom', \
                       'Indexed Term Atom', 'synthetic content about zzindexedzz only', '[]', NULL, 1, \
                       'reviewed', NULL, NULL, 0, 0, NULL), \
                      ('92400000-0000-0000-0000-000000000003', 'local', 'unrelated-recent-atom', \
                       'Unrelated Recent Atom', 'generic filler text with no special term', '[]', NULL, 1, \
                       'reviewed', NULL, NULL, 1, 1, NULL)"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed control rows");
        drop(writer);

        let outcome = fetch_fts_candidates(&runtime, "local", "zzindexedzz", None, &[], &[], 5)
            .await
            .expect("fetch must not error");

        assert!(outcome.timeout.is_none());
        assert_eq!(
            outcome.atoms.len(),
            1,
            "only the indexed match may be returned, never the unrelated \
             fallback-only row: {:?}",
            outcome
                .atoms
                .iter()
                .map(|a| a.slug.as_str())
                .collect::<Vec<_>>()
        );
        assert_eq!(outcome.atoms[0].slug, "indexed-term-atom");
        assert_eq!(outcome.state, LexicalCandidateState::Matched);
    }

    #[tokio::test]
    async fn filtered_candidate_state_is_stable_behind_a_foreign_ceiling_prefix() {
        let mut public_responses = Vec::new();
        for foreign_prefix in [false, true] {
            let runtime = KhiveRuntime::memory().expect("in-memory runtime");
            let access = runtime.sql();
            let mut writer = access.writer().await.expect("writer");
            if foreign_prefix {
                writer
                    .execute(SqlStatement {
                        sql: "WITH RECURSIVE x(n) AS ( \
                                  VALUES(1) UNION ALL SELECT n + 1 FROM x WHERE n < 20 \
                              ) \
                              INSERT INTO knowledge_atoms ( \
                                  rowid, id, namespace, slug, name, content, tags, finalized, \
                                  status, created_at, updated_at \
                              ) \
                              SELECT x.n, printf('92710000-0000-0000-0000-%012d', x.n), \
                                  'foreign', printf('foreign-prefix-%02d', x.n), 'Foreign Match', \
                                  'zzfilteredceilingzz', '[]', 1, 'reviewed', 0, 0 \
                              FROM x"
                            .into(),
                        params: Vec::new(),
                        label: None,
                    })
                    .await
                    .expect("seed foreign ceiling prefix");
            }
            writer
                .execute(SqlStatement {
                    sql: "INSERT INTO knowledge_atoms ( \
                              rowid, id, namespace, slug, name, content, tags, finalized, \
                              status, created_at, updated_at \
                          ) VALUES ( \
                              21, '92710000-0000-0000-0000-000000000021', 'local', \
                              'local-filtered-match', 'Local Filtered Match', \
                              'zzfilteredceilingzz', '[]', 0, 'draft', 0, 0 \
                          )"
                    .into(),
                    params: Vec::new(),
                    label: None,
                })
                .await
                .expect("seed identical local filtered match");
            drop(writer);

            let mut reader = access.reader().await.expect("reader");
            let rows = reader
                .query_all(phase_a_rowids_statement("\"zzfilteredceilingzz\"", 20))
                .await
                .expect("inspect ceiling window");
            let rowids: Vec<_> = rows
                .iter()
                .filter_map(|row| row_i64(row, "rowid"))
                .collect();
            if foreign_prefix {
                assert_eq!(rowids, (1..=20).collect::<Vec<i64>>());
            } else {
                assert_eq!(rowids, [21]);
            }
            drop(reader);

            let token = runtime.authorize(Namespace::local()).expect("local token");
            let ann = vamana::new_shared();
            let response = with_phase_a_widen_ceiling_override(20, async {
                KnowledgeHandlers::search(
                    &runtime,
                    &token,
                    json!({"query": "zzfilteredceilingzz", "rerank": false}),
                    &ann,
                )
                .await
            })
            .await
            .expect("public filtered search");
            assert_eq!(
                response,
                json!({
                    "results": [], "total": 0,
                    "candidate_provenance": {"lexical": "filtered", "fallback": "none", "terms_truncated": false},
                }),
                "foreign matches must not change the same local filtered result: {foreign_prefix}"
            );
            public_responses
                .push(serde_json::to_vec(&response).expect("serialize public response"));
        }
        assert_eq!(public_responses[0], public_responses[1]);
    }

    /// Issue #2396 fix 2: when phase A's widening reaches the ceiling and the
    /// eligible set is still short, more than `ceiling` ineligible top-ranked
    /// rows must not be allowed to hide an eligible row further down the
    /// bm25 ranking than phase A ever probed. The ceiling is overridden down
    /// to 20 so the fixture can stay small: 20 `deprecated` rows (lower
    /// rowids, so they sort first at equal bm25) exactly fill the first — and
    /// at this override, only — probe window, so `eligible_now` is empty
    /// right at the ceiling. The eligibility-scoped fallback query must then
    /// recover the 2 `reviewed` rows seeded after them (higher rowids, never
    /// inside the ceiling-bounded window). The ordinary (non-ceiling)
    /// widening path and its shortfall control are covered by
    /// `phase_b_widening_recovers_eligible_rows_behind_an_ineligible_top_page`
    /// and `phase_b_accepts_a_genuine_shortfall_without_widening` above.
    #[tokio::test]
    async fn phase_b_ceiling_exhaustion_recovers_eligible_row_via_scoped_fallback() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "WITH RECURSIVE x(n) AS ( \
                          VALUES(0) UNION ALL SELECT n + 1 FROM x WHERE n < 19 \
                      ) \
                      INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) \
                      SELECT \
                          printf('92500000-0000-0000-0000-%012d', x.n), \
                          'local', printf('zzceilingzz-dep-%02d', x.n), printf('Ceiling Dep %02d', x.n), \
                          'synthetic content about zzceilingzz only', '[]', NULL, 1, \
                          'deprecated', NULL, NULL, x.n, x.n, NULL \
                      FROM x"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed deprecated ceiling rows");
        writer
            .execute(SqlStatement {
                sql: "WITH RECURSIVE x(n) AS ( \
                          VALUES(0) UNION ALL SELECT n + 1 FROM x WHERE n < 1 \
                      ) \
                      INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) \
                      SELECT \
                          printf('92510000-0000-0000-0000-%012d', x.n), \
                          'local', printf('zzceilingzz-ok-%02d', x.n), printf('Ceiling Ok %02d', x.n), \
                          'synthetic content about zzceilingzz only', '[]', NULL, 1, \
                          'reviewed', NULL, NULL, 100 + x.n, 100 + x.n, NULL \
                      FROM x"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed reviewed ceiling rows");
        drop(writer);

        let outcome = with_phase_a_widen_ceiling_override(20, async {
            fetch_fts_candidates(&runtime, "local", "zzceilingzz", None, &[], &[], 5).await
        })
        .await
        .expect("fetch must not error");

        assert!(outcome.timeout.is_none());
        assert_eq!(
            outcome.atoms.len(),
            2,
            "the 2 reviewed rows sit beyond the ceiling-bounded phase-A \
             window; only the eligibility-scoped fallback query can recover \
             them: {:?}",
            outcome
                .atoms
                .iter()
                .map(|a| a.slug.as_str())
                .collect::<Vec<_>>()
        );
        assert!(
            outcome
                .atoms
                .iter()
                .all(|a| a.slug.starts_with("zzceilingzz-ok-")),
            "no deprecated row may survive into the eligible set: {:?}",
            outcome
                .atoms
                .iter()
                .map(|a| a.slug.as_str())
                .collect::<Vec<_>>()
        );
    }

    /// A member-token-sizing timeout returns no measurements, never a
    /// placeholder zero that could be admitted as a free fold candidate.
    #[tokio::test]
    async fn member_token_sizes_report_timeout_instead_of_a_measured_zero() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) VALUES ( \
                          '92600000-0000-0000-0000-000000000000', 'local', 'sizing-member-atom', \
                          'Sizing Member Atom', \
                          'enough body content to price a non-zero token size for the owning domain once member sizing actually runs to completion', \
                          '[]', NULL, 1, 'reviewed', NULL, NULL, 0, 0, NULL)"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed member atom");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_domains ( \
                          id, namespace, slug, name, description, tags, members, status, \
                          created_at, updated_at, deleted_at \
                      ) VALUES ( \
                          '92600000-0000-0000-0000-000000000001', 'local', 'sizing-domain', \
                          'Sizing Domain', NULL, '[]', '[\"sizing-member-atom\"]', 'reviewed', \
                          0, 0, NULL)"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed domain");
        drop(writer);

        let domain_ids = vec!["92600000-0000-0000-0000-000000000001".to_string()];

        let (degraded_sizes, timed_out) = khive_storage::scope_request_read_deadline(
            std::time::Duration::ZERO,
            load_domain_member_token_sizes(&runtime, "local", &domain_ids),
        )
        .await
        .expect("an expired read deadline must degrade, not error");
        assert!(
            timed_out,
            "an expired read deadline must be reported as unmeasured"
        );
        assert!(
            degraded_sizes.is_empty(),
            "a timed-out batch must not contain fabricated measurements"
        );

        let (healthy_sizes, healthy_timed_out) =
            load_domain_member_token_sizes(&runtime, "local", &domain_ids)
                .await
                .expect("undeadlined lookup must succeed");
        assert!(!healthy_timed_out);
        assert!(
            healthy_sizes
                .get(&domain_ids[0])
                .is_some_and(|sizing| sizing.tokens > 0 && sizing.live_members == 1),
            "control: without a deadline the lookup measures the real member \
             body cost; got {healthy_sizes:?}"
        );
    }

    /// Issue #2396 fix 4: the lexical-stage-budget override rides a
    /// `tokio::task_local!`, so it is scoped to the task it wraps only.
    /// Two concurrent tasks — one scoped to an override, one with none —
    /// must observe different budgets; the prior process-global `AtomicU64`
    /// override could not guarantee this; a task with no override of its own
    /// could observe whatever value another concurrently running test last
    /// stored.
    #[tokio::test]
    async fn lexical_stage_budget_override_does_not_leak_across_concurrent_tasks() {
        let with_override = tokio::spawn(with_lexical_stage_budget_override_ms(50, async {
            tokio::task::yield_now().await;
            lexical_stage_budget()
        }));
        let without_override = tokio::spawn(async {
            tokio::task::yield_now().await;
            lexical_stage_budget()
        });

        let overridden = with_override.await.expect("task must not panic");
        let baseline = without_override.await.expect("task must not panic");

        assert_eq!(overridden, std::time::Duration::from_millis(50));
        assert_eq!(
            baseline,
            std::time::Duration::from_millis(LEXICAL_STAGE_BUDGET_MS),
            "a concurrently running task with no override of its own must \
             never observe another task's override; got {baseline:?}"
        );
    }

    /// Issue: `MIN_TERM_LEN=3` drops every token of a query like "AI" before
    /// FTS ever sees it, and the trigram tokenizer cannot match a phrase that
    /// short either, so the atom was unreachable without ANN. The indexed
    /// slug probe in the lexical stage must restore discoverability for both the
    /// atom's exact-case name and a case-insensitive spelling, while a query
    /// that matches no slug at all must still report a genuine miss.
    #[tokio::test]
    async fn short_exact_name_is_discoverable_without_ann() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        {
            let access = runtime.sql();
            let mut writer = access.writer().await.expect("writer");
            writer
                .execute(SqlStatement {
                    sql: "INSERT INTO knowledge_atoms ( \
                              id, namespace, slug, name, content, tags, properties, finalized, \
                              status, source_uri, source_type, created_at, updated_at, deleted_at \
                          ) VALUES ( \
                              '93000000-0000-0000-0000-000000000001', 'local', \
                              'ai', 'AI', \
                              'artificial intelligence overview content for the corpus', '[]', \
                              NULL, 1, 'reviewed', NULL, NULL, 1000, 1000, NULL \
                          )"
                    .to_string(),
                    params: Vec::new(),
                    label: None,
                })
                .await
                .expect("seed short-name atom");
        }

        let token = runtime.authorize(Namespace::local()).expect("local token");
        let ann = vamana::new_shared();

        let exact_case = KnowledgeHandlers::search(
            &runtime,
            &token,
            json!({"query": "AI", "rerank": false}),
            &ann,
        )
        .await
        .expect("exact-case short-name search must not error");
        assert_eq!(exact_case["total"], 1);
        assert_eq!(exact_case["results"][0]["slug"], "ai");
        assert_eq!(exact_case["candidate_provenance"]["lexical"], "exact_name");
        assert_eq!(exact_case["candidate_provenance"]["fallback"], "none");
        assert_eq!(
            exact_case["results"][0]["score_provenance"]["sources"],
            json!(["lexical"])
        );
        assert!(exact_case["results"][0]["score"].as_f64().unwrap() > 0.0);

        let lower_case = KnowledgeHandlers::search(
            &runtime,
            &token,
            json!({"query": "ai", "rerank": false}),
            &ann,
        )
        .await
        .expect("lower-case short-name search must not error");
        assert_eq!(lower_case["total"], 1);
        assert_eq!(lower_case["results"][0]["slug"], "ai");
        assert_eq!(lower_case["candidate_provenance"]["lexical"], "exact_name");

        let miss = KnowledgeHandlers::search(
            &runtime,
            &token,
            json!({"query": "zz", "rerank": false}),
            &ann,
        )
        .await
        .expect("non-matching short query must not error");
        assert_eq!(miss["total"], 0);
        assert_eq!(miss["candidate_provenance"]["lexical"], "no_match");

        // A role prefix is scored, never searched: it must not hide the probe.
        let role_qualified = KnowledgeHandlers::search(
            &runtime,
            &token,
            json!({"query": "AI", "role": "researcher", "rerank": false}),
            &ann,
        )
        .await
        .expect("role-qualified short-name search must not error");
        assert_eq!(role_qualified["total"], 1);
        assert_eq!(role_qualified["results"][0]["slug"], "ai");
        assert_eq!(
            role_qualified["candidate_provenance"]["lexical"],
            "exact_name"
        );
    }

    /// A deadline that expires inside the exact-name probe is a lexical
    /// timeout, not a miss: the caller degrades the response on `TimedOut`
    /// and would otherwise reach the final active-read check and error.
    #[tokio::test]
    async fn exact_name_probe_reports_an_expired_deadline_as_a_timeout() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let sql = runtime.sql();
        let mut reader = sql.reader().await.expect("reader before deadline");
        let configured = lexical_stage_budget();

        let expired =
            khive_storage::scope_request_read_deadline(std::time::Duration::ZERO, async {
                let mut stage =
                    LexicalStage::new(LexicalPass::Full, tokio::time::Instant::now(), configured);
                let outcome = fetch_exact_name_candidate(
                    reader.as_mut(),
                    "local",
                    "AI",
                    None,
                    &[],
                    &[],
                    &mut stage,
                )
                .await;
                let timeout = stage.timeout.expect("exact probe captures timeout details");
                assert_eq!(timeout.phase, LexicalPhase::ExactNameProbe);
                assert_eq!(timeout.effective_budget_ms, 0);
                outcome
            })
            .await;
        assert!(
            matches!(expired, Ok(ExactNameProbe::TimedOut)),
            "an expired read deadline must surface as TimedOut, never as a \
             miss; got {expired:?}"
        );

        let mut stage =
            LexicalStage::new(LexicalPass::Full, tokio::time::Instant::now(), configured);
        let healthy =
            fetch_exact_name_candidate(reader.as_mut(), "local", "AI", None, &[], &[], &mut stage)
                .await
                .expect("undeadlined probe must succeed");
        assert!(
            matches!(healthy, ExactNameProbe::Miss),
            "control: without a deadline an unseeded name is a plain miss; got {healthy:?}"
        );
        assert!(stage.timeout.is_none());
    }

    /// The indexed exact-name probe must use the unique `(namespace, slug)`
    /// index, never a full-namespace scan on `name` — no such index exists.
    /// Same `EXPLAIN QUERY PLAN` style as
    /// `crud::get_prefix_query_plan_uses_primary_key_range_seeks`.
    #[tokio::test]
    async fn exact_name_probe_query_plan_uses_slug_index() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let mut reader = runtime.sql().reader().await.expect("exact-name reader");
        let rows = reader
            .explain(exact_name_statement(
                "local",
                "ai",
                Some("atom"),
                &[],
                &["draft", "deprecated"],
            ))
            .await
            .expect("explain exact-name probe");
        let details: Vec<String> = rows
            .iter()
            .filter_map(|row| match row.get("detail") {
                Some(SqlValue::Text(detail)) => Some(detail.clone()),
                _ => None,
            })
            .collect();
        assert!(
            details.iter().any(|d| d.contains("SEARCH knowledge_atoms")
                && d.contains("USING INDEX")
                && d.contains("namespace=? AND slug=?")),
            "exact-name probe must use an index seek, not a table scan: {details:?}"
        );
        assert!(
            !details.iter().any(|d| d.contains("SCAN knowledge_atoms")),
            "exact-name probe must never full-scan knowledge_atoms: {details:?}"
        );
    }

    #[tokio::test]
    async fn short_exact_name_probe_respects_namespace_status_type_and_soft_deletion() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let sql = runtime.sql();
        let mut writer = sql.writer().await.unwrap();
        for (index, (ns, slug, name, status, tags, deleted)) in [
            ("local", "ai", "AI", "draft", "[]", SqlValue::Null),
            ("tenant-b", "ai", "AI", "reviewed", "[]", SqlValue::Null),
            (
                "local",
                "ml",
                "ML",
                "reviewed",
                "[\"type:domain\"]",
                SqlValue::Null,
            ),
            (
                "local",
                "zz",
                "ZZ",
                "reviewed",
                "[]",
                SqlValue::Integer(1000),
            ),
            (
                "local",
                "custom-name",
                "UI",
                "reviewed",
                "[]",
                SqlValue::Null,
            ),
        ]
        .into_iter()
        .enumerate()
        {
            writer.execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms (id, namespace, slug, name, content, tags, finalized, status, created_at, updated_at, deleted_at) \
                      VALUES (?1, ?2, ?3, ?4, 'unrelated overview', ?5, 1, ?6, 0, 0, ?7)".into(),
                params: vec![SqlValue::Text(format!("93000000-0000-0000-0001-{index:012}")), SqlValue::Text(ns.into()), SqlValue::Text(slug.into()), SqlValue::Text(name.into()), SqlValue::Text(tags.into()), SqlValue::Text(status.into()), deleted],
                label: None,
            }).await.unwrap();
        }
        drop(writer);
        for (ns, query, kind, statuses, expected_state, expected_count) in [
            (
                "local",
                "AI",
                Some("atom"),
                vec![],
                LexicalCandidateState::Filtered,
                0,
            ),
            (
                "local",
                "AI",
                Some("atom"),
                vec!["draft".to_string()],
                LexicalCandidateState::ExactName,
                1,
            ),
            (
                "tenant-b",
                "AI",
                Some("atom"),
                vec![],
                LexicalCandidateState::ExactName,
                1,
            ),
            (
                "tenant-c",
                "AI",
                Some("atom"),
                vec![],
                LexicalCandidateState::NoMatch,
                0,
            ),
            (
                "local",
                "ML",
                Some("atom"),
                vec![],
                LexicalCandidateState::Filtered,
                0,
            ),
            (
                "local",
                "ML",
                Some("domain"),
                vec![],
                LexicalCandidateState::ExactName,
                1,
            ),
            (
                "local",
                "ZZ",
                Some("atom"),
                vec![],
                LexicalCandidateState::NoMatch,
                0,
            ),
            (
                "local",
                "UI",
                Some("atom"),
                vec![],
                LexicalCandidateState::NoMatch,
                0,
            ),
        ] {
            let outcome = fetch_fts_candidates(
                &runtime,
                ns,
                query,
                kind,
                &statuses,
                &["draft", "deprecated"],
                5,
            )
            .await
            .unwrap();
            assert!(outcome.timeout.is_none());
            assert_eq!(
                outcome.state, expected_state,
                "{ns}/{query}/{kind:?}/{statuses:?}"
            );
            assert_eq!(outcome.atoms.len(), expected_count);
            assert!(outcome.atoms.iter().all(|atom| atom.namespace == ns));
        }
    }

    #[test]
    fn fts_candidate_expression_recalls_non_contiguous_terms() {
        assert_eq!(
            fts5_candidate_terms("alpha beta alpha and").join(" OR "),
            "\"alpha\" OR \"alphas\" OR \"beta\" OR \"betas\""
        );
        assert_eq!(
            fts5_candidate_terms("RAG").join(" OR "),
            "\"rag\" OR \"rags\""
        );
        assert_eq!(
            fts5_candidate_terms("the and").join(" OR "),
            "\"the and\"",
            "stop-only queries retain the exact-phrase fallback"
        );
    }

    #[test]
    fn rrf_fusion_preserves_per_hit_score_sources_and_ann_fallback() {
        let mut hybrid = vec![make_hit("shared", Some("reviewed"), 0.8)];
        let ann = vec![make_ann_hit("shared", Some("reviewed"), 0.9)];
        fuse_ann_hits(&mut hybrid, &ann, 0.0);
        assert_eq!(hybrid.len(), 1);
        assert_eq!(
            hybrid[0].provenance.to_json()["sources"],
            json!(["lexical", "ann"])
        );
        assert_eq!(candidate_fallback(&hybrid), "none");

        let mut ann_only = Vec::new();
        fuse_ann_hits(
            &mut ann_only,
            &[make_ann_hit("semantic", Some("reviewed"), 0.9)],
            0.0,
        );
        assert_eq!(ann_only.len(), 1);
        assert_eq!(ann_only[0].provenance.to_json()["sources"], json!(["ann"]));
        assert_eq!(candidate_fallback(&ann_only), "ann");
        assert_eq!(
            ann_only[0].provenance.to_json(),
            json!({
                "sources": ["ann"],
                "embedding_rerank": false,
                "normalization": "s_over_s_plus_1",
                "calibrated": false,
            })
        );

        let lexical_only = vec![make_hit("lexical", Some("reviewed"), 0.7)];
        assert_eq!(
            lexical_only[0].provenance.to_json()["sources"],
            json!(["lexical"])
        );
        assert_eq!(candidate_fallback(&lexical_only), "none");
    }

    #[tokio::test]
    async fn embedding_rerank_provenance_is_true_when_rerank_runs() {
        let (runtime, _, fail_query) = rt_with_role_aware_recording_embedder();
        fail_query.store(true, std::sync::atomic::Ordering::SeqCst);
        {
            let access = runtime.sql();
            let mut writer = access.writer().await.expect("writer");
            writer
                .execute(SqlStatement {
                    sql: "INSERT INTO knowledge_atoms ( \
                              id, namespace, slug, name, content, tags, properties, finalized, \
                              status, source_uri, source_type, created_at, updated_at, deleted_at \
                          ) VALUES ( \
                              '94000000-0000-0000-0000-000000000001', 'local', \
                              'rerank-target', 'Rerank Target', \
                              'content that the lexical stage must match for the rerank pass', \
                              '[]', NULL, 1, 'reviewed', NULL, NULL, 1000, 1000, NULL \
                          )"
                    .to_string(),
                    params: Vec::new(),
                    label: None,
                })
                .await
                .expect("seed rerank target atom");
        }

        let token = runtime.authorize(Namespace::local()).expect("local token");
        let ann = vamana::new_shared();
        let out = KnowledgeHandlers::search(
            &runtime,
            &token,
            json!({"query": "rerank target content", "rerank": true}),
            &ann,
        )
        .await
        .expect("rerank-enabled search must not error");

        assert_eq!(out["total"], 1);
        assert_eq!(
            out["results"][0]["score_provenance"]["embedding_rerank"], true,
            "a successful embedding rerank must record embedding_rerank: true; got {out:?}"
        );
    }

    #[test]
    fn exact_name_provenance_survives_merge_without_hiding_timeouts() {
        use LexicalCandidateState::{ExactName, Matched, NoMatch, PartialTimeout, TimedOut};
        for (states, expected) in [
            (vec![NoMatch, ExactName], ExactName),
            (vec![ExactName, Matched], Matched),
            (vec![ExactName, TimedOut], PartialTimeout),
            (vec![ExactName, PartialTimeout], PartialTimeout),
        ] {
            assert_eq!(LexicalCandidateState::merge(&states), expected);
        }
    }

    #[tokio::test]
    async fn missing_ann_hydration_is_dropped_and_reported() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let mut hits = vec![ScoredHit {
            id: "00000000-0000-0000-0000-000000001763".to_string(),
            slug: String::new(),
            name: String::new(),
            content: None,
            tags: None,
            finalized: false,
            is_domain: false,
            status: None,
            score: 0.8,
            provenance: ScoreProvenance::ann(),
        }];

        let failures = hydrate_empty_hits(&runtime, "local", &mut hits).await;
        assert_eq!(failures, 1);
        assert!(hits.is_empty(), "unhydrated shells must never be returned");

        let mut response = json!({"results": [], "total": 0});
        attach_hydration_degradation(&mut response, failures);
        assert_eq!(response["degraded"]["hydration_failures"], 1);
    }

    #[test]
    fn zero_hydration_failures_do_not_change_the_response() {
        let mut response = json!({"results": [], "total": 0});
        attach_hydration_degradation(&mut response, 0);
        assert!(response.get("degraded").is_none());
    }

    #[test]
    fn hydration_degradation_preserves_existing_diagnostics() {
        let mut response = json!({
            "results": [],
            "total": 0,
            "degraded": {
                "reason": "ann_unavailable",
                "cache_safe": false,
            }
        });
        attach_hydration_degradation(&mut response, 7);
        assert_eq!(response["degraded"]["reason"], "ann_unavailable");
        assert_eq!(response["degraded"]["cache_safe"], false);
        assert_eq!(response["degraded"]["hydration_failures"], 7);
    }

    #[tokio::test]
    async fn hydration_chunks_candidate_sets_above_sqlite_bind_ceiling() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        {
            let access = runtime.sql();
            let mut writer = access.writer().await.expect("writer");
            writer
                .execute(SqlStatement {
                    sql: "WITH RECURSIVE x(n) AS ( \
                              VALUES(0) UNION ALL SELECT n + 1 FROM x WHERE n < 20 \
                          ), y(n) AS ( \
                              VALUES(0) UNION ALL SELECT n + 1 FROM y WHERE n < 49 \
                          ) \
                          INSERT INTO knowledge_atoms ( \
                              id, namespace, slug, name, content, tags, properties, finalized, \
                              status, source_uri, source_type, created_at, updated_at, deleted_at \
                          ) \
                          SELECT \
                              printf('70000000-0000-0000-0000-%012d', x.n * 50 + y.n), \
                              'local', printf('hydrate-%04d', x.n * 50 + y.n), \
                              printf('Hydrate %04d', x.n * 50 + y.n), 'hydration content', \
                              '[]', NULL, 1, 'reviewed', NULL, NULL, \
                              x.n * 50 + y.n, x.n * 50 + y.n, NULL \
                          FROM x CROSS JOIN y WHERE x.n * 50 + y.n < 1005"
                        .to_string(),
                    params: Vec::new(),
                    label: None,
                })
                .await
                .expect("seed hydration rows");
        }

        let mut hits: Vec<ScoredHit> = (0..1005)
            .map(|i| ScoredHit {
                id: format!("70000000-0000-0000-0000-{i:012}"),
                slug: String::new(),
                name: String::new(),
                content: None,
                tags: None,
                finalized: false,
                is_domain: false,
                status: None,
                score: 1.0,
                provenance: ScoreProvenance::ann(),
            })
            .collect();

        let failures = hydrate_empty_hits(&runtime, "local", &mut hits).await;
        assert_eq!(failures, 0);
        assert_eq!(hits.len(), 1005);
        assert!(hits.iter().all(|hit| hit.slug.starts_with("hydrate-")));
    }

    /// Pins the production plan measured on the live store (179,809-row
    /// `knowledge_atoms`, no `sqlite_stat1`): with 250 literal ids and no
    /// `ANALYZE`, the planner must pick the primary-key auto-index, never a
    /// namespace index. A scratch, statistics-free database reproduces the
    /// same wrong-index choice the live store made, because the planner's
    /// default no-statistics guess (an indexed equality is ~10 rows) is what
    /// drove the original defect, not data volume.
    #[tokio::test]
    async fn hydrate_atoms_statement_plan_uses_primary_key_not_namespace_index() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let ids: Vec<String> = (0..250)
            .map(|i| format!("aaaaaaaa-0000-0000-0000-{i:012}"))
            .collect();

        let mut reader = runtime.sql().reader().await.expect("plan reader");
        let rows = reader
            .explain(hydrate_atoms_statement("local", &ids))
            .await
            .expect("explain atom hydration statement");
        let details: Vec<String> = rows
            .iter()
            .filter_map(|row| match row.get("detail") {
                Some(SqlValue::Text(detail)) => Some(detail.clone()),
                _ => None,
            })
            .collect();

        assert!(
            details
                .iter()
                .any(|detail| detail.contains("USING INDEX sqlite_autoindex_knowledge_atoms_1")),
            "atom hydration must seek the primary key: {details:?}"
        );
        assert!(
            !details
                .iter()
                .any(|detail| detail.contains("idx_knowledge_atoms_ns")),
            "atom hydration must not fall back to a namespace index: {details:?}"
        );
    }

    /// Domains twin of the atoms plan-pin above — same shape, same reason
    /// (`knowledge_domains` also carries a namespace index that the
    /// no-statistics planner would otherwise prefer).
    #[tokio::test]
    async fn hydrate_domains_statement_plan_uses_primary_key_not_namespace_index() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let ids: Vec<String> = (0..250)
            .map(|i| format!("bbbbbbbb-0000-0000-0000-{i:012}"))
            .collect();

        let mut reader = runtime.sql().reader().await.expect("plan reader");
        let rows = reader
            .explain(hydrate_domains_statement("local", &ids))
            .await
            .expect("explain domain hydration statement");
        let details: Vec<String> = rows
            .iter()
            .filter_map(|row| match row.get("detail") {
                Some(SqlValue::Text(detail)) => Some(detail.clone()),
                _ => None,
            })
            .collect();

        assert!(
            details.iter().any(|detail| {
                detail.contains("USING INDEX sqlite_autoindex_knowledge_domains_1")
            }),
            "domain hydration must seek the primary key: {details:?}"
        );
        assert!(
            !details
                .iter()
                .any(|detail| detail.contains("idx_knowledge_domains_ns")),
            "domain hydration must not fall back to a namespace index: {details:?}"
        );
    }

    /// Issue #2396 fix 5, same plan-pin shape as the two tests above applied
    /// to the lexical phase-B hydration statement: at `HYDRATION_ID_CHUNK`
    /// (900) rowids, the no-statistics planner must seek the integer primary
    /// key, never fall back to `idx_knowledge_atoms_ns`.
    #[tokio::test]
    async fn phase_b_hydration_statement_plan_uses_primary_key_not_namespace_index() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let rowids: Vec<i64> = (1..=HYDRATION_ID_CHUNK as i64).collect();

        let mut reader = runtime.sql().reader().await.expect("plan reader");
        let rows = reader
            .explain(phase_b_hydration_statement("local", &rowids, &[], &[], ""))
            .await
            .expect("explain phase-b hydration statement");
        let details: Vec<String> = rows
            .iter()
            .filter_map(|row| match row.get("detail") {
                Some(SqlValue::Text(detail)) => Some(detail.clone()),
                _ => None,
            })
            .collect();

        assert!(
            details
                .iter()
                .any(|detail| detail.contains("USING INTEGER PRIMARY KEY")),
            "phase-b hydration must seek the rowid primary key: {details:?}"
        );
        assert!(
            !details
                .iter()
                .any(|detail| detail.contains("idx_knowledge_atoms_ns")),
            "phase-b hydration must not fall back to a namespace index: {details:?}"
        );
    }

    /// Functional companion to the plan-pin tests above: the primary-key-first
    /// rewrite must not weaken namespace scoping. Seed atoms in two
    /// namespaces, hydrate ids drawn from both against a single namespace,
    /// and confirm the other namespace's row never comes back.
    #[tokio::test]
    async fn hydrate_atoms_statement_still_scopes_by_namespace() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms ( \
                          id, namespace, slug, name, content, tags, properties, finalized, \
                          status, source_uri, source_type, created_at, updated_at, deleted_at \
                      ) VALUES \
                      ('90000000-0000-0000-0000-000000000001', 'local', 'local-one', \
                       'Local One', 'local content', '[]', NULL, 1, 'reviewed', NULL, NULL, \
                       1, 1, NULL), \
                      ('90000000-0000-0000-0000-000000000002', 'local', 'local-two', \
                       'Local Two', 'local content', '[]', NULL, 1, 'reviewed', NULL, NULL, \
                       2, 2, NULL), \
                      ('90000000-0000-0000-0000-000000000003', 'other', 'other-one', \
                       'Other One', 'other content', '[]', NULL, 1, 'reviewed', NULL, NULL, \
                       3, 3, NULL)"
                    .to_string(),
                params: Vec::new(),
                label: None,
            })
            .await
            .expect("seed cross-namespace atoms");
        drop(writer);

        let mut hits: Vec<ScoredHit> = [
            "90000000-0000-0000-0000-000000000001",
            "90000000-0000-0000-0000-000000000002",
            "90000000-0000-0000-0000-000000000003",
        ]
        .iter()
        .map(|id| ScoredHit {
            id: id.to_string(),
            slug: String::new(),
            name: String::new(),
            content: None,
            tags: None,
            finalized: false,
            is_domain: false,
            status: None,
            score: 1.0,
            provenance: ScoreProvenance::ann(),
        })
        .collect();

        let failures = hydrate_empty_hits(&runtime, "local", &mut hits).await;
        assert_eq!(
            failures, 1,
            "the other-namespace row must be reported as an unhydrated candidate"
        );
        assert_eq!(hits.len(), 2, "only the local-namespace rows may hydrate");
        assert!(
            hits.iter()
                .all(|hit| hit.id != "90000000-0000-0000-0000-000000000003"),
            "the other-namespace row must never be returned: {:?}",
            hits.iter().map(|h| &h.id).collect::<Vec<_>>()
        );
        assert!(hits.iter().any(|hit| hit.slug == "local-one"));
        assert!(hits.iter().any(|hit| hit.slug == "local-two"));
    }

    // ── embed-intent regression ───────────────────────────────────────────────
    // Guard that the shared ANN candidate runner and the compose KG-blend gate
    // use the query-intent embedding call, not the generic
    // `runtime.embed(...)`. Uses include_str! so the assertion runs on the
    // actual source bytes, but splits the needle to avoid matching the
    // needle itself in test source.
    #[test]
    fn knowledge_ann_query_paths_use_query_intent_embed() {
        let src = include_str!("search.rs");
        // Build needle at runtime to avoid self-match in include_str.
        let generic_needle: String = [".embed(", "raw_query)"].concat();
        let generic_borrowed_needle: String = [".embed(", "&raw_query)"].concat();
        let generic_count = src
            .lines()
            // Skip lines that are part of this test body (contain "concat" or "needle").
            .filter(|l| !l.contains("concat") && !l.contains("needle"))
            .filter(|l| l.contains(&generic_needle) || l.contains(&generic_borrowed_needle))
            .count();
        assert_eq!(
            generic_count, 0,
            "ANN query paths must not call generic {generic_needle}; \
             found {generic_count} occurrence(s) — use embed_query instead"
        );

        // Positive check (#2307): the assertion above only proves the generic
        // path is *absent* — a mutation that replaced every production
        // `embed_query` call with a different method entirely (e.g.
        // `embed_document`) would still pass it, since that mutation never
        // introduces the generic-embed needle either. Count the query-intent
        // call sites directly so a silent removal (or mutation-away) of one
        // is caught: the shared ANN candidate runner and `compose`'s
        // KG-blend gate are the only two production call sites.
        let query_intent_needle: String = [".embed_query(", "raw_query)"].concat();
        let query_intent_borrowed_needle: String = [".embed_query(", "&raw_query)"].concat();
        let query_intent_count = src
            .lines()
            .filter(|l| !l.contains("concat") && !l.contains("needle"))
            .filter(|l| {
                l.contains(&query_intent_needle) || l.contains(&query_intent_borrowed_needle)
            })
            .count();
        assert_eq!(
            query_intent_count, 2,
            "expected exactly 2 query-intent call sites \
             (shared ANN runner + compose KG-blend gate), found {query_intent_count}"
        );
    }

    /// #2232: once a rerank stage has successfully embedded the query, later
    /// stages embed candidates only. The recording provider sees the literal
    /// query exactly once across two independent candidate pools.
    #[tokio::test]
    async fn query_embedding_cache_reuses_query_vector_across_reranks() {
        use std::sync::{Arc, Mutex};

        use async_trait::async_trait;
        use khive_runtime::{AllowAllGate, BackendId, EmbedderProvider, RuntimeConfig};
        use lattice_embed::{EmbedError, EmbeddingModel, EmbeddingService};

        const MODEL_KEY: &str = "all-minilm-l6-v2";
        const DIM: usize = 384;

        struct RecordingService {
            texts: Arc<Mutex<Vec<String>>>,
        }

        #[async_trait]
        impl EmbeddingService for RecordingService {
            async fn embed(
                &self,
                texts: &[String],
                _model: EmbeddingModel,
            ) -> Result<Vec<Vec<f32>>, EmbedError> {
                self.texts
                    .lock()
                    .expect("recording lock")
                    .extend(texts.iter().cloned());
                Ok(texts.iter().map(|_| vec![0.5; DIM]).collect())
            }

            fn supports_model(&self, _model: EmbeddingModel) -> bool {
                true
            }

            fn name(&self) -> &'static str {
                "query-reuse-recording-service"
            }
        }

        struct RecordingProvider {
            texts: Arc<Mutex<Vec<String>>>,
        }

        #[async_trait]
        impl EmbedderProvider for RecordingProvider {
            fn name(&self) -> &str {
                MODEL_KEY
            }

            fn dimensions(&self) -> usize {
                DIM
            }

            async fn build(
                &self,
            ) -> Result<Arc<dyn EmbeddingService>, khive_runtime::RuntimeError> {
                Ok(Arc::new(RecordingService {
                    texts: Arc::clone(&self.texts),
                }))
            }
        }

        let texts = Arc::new(Mutex::new(Vec::new()));
        let runtime = KhiveRuntime::new(RuntimeConfig {
            web: Default::default(),
            telemetry: Default::default(),
            mounts: Vec::new(),
            brain: Default::default(),
            git_write: Default::default(),
            display_timezone: khive_runtime::config::resolve_default_display_timezone(),
            events_split: None,
            db_path: None,
            blob_hydration_bytes: khive_runtime::DEFAULT_BLOB_HYDRATION_BYTES,
            default_namespace: Namespace::local(),
            embedding_model: Some(EmbeddingModel::AllMiniLmL6V2),
            additional_embedding_models: Vec::new(),
            gate: Arc::new(AllowAllGate),
            packs: vec!["knowledge".to_string()],
            backend_id: BackendId::main(),
            brain_profile: None,
            visible_namespaces: Vec::new(),
            allowed_outbound_namespaces: Vec::new(),
            actor_id: None,
            exec: Default::default(),
        })
        .expect("runtime");
        runtime.register_embedder(RecordingProvider {
            texts: Arc::clone(&texts),
        });

        let query = "one request-local query vector";
        let mut query_embedding = QueryEmbeddingCache::default();
        let first = vec![
            "first candidate".to_string(),
            "second candidate".to_string(),
        ];
        let second = vec!["third candidate".to_string()];
        assert_eq!(
            embed_cosine_scores(&runtime, query, &mut query_embedding, &first)
                .await
                .expect("first rerank")
                .expect("first scores")
                .len(),
            2
        );
        assert!(
            query_embedding.any().is_some(),
            "first rerank must fill cache"
        );
        assert!(
            query_embedding.role_specific.is_not_attempted(),
            "embed_cosine_scores must cache the batch vector as generic, \
             never role_specific — it came from embed_batch, not embed_query"
        );
        assert_eq!(
            embed_cosine_scores(&runtime, query, &mut query_embedding, &second)
                .await
                .expect("second rerank")
                .expect("second scores")
                .len(),
            1
        );

        let recorded = texts.lock().expect("recording lock");
        assert_eq!(
            recorded
                .iter()
                .filter(|text| text.as_str() == query)
                .count(),
            1,
            "the shared query must be embedded exactly once: {recorded:?}"
        );
        assert_eq!(recorded.len(), 4, "one query plus three candidates");
    }

    // ── #2307: failed query embeddings must not be retried within a request ──
    //
    // Extends the #2232 `RecordingService` pattern above with a separate,
    // overridable `embed_query` (distinct from the generic `embed`) so these
    // tests can fail the query embedding on demand and prove which method a
    // given text actually reached.

    const ROLE_RECORDING_MODEL_KEY: &str = "all-minilm-l6-v2";
    const ROLE_RECORDING_DIM: usize = 384;
    const ROLE_RECORDING_QUERY: &str = "graph traversal caching strategies distributed \
         knowledge retrieval systems degraded embedding providers";
    // Atom content must clear the 20-word minimum; repeats the query terms
    // (for lexical relevance) plus filler.
    const ROLE_RECORDING_ATOM_CONTENT: &str = "graph traversal caching strategies distributed \
         knowledge retrieval systems degraded embedding providers require resilient fallback \
         behavior across production knowledge retrieval pipelines and search infrastructure";

    #[derive(Debug, Default)]
    struct RoleAwareRecordingCalls {
        query: Vec<String>,
        generic: Vec<String>,
        query_gate: Option<std::sync::Arc<tokio::sync::Semaphore>>,
    }

    struct RoleAwareRecordingService {
        calls: std::sync::Arc<std::sync::Mutex<RoleAwareRecordingCalls>>,
        fail_query: std::sync::Arc<std::sync::atomic::AtomicBool>,
    }

    #[async_trait::async_trait]
    impl lattice_embed::EmbeddingService for RoleAwareRecordingService {
        async fn embed(
            &self,
            texts: &[String],
            _model: lattice_embed::EmbeddingModel,
        ) -> Result<Vec<Vec<f32>>, lattice_embed::EmbedError> {
            self.calls
                .lock()
                .expect("recording lock")
                .generic
                .extend(texts.iter().cloned());
            Ok(texts
                .iter()
                .map(|_| vec![0.5; ROLE_RECORDING_DIM])
                .collect())
        }

        async fn embed_query(
            &self,
            texts: &[String],
            _model: lattice_embed::EmbeddingModel,
        ) -> Result<Vec<Vec<f32>>, lattice_embed::EmbedError> {
            let gate = {
                let mut calls = self.calls.lock().expect("recording lock");
                calls.query.extend(texts.iter().cloned());
                calls.query_gate.clone()
            };
            if let Some(gate) = gate {
                gate.acquire()
                    .await
                    .expect("query gate remains open")
                    .forget();
            }
            if self.fail_query.load(std::sync::atomic::Ordering::SeqCst) {
                return Err(lattice_embed::EmbedError::InferenceFailed(
                    "forced query-embedding failure".into(),
                ));
            }
            Ok(texts
                .iter()
                .map(|_| vec![0.25; ROLE_RECORDING_DIM])
                .collect())
        }

        fn supports_model(&self, _model: lattice_embed::EmbeddingModel) -> bool {
            true
        }

        fn name(&self) -> &'static str {
            "role-aware-recording-service"
        }
    }

    struct RoleAwareRecordingProvider {
        calls: std::sync::Arc<std::sync::Mutex<RoleAwareRecordingCalls>>,
        fail_query: std::sync::Arc<std::sync::atomic::AtomicBool>,
    }

    #[async_trait::async_trait]
    impl khive_runtime::EmbedderProvider for RoleAwareRecordingProvider {
        fn name(&self) -> &str {
            ROLE_RECORDING_MODEL_KEY
        }

        fn dimensions(&self) -> usize {
            ROLE_RECORDING_DIM
        }

        async fn build(
            &self,
        ) -> Result<std::sync::Arc<dyn lattice_embed::EmbeddingService>, RuntimeError> {
            Ok(std::sync::Arc::new(RoleAwareRecordingService {
                calls: std::sync::Arc::clone(&self.calls),
                fail_query: std::sync::Arc::clone(&self.fail_query),
            }))
        }
    }

    fn rt_with_role_aware_recording_embedder() -> (
        KhiveRuntime,
        std::sync::Arc<std::sync::Mutex<RoleAwareRecordingCalls>>,
        std::sync::Arc<std::sync::atomic::AtomicBool>,
    ) {
        let calls = std::sync::Arc::new(std::sync::Mutex::new(RoleAwareRecordingCalls::default()));
        let fail_query = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let runtime = KhiveRuntime::new(khive_runtime::RuntimeConfig {
            web: Default::default(),
            telemetry: Default::default(),
            mounts: Vec::new(),
            brain: Default::default(),
            git_write: Default::default(),
            display_timezone: khive_runtime::config::resolve_default_display_timezone(),
            events_split: None,
            db_path: None,
            blob_hydration_bytes: khive_runtime::DEFAULT_BLOB_HYDRATION_BYTES,
            default_namespace: Namespace::local(),
            embedding_model: Some(lattice_embed::EmbeddingModel::AllMiniLmL6V2),
            additional_embedding_models: Vec::new(),
            gate: std::sync::Arc::new(khive_runtime::AllowAllGate),
            packs: vec!["kg".to_string(), "knowledge".to_string()],
            backend_id: khive_runtime::BackendId::main(),
            brain_profile: None,
            visible_namespaces: Vec::new(),
            allowed_outbound_namespaces: Vec::new(),
            actor_id: None,
            exec: Default::default(),
        })
        .expect("in-memory runtime");
        runtime.register_embedder(RoleAwareRecordingProvider {
            calls: std::sync::Arc::clone(&calls),
            fail_query: std::sync::Arc::clone(&fail_query),
        });
        (runtime, calls, fail_query)
    }

    #[tokio::test]
    async fn search_and_suggest_start_lexical_reads_while_query_embedding_waits() {
        for suggest in [false, true] {
            let (runtime, calls, _) = rt_with_role_aware_recording_embedder();
            let access = runtime.sql();
            let mut writer = access.writer().await.expect("writer");
            writer
                .execute(SqlStatement {
                    sql: "INSERT INTO knowledge_atoms \
                          (id, namespace, slug, name, content, tags, finalized, status, created_at, updated_at) \
                          VALUES ('94000000-0000-0000-0000-000000000238', 'local', \
                                  'candidate-overlap', 'Candidate Overlap', \
                                  'graph traversal caching strategies distributed knowledge retrieval', \
                                  '[]', 1, 'reviewed', 0, 0)"
                        .into(),
                    params: Vec::new(),
                    label: None,
                })
                .await
                .expect("seed lexical hit");
            drop(writer);
            let gate = Arc::new(tokio::sync::Semaphore::new(0));
            calls.lock().expect("recording lock").query_gate = Some(Arc::clone(&gate));
            let token = runtime.authorize(Namespace::local()).expect("token");
            let ann = vamana::new_shared_for_role(false);
            let probes = Arc::new(Mutex::new(Vec::new()));
            let query = "graph traversal caching strategies distributed knowledge retrieval";
            let future = TERM_PROBES.scope(probes.clone(), async {
                if suggest {
                    KnowledgeHandlers::suggest(&runtime, &token, json!({"query": query}), &ann)
                        .await
                } else {
                    KnowledgeHandlers::search(
                        &runtime,
                        &token,
                        json!({"query": query, "rerank": false}),
                        &ann,
                    )
                    .await
                }
            });
            tokio::pin!(future);
            let overlapped = tokio::time::timeout(std::time::Duration::from_secs(3), async {
                loop {
                    let embedding_started = !calls.lock().expect("recording lock").query.is_empty();
                    let lexical_started = !probes.lock().expect("term probes").is_empty();
                    if embedding_started && lexical_started {
                        break;
                    }
                    tokio::select! {
                        result = &mut future => panic!("candidate stages finished before gate release: {result:?}"),
                        () = tokio::time::sleep(std::time::Duration::from_millis(1)) => {}
                    }
                }
            })
            .await;
            gate.add_permits(1);
            assert!(
                overlapped.is_ok(),
                "lexical read waited for embedding: suggest={suggest}"
            );
            let response = future
                .await
                .expect("candidate stages complete after gate release");
            if !suggest {
                assert_eq!(response["results"][0]["slug"], "candidate-overlap");
                assert_eq!(response["candidate_provenance"]["lexical"], "matched");
            }
        }
    }

    #[tokio::test(start_paused = true)]
    async fn failed_embedding_and_timed_out_lexical_stage_return_degraded_search() {
        let (runtime, _, fail_query) = rt_with_role_aware_recording_embedder();
        fail_query.store(true, std::sync::atomic::Ordering::SeqCst);
        let token = runtime.authorize(Namespace::local()).expect("token");
        let ann = vamana::new_shared_for_role(false);
        let response = crate::knowledge::lexical_timeout::tests::with_timeout(
            vec![LexicalPhase::ReaderOpen],
            std::time::Duration::from_millis(1),
            KnowledgeHandlers::search(
                &runtime,
                &token,
                json!({"query": "graph traversal caching strategies", "rerank": false}),
                &ann,
            ),
        )
        .await
        .expect("both recoverable candidate failures remain a response");
        assert_eq!(response["total"], 0);
        assert_eq!(response["candidate_provenance"]["lexical"], "timed_out");
        assert_eq!(response["degraded"]["lexical_timeout"], true);
    }

    #[tokio::test(start_paused = true)]
    async fn completed_ann_candidate_survives_lexical_stage_timeout() {
        let (runtime, _, _) = rt_with_role_aware_recording_embedder();
        let runtime = runtime.with_ann_fresh_tail_enabled(false);
        let atom_id = Uuid::from_u128(0x94000000000000000000000000000239);
        let access = runtime.sql();
        let mut writer = access.writer().await.expect("writer");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO knowledge_atoms \
                      (id, namespace, slug, name, content, tags, finalized, status, created_at, updated_at) \
                      VALUES (?1, 'local', 'ann-timeout-survivor', 'ANN Timeout Survivor', \
                              'dense candidate outside this lexical query', '[]', 1, 'reviewed', 0, 0)"
                    .into(),
                params: vec![SqlValue::Text(atom_id.to_string())],
                label: None,
            })
            .await
            .expect("seed ANN hydration row");
        writer
            .execute(SqlStatement {
                sql: "INSERT INTO ann_consumer_watermark \
                      (consumer, namespace, embedding_model, watermark) \
                      VALUES ('knowledge:knowledge.atom', 'local', ?1, 0)"
                    .into(),
                params: vec![SqlValue::Text(ROLE_RECORDING_MODEL_KEY.into())],
                label: None,
            })
            .await
            .expect("register loaded ANN consumer");
        drop(writer);

        let ann = vamana::new_shared_for_role(false);
        let key = vamana::AnnKey::new("local", ROLE_RECORDING_MODEL_KEY);
        let bridge = vamana::AnnBridge::build(
            vec![0.25; ROLE_RECORDING_DIM],
            ROLE_RECORDING_DIM,
            vec![atom_id],
        )
        .expect("build loaded bridge");
        vamana::install_if_fresher(&ann, &key, bridge).await;
        let token = runtime.authorize(Namespace::local()).expect("token");
        let response = crate::knowledge::lexical_timeout::tests::with_timeout(
            vec![LexicalPhase::ReaderOpen],
            std::time::Duration::from_millis(1),
            KnowledgeHandlers::search(
                &runtime,
                &token,
                json!({"query": "graph traversal caching strategies", "rerank": false}),
                &ann,
            ),
        )
        .await
        .expect("lexical timeout retains completed ANN result");
        assert_eq!(response["total"], 1);
        assert_eq!(response["results"][0]["slug"], "ann-timeout-survivor");
        assert_eq!(
            response["results"][0]["score_provenance"]["sources"],
            json!(["ann"])
        );
        assert_eq!(response["candidate_provenance"]["fallback"], "ann");
        assert_eq!(response["degraded"]["lexical_timeout"], true);
    }

    fn build_role_recording_registry(rt: &KhiveRuntime) -> khive_runtime::VerbRegistry {
        let mut builder = khive_runtime::VerbRegistryBuilder::new();
        builder.register(khive_pack_kg::KgPack::new(rt.clone()));
        builder.register(crate::KnowledgePack::new(rt.clone()));
        let registry = builder.build().expect("registry builds");
        rt.install_edge_rules(registry.all_edge_rules());
        registry
    }

    /// Seeds one atom as a domain member so `compose`'s auto flow reaches the
    /// Rerank phase; auto-compose skips domains with no live members before
    /// the KG-blend gate these tests exercise.
    async fn seed_role_recording_corpus(registry: &khive_runtime::VerbRegistry) {
        registry
            .dispatch(
                "knowledge.upsert_atoms",
                json!({
                    "atoms": [{
                        "slug": "role-recording-atom",
                        "name": "Role Recording Atom",
                        "finalized": true,
                        "content": ROLE_RECORDING_ATOM_CONTENT
                    }]
                }),
            )
            .await
            .expect("upsert atom");
        registry
            .dispatch(
                "knowledge.upsert_domains",
                json!({
                    "domains": [{
                        "slug": "role-recording-domain",
                        "name": "Role Recording Domain",
                        "description": ROLE_RECORDING_ATOM_CONTENT,
                        "members": ["role-recording-atom"]
                    }]
                }),
            )
            .await
            .expect("upsert domain");
        registry
            .dispatch("knowledge.index", json!({ "rebuild_ann": false }))
            .await
            .expect("index");
    }

    /// (a) A failed `embed_query` inside `suggest` must not be retried by
    /// `compose`'s KG-blend gate immediately afterward in the same
    /// auto-compose request. Before the fix, `compose` saw
    /// `role_specific: None` — indistinguishable from "never tried" — and
    /// spent a second failing provider call; the query text was attempted
    /// twice. Red before the fix: 2 attempts.
    #[tokio::test]
    async fn compose_auto_does_not_retry_role_specific_embed_after_suggest_failure() {
        let (rt, calls, fail_query) = rt_with_role_aware_recording_embedder();
        let registry = build_role_recording_registry(&rt);
        seed_role_recording_corpus(&registry).await;
        fail_query.store(true, std::sync::atomic::Ordering::SeqCst);

        let ann = vamana::new_shared();
        let token = rt.authorize(Namespace::local()).expect("authorize");
        let result = KnowledgeHandlers::compose(
            &rt,
            &token,
            json!({ "query": ROLE_RECORDING_QUERY }),
            &ann,
            HashMap::new(),
        )
        .await
        .expect("compose must not Err when the query embedding is degraded");

        let attempts = calls
            .lock()
            .expect("recording lock")
            .query
            .iter()
            .filter(|text| text.as_str() == ROLE_RECORDING_QUERY)
            .count();
        assert_eq!(
            attempts, 1,
            "a failed embed_query must not be retried later in the same request; result: {result}"
        );
        assert_eq!(
            result["data"]["count"].as_u64(),
            Some(1),
            "the atom must still reach the briefing through the degraded blend path; \
             result: {result}"
        );
    }

    /// (b) Control: without a prior failure, `suggest`'s successful
    /// role-specific embed is the *only* attempt across the whole
    /// auto-compose request — `compose`'s KG-blend gate reuses it rather than
    /// embedding again. The narrower claim (a rerank stage specifically
    /// reuses a cached vector across candidate batches) is covered by
    /// `query_embedding_cache_reuses_query_vector_across_reranks` (#2232)
    /// above; this test covers the handler-level chain instead.
    #[tokio::test]
    async fn compose_auto_reuses_successful_suggest_embed_without_retry() {
        let (rt, calls, _fail_query) = rt_with_role_aware_recording_embedder();
        let registry = build_role_recording_registry(&rt);
        seed_role_recording_corpus(&registry).await;

        let ann = vamana::new_shared();
        let token = rt.authorize(Namespace::local()).expect("authorize");
        let result = KnowledgeHandlers::compose(
            &rt,
            &token,
            json!({ "query": ROLE_RECORDING_QUERY }),
            &ann,
            HashMap::new(),
        )
        .await
        .expect("compose must not Err");

        let attempts = calls
            .lock()
            .expect("recording lock")
            .query
            .iter()
            .filter(|text| text.as_str() == ROLE_RECORDING_QUERY)
            .count();
        assert_eq!(
            attempts, 1,
            "a successful embed_query must be reused, not repeated; result: {result}"
        );
        assert_eq!(
            result["data"]["count"].as_u64(),
            Some(1),
            "result: {result}"
        );
    }

    /// (c) Control: a `compose` call that never goes through `suggest` (explicit
    /// `domain_ids`, so auto-mode never runs) still embeds the query exactly
    /// once for its own KG-blend gate — `NotAttempted` always authorizes the
    /// one attempt a stage that never tried is entitled to.
    #[tokio::test]
    async fn compose_direct_call_without_suggest_still_embeds_query_once() {
        let (rt, calls, _fail_query) = rt_with_role_aware_recording_embedder();
        let registry = build_role_recording_registry(&rt);
        seed_role_recording_corpus(&registry).await;

        let ann = vamana::new_shared();
        let token = rt.authorize(Namespace::local()).expect("authorize");
        let result = KnowledgeHandlers::compose(
            &rt,
            &token,
            json!({
                "query": ROLE_RECORDING_QUERY,
                "domain_ids": ["role-recording-domain"],
            }),
            &ann,
            HashMap::new(),
        )
        .await
        .expect("compose must not Err");

        let attempts = calls
            .lock()
            .expect("recording lock")
            .query
            .iter()
            .filter(|text| text.as_str() == ROLE_RECORDING_QUERY)
            .count();
        assert_eq!(
            attempts, 1,
            "a stage that never tried must still embed once; result: {result}"
        );
        assert_eq!(
            result["data"]["count"].as_u64(),
            Some(1),
            "result: {result}"
        );
    }

    /// (d) #2307 item 2: `search`, `suggest`, and `compose` must each dispatch
    /// the query text through `EmbeddingService::embed_query` specifically —
    /// never through the generic `embed`. The source-scan guard below this
    /// test only ever checked the generic path's *absence*; a mutation
    /// swapping every production `embed_query` call for `embed_document`
    /// still passed it (documented in the crate's fix report for #2307).
    /// This behavioral check closes that gap by observing which method the
    /// query text actually reaches at runtime.
    #[tokio::test]
    async fn search_suggest_compose_dispatch_query_through_embed_query_not_generic() {
        for verb in ["search", "suggest", "compose"] {
            let (rt, calls, _fail_query) = rt_with_role_aware_recording_embedder();
            let registry = build_role_recording_registry(&rt);
            seed_role_recording_corpus(&registry).await;
            let ann = vamana::new_shared();
            let token = rt.authorize(Namespace::local()).expect("authorize");

            match verb {
                "search" => {
                    KnowledgeHandlers::search(
                        &rt,
                        &token,
                        json!({ "query": ROLE_RECORDING_QUERY }),
                        &ann,
                    )
                    .await
                    .expect("search must not Err");
                }
                "suggest" => {
                    KnowledgeHandlers::suggest(
                        &rt,
                        &token,
                        json!({ "query": ROLE_RECORDING_QUERY }),
                        &ann,
                    )
                    .await
                    .expect("suggest must not Err");
                }
                "compose" => {
                    KnowledgeHandlers::compose(
                        &rt,
                        &token,
                        json!({ "query": ROLE_RECORDING_QUERY }),
                        &ann,
                        HashMap::new(),
                    )
                    .await
                    .expect("compose must not Err");
                }
                _ => unreachable!(),
            }

            let recorded = calls.lock().expect("recording lock");
            assert!(
                recorded
                    .query
                    .iter()
                    .any(|text| text == ROLE_RECORDING_QUERY),
                "{verb}: query text must reach embed_query at least once; recorded={recorded:?}"
            );
            assert!(
                !recorded
                    .generic
                    .iter()
                    .any(|text| text == ROLE_RECORDING_QUERY),
                "{verb}: query text must never reach the generic embed path; recorded={recorded:?}"
            );
        }
    }

    // ── filter_by_excluded_statuses ───────────────────────────────────────────

    fn make_hit(id: &str, status: Option<&str>, score: f32) -> ScoredHit {
        ScoredHit {
            id: id.to_string(),
            slug: id.to_string(),
            name: id.to_string(),
            content: None,
            tags: None,
            finalized: false,
            is_domain: false,
            status: status.map(str::to_string),
            score,
            provenance: ScoreProvenance::lexical(),
        }
    }

    fn make_ann_hit(id: &str, status: Option<&str>, score: f32) -> ScoredHit {
        let mut hit = make_hit(id, status, score);
        hit.provenance = ScoreProvenance::ann();
        hit
    }

    #[test]
    fn rrf_overlap_retains_both_candidate_sources() {
        let mut hits = vec![
            make_hit("shared", Some("reviewed"), 8.0),
            make_hit("lexical-only", Some("reviewed"), 4.0),
        ];
        let ann = vec![
            make_ann_hit("shared", Some("reviewed"), 0.9),
            make_ann_hit("ann-only", Some("reviewed"), 0.8),
        ];
        fuse_ann_hits(&mut hits, &ann, 0.0);

        assert_eq!(hits.len(), 3);
        assert_eq!(hits[0].id, "shared");
        assert_eq!(hits[0].score, 1.0);
        assert_eq!(
            hits[0].provenance.to_json(),
            json!({
                "sources": ["lexical", "ann"],
                "embedding_rerank": false,
                "normalization": "s_over_s_plus_1",
                "calibrated": false,
            })
        );
        let lexical = hits.iter().find(|hit| hit.id == "lexical-only").unwrap();
        let ann = hits.iter().find(|hit| hit.id == "ann-only").unwrap();
        assert_eq!(lexical.provenance, ScoreProvenance::lexical());
        assert_eq!(ann.provenance, ScoreProvenance::ann());
        assert_eq!(lexical.score, ann.score);
    }

    #[test]
    fn decomposed_overlap_merges_provenance_without_counting_duplicates_twice() {
        let full = vec![
            make_hit("shared", Some("reviewed"), 8.0),
            make_hit("full-only", Some("reviewed"), 6.0),
        ];
        let subqueries = [
            vec![
                make_ann_hit("shared", Some("reviewed"), 100.0),
                make_hit("sub-shared", Some("reviewed"), 10.0),
                make_ann_hit("sub-shared", Some("reviewed"), 50.0),
            ],
            vec![
                make_ann_hit("shared", Some("reviewed"), 100.0),
                make_ann_hit("sub-shared", Some("reviewed"), 50.0),
                make_ann_hit("ann-only", Some("reviewed"), 2.0),
            ],
        ];
        let hits = merge_decomposed_hits(full, subqueries, 0.5, 10);

        let ids: Vec<_> = hits.iter().map(|hit| hit.id.as_str()).collect();
        assert_eq!(ids, ["shared", "full-only", "sub-shared", "ann-only"]);
        assert_eq!(hits[0].score, 12.0);
        assert_eq!(hits[1].score, 6.0);
        assert_eq!(hits[2].score, 4.5);
        assert!((hits[3].score - 0.6).abs() < 1e-6);
        for hit in [&hits[0], &hits[2]] {
            assert!(hit.provenance.lexical && hit.provenance.ann);
            assert!(!hit.provenance.embedding_rerank);
        }
        assert_eq!(hits[1].provenance, ScoreProvenance::lexical());
        assert_eq!(hits[3].provenance, ScoreProvenance::ann());
    }

    #[test]
    fn candidate_fallback_requires_ann_without_any_lexical_source() {
        let lexical = make_hit("lexical", None, 1.0);
        let ann = make_ann_hit("ann", None, 1.0);
        let mut overlap = lexical.clone();
        overlap.provenance.merge_sources(ann.provenance);
        assert_eq!(candidate_fallback(&[]), "none");
        assert_eq!(candidate_fallback(std::slice::from_ref(&ann)), "ann");
        assert_eq!(candidate_fallback(std::slice::from_ref(&lexical)), "none");
        assert_eq!(candidate_fallback(&[lexical, ann]), "none");
        assert_eq!(candidate_fallback(&[overlap]), "none");
    }

    #[tokio::test]
    async fn skipped_embedding_rerank_preserves_scores_and_provenance() {
        let runtime = KhiveRuntime::new(khive_runtime::RuntimeConfig {
            db_path: None,
            ..khive_runtime::RuntimeConfig::no_embeddings()
        })
        .expect("in-memory runtime without embeddings");
        assert!(runtime.config().db_path.is_none());
        let mut hits = vec![
            make_hit("lexical", None, 3.0),
            make_ann_hit("ann", None, 0.8),
        ];
        let applied = rerank_with_embeddings(
            &runtime,
            "provenance query",
            &mut QueryEmbeddingCache::default(),
            &mut hits,
            0.7,
        )
        .await
        .expect("optional rerank");
        assert!(!applied);
        assert_eq!(hits[0].score, 3.0);
        assert_eq!(hits[1].score, 0.8);
        assert_eq!(hits[0].provenance, ScoreProvenance::lexical());
        assert_eq!(hits[1].provenance, ScoreProvenance::ann());
    }

    #[tokio::test]
    async fn search_reports_lexical_provenance_and_successful_embedding_rerank() {
        let (runtime, calls, fail_query) = rt_with_role_aware_recording_embedder();
        let registry = build_role_recording_registry(&runtime);
        seed_role_recording_corpus(&registry).await;
        fail_query.store(true, std::sync::atomic::Ordering::SeqCst);
        let token = runtime.authorize(Namespace::local()).expect("local token");
        let ann = vamana::new_shared();

        for rerank in [false, true] {
            calls.lock().expect("recording lock").generic.clear();
            let response = KnowledgeHandlers::search(
                &runtime,
                &token,
                json!({"query": ROLE_RECORDING_QUERY, "kind": "atom", "rerank": rerank}),
                &ann,
            )
            .await
            .expect("search");
            assert_eq!(response["total"], 1, "{response}");
            assert_eq!(response["results"][0]["slug"], "role-recording-atom");
            assert_eq!(
                response["results"][0]["score_provenance"],
                json!({
                    "sources": ["lexical"],
                    "embedding_rerank": rerank,
                    "normalization": "s_over_s_plus_1",
                    "calibrated": false,
                })
            );
            let recorded = calls.lock().expect("recording lock");
            if rerank {
                assert_eq!(
                    recorded.generic,
                    [
                        ROLE_RECORDING_QUERY.to_string(),
                        format!("Role Recording Atom {ROLE_RECORDING_ATOM_CONTENT}")
                    ]
                );
            } else {
                assert!(recorded.generic.is_empty());
            }
        }
    }

    #[test]
    fn explicit_status_is_an_exact_allowlist_for_hydrated_hits() {
        let mut hits = vec![
            make_hit("reviewed", Some("reviewed"), 0.9),
            make_hit("draft", Some("draft"), 0.8),
            make_hit("deprecated", Some("deprecated"), 0.7),
            make_hit("missing-status", None, 0.6),
        ];
        filter_hits_by_status(&mut hits, &["draft".to_string()], &[]);
        let ids: Vec<&str> = hits.iter().map(|hit| hit.id.as_str()).collect();
        assert_eq!(ids, ["draft"]);
    }

    #[test]
    fn deprecated_multiplier_gate_uses_resolved_status_policy() {
        assert!(!deprecated_allowed_by_status_policy(
            &[],
            &["draft", "deprecated"]
        ));
        assert!(!deprecated_allowed_by_status_policy(&[], &["deprecated"]));
        assert!(deprecated_allowed_by_status_policy(&[], &["reviewed"]));
        assert!(!deprecated_allowed_by_status_policy(
            &["reviewed".to_string()],
            &[]
        ));
        assert!(deprecated_allowed_by_status_policy(
            &["deprecated".to_string()],
            &[]
        ));
    }

    #[test]
    fn filter_excluded_statuses_removes_draft_hits() {
        let mut hits = vec![
            make_hit("reviewed-1", Some("reviewed"), 0.8),
            make_hit("draft-1", Some("draft"), 0.7),
            make_hit("reviewed-2", Some("reviewed"), 0.6),
            make_hit("draft-2", Some("draft"), 0.5),
        ];
        filter_by_excluded_statuses(&mut hits, &["draft", "deprecated"]);
        let ids: Vec<&str> = hits.iter().map(|h| h.id.as_str()).collect();
        assert_eq!(
            ids,
            ["reviewed-1", "reviewed-2"],
            "draft hits must be removed"
        );
    }

    #[test]
    fn filter_excluded_statuses_removes_deprecated_hits() {
        let mut hits = vec![
            make_hit("reviewed-1", Some("reviewed"), 0.9),
            make_hit("deprecated-1", Some("deprecated"), 0.8),
        ];
        filter_by_excluded_statuses(&mut hits, &["draft", "deprecated"]);
        let ids: Vec<&str> = hits.iter().map(|h| h.id.as_str()).collect();
        assert_eq!(ids, ["reviewed-1"]);
    }

    #[test]
    fn filter_excluded_statuses_empty_list_is_noop() {
        let mut hits = vec![
            make_hit("draft-1", Some("draft"), 0.9),
            make_hit("reviewed-1", Some("reviewed"), 0.8),
        ];
        filter_by_excluded_statuses(&mut hits, &[]);
        assert_eq!(hits.len(), 2, "empty exclude list must be a no-op");
    }

    #[test]
    fn filter_excluded_statuses_null_status_treated_as_not_excluded() {
        // Hits with no status (ANN-sourced before hydration completes) must not
        // be removed by the status exclusion — they are not drafts or deprecated.
        let mut hits = vec![
            make_hit("no-status", None, 0.9),
            make_hit("draft-1", Some("draft"), 0.7),
        ];
        filter_by_excluded_statuses(&mut hits, &["draft", "deprecated"]);
        let ids: Vec<&str> = hits.iter().map(|h| h.id.as_str()).collect();
        assert_eq!(ids, ["no-status"], "null-status hit must survive exclusion");
    }

    #[test]
    fn normalize_rrf_score_is_bounded_and_monotonic() {
        let k = RRF_K;
        let max_single = 1.0f32 / (k as f32 + 1.0);
        let scores_single = [
            max_single * 0.25,
            max_single * 0.5,
            max_single,
            max_single * 1.5,
        ];
        let normed_single: Vec<f32> = scores_single
            .iter()
            .map(|&r| normalize_rrf_score(r, 1, k))
            .collect();
        for &s in &normed_single {
            assert!((0.0..=1.0).contains(&s), "score out of range: {s}");
        }
        assert!(normed_single[0] < normed_single[1]);
        assert!(normed_single[1] < normed_single[2]);
        assert_eq!(normed_single[3], 1.0);

        let max_two = 2.0f32 / (k as f32 + 1.0);
        let scores_two = [max_two * 0.25, max_two * 0.75, max_two, max_two * 2.0];
        let normed_two: Vec<f32> = scores_two
            .iter()
            .map(|&r| normalize_rrf_score(r, 2, k))
            .collect();
        for &s in &normed_two {
            assert!((0.0..=1.0).contains(&s), "score out of range: {s}");
        }
        assert!(normed_two[0] < normed_two[1]);
        assert!(normed_two[1] < normed_two[2]);
        assert_eq!(normed_two[3], 1.0);

        let raw = [0.001f32, 0.005, 0.010, 0.015];
        let normed: Vec<f32> = raw.iter().map(|&r| normalize_rrf_score(r, 1, k)).collect();
        let raw_order: Vec<usize> = {
            let mut idx: Vec<usize> = (0..raw.len()).collect();
            idx.sort_by(|&a, &b| raw[b].partial_cmp(&raw[a]).unwrap());
            idx
        };
        let norm_order: Vec<usize> = {
            let mut idx: Vec<usize> = (0..normed.len()).collect();
            idx.sort_by(|&a, &b| normed[b].partial_cmp(&normed[a]).unwrap());
            idx
        };
        assert_eq!(
            raw_order, norm_order,
            "normalization must not invert ranking"
        );
    }

    #[test]
    fn normalize_rrf_score_zero_source_count_returns_zero() {
        assert_eq!(normalize_rrf_score(0.5, 0, RRF_K), 0.0);
    }

    /// Fusion-admitted hit whose score the status multiplier squashes below
    /// `min_score` must not survive the late floor. Reproduction arithmetic:
    /// a single-source RRF top hit normalizes to 1.0, then `s/(s+1)` with
    /// multiplier 1.0 squashes it to 0.5 — below a 0.7 floor.
    #[test]
    fn min_score_floor_drops_hit_squashed_below_threshold_by_status_multiplier() {
        let mut hits = vec![make_hit("atom-1", Some("reviewed"), 0.0)];
        fuse_ann_hits(&mut hits, &[], 0.7);
        assert_eq!(hits.len(), 1, "fusion stage must admit the 1.0 RRF hit");
        assert_eq!(hits[0].score, 1.0);

        apply_status_multipliers(&mut hits, false);
        assert!((hits[0].score - 0.5).abs() < 1e-6, "1.0 squashes to 0.5");

        enforce_min_score_floor(&mut hits, 0.7);
        assert!(
            hits.is_empty(),
            "0.5 post-multiplier score must not clear a 0.7 floor"
        );
    }

    #[test]
    fn min_score_floor_keeps_hit_at_or_above_threshold_after_multiplier() {
        let mut hits = vec![make_hit("atom-1", Some("reviewed"), 0.0)];
        fuse_ann_hits(&mut hits, &[], 0.4);
        assert_eq!(hits.len(), 1, "fusion stage must admit the 1.0 RRF hit");

        apply_status_multipliers(&mut hits, false);
        let squashed = hits[0].score;

        enforce_min_score_floor(&mut hits, 0.4);
        assert_eq!(
            hits.len(),
            1,
            "0.5 post-multiplier score clears a 0.4 floor"
        );
        assert_eq!(hits[0].id, "atom-1");
        assert!(hits[0].score >= 0.4);
        assert_eq!(hits[0].score, squashed, "floor must not rewrite scores");
    }

    /// `min_score = 0.0` (the absent default) must return the identical set —
    /// the floor cannot alter the no-threshold path.
    #[test]
    fn min_score_floor_zero_is_noop_on_multiplier_survivors() {
        let build = || {
            let mut hits = vec![
                make_hit("atom-1", Some("reviewed"), 0.9),
                make_hit("atom-2", Some("draft"), 0.6),
                make_hit("atom-3", Some("deprecated"), 0.8),
            ];
            apply_status_multipliers(&mut hits, false);
            hits
        };

        let before = build();
        let mut after = build();
        enforce_min_score_floor(&mut after, 0.0);

        let ids_before: Vec<&str> = before.iter().map(|h| h.id.as_str()).collect();
        let ids_after: Vec<&str> = after.iter().map(|h| h.id.as_str()).collect();
        assert_eq!(ids_after, ids_before);
        for (a, b) in after.iter().zip(before.iter()) {
            assert_eq!(a.score, b.score);
        }
    }

    /// Body-line metadata is best-effort: a read-deadline timeout during the
    /// aggregate lookup degrades to `Ok(None)` (rendered as `body_lines:
    /// null` plus a degradation flag by the handler) instead of failing an
    /// already-ranked search with an `Internal` error.
    #[tokio::test]
    async fn body_line_counts_degrade_to_none_under_expired_read_deadline() {
        let runtime = KhiveRuntime::memory().expect("in-memory runtime");
        let atom_ids = vec!["10000000-0000-0000-0000-000000000001".to_owned()];

        let degraded = khive_storage::scope_request_read_deadline(
            std::time::Duration::ZERO,
            load_atom_body_line_counts(&runtime, "local", &atom_ids),
        )
        .await;
        assert!(
            matches!(degraded, Ok(None)),
            "an expired read deadline must degrade body-line metadata to \
             None, never error the search; got {degraded:?}"
        );

        let healthy = load_atom_body_line_counts(&runtime, "local", &atom_ids)
            .await
            .expect("undeadlined lookup must succeed");
        assert_eq!(
            healthy.and_then(|counts| counts.get(&atom_ids[0]).copied()),
            Some(0),
            "control: without a deadline the lookup returns real counts"
        );
    }
}