frankensearch-lexical 0.2.2

Tantivy BM25 full-text search integration for frankensearch
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
//! Tantivy BM25 full-text search integration for frankensearch.
//!
//! Provides the [`TantivyIndex`] implementation of the [`LexicalSearch`] trait,
//! including schema creation, document indexing, BM25 query parsing,
//! and search result ranking.
//!
//! The crate version constant is part of gauntlet dependency provenance: it
//! identifies the concrete lexical wrapper compiled around Tantivy.
//!
//! # Schema
//!
//! | Field | Tantivy Options | Source |
//! |-------|-----------------|--------|
//! | `id` | `STRING \| STORED` | `IndexableDocument::id` |
//! | `content` | `TEXT \| STORED` | `IndexableDocument::content` |
//! | `title` | `TEXT \| STORED` | `IndexableDocument::title` (empty if `None`) |
//! | `metadata_json` | `STORED` | Serialized `IndexableDocument::metadata` |
//!
//! The `content` and `title` fields are searched with BM25 scoring.
//! Title matches receive a 2× boost via `QueryParser::set_field_boost`.

/// Exact `frankensearch-lexical` crate version compiled into this adapter.
pub const FRANKENSEARCH_LEXICAL_CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");

pub mod cass_compat;
pub mod quill_contract;

pub use cass_compat::{
    CASS_SCHEMA_HASH, CASS_SCHEMA_VERSION, CassDocument, CassDocumentRef, CassFields,
    CassMergeStatus, CassQueryFilters, CassQueryToken, CassSourceFilter, CassTantivyIndex,
    CassWildcardPattern, cass_build_preview, cass_build_schema, cass_build_tantivy_query,
    cass_ensure_tokenizer, cass_fields_from_schema, cass_generate_edge_ngrams,
    cass_has_boolean_operators, cass_index_dir, cass_open_search_reader, cass_parse_boolean_query,
    cass_regex_query_cached, cass_regex_query_uncached, cass_sanitize_query,
    cass_schema_hash_matches,
};

// Re-export tantivy types that appear in frankensearch-lexical's public API.
// Consumers can import these from `frankensearch::lexical_tantivy::` instead
// of adding a direct Tantivy dependency. The explicit namespace keeps
// foreign-format and oracle callers stable when the facade's generic
// `lexical` feature selects Quill.
pub use tantivy::collector::{Count, TopDocs};
pub use tantivy::query::{BooleanQuery, Occur, Query, TermQuery};
pub use tantivy::schema::{Field, IndexRecordOption, Schema, Value};
pub use tantivy::{
    self as tantivy_crate, DocAddress, Index, IndexReader, IndexWriter, ReloadPolicy, Searcher,
    TantivyDocument, Term,
};

use std::borrow::Cow;
use std::path::{Path, PathBuf};
#[cfg(feature = "bench-internals")]
use std::sync::Arc;
use std::sync::RwLock;
#[cfg(feature = "bench-internals")]
use std::sync::atomic::{AtomicBool, AtomicU64};
use std::sync::atomic::{AtomicUsize, Ordering};

use asupersync::Cx;
use asupersync::sync::Mutex;
use frankensearch_core::error::{SearchError, SearchResult};
use frankensearch_core::traits::{LexicalCandidateBatch, LexicalHydrationContext, SearchFuture};
use frankensearch_core::types::{DocId, IndexableDocument, ScoreSource, ScoredResult};
use serde::{Deserialize, Serialize};
use tantivy::collector::DocSetCollector;
#[cfg(feature = "bench-internals")]
use tantivy::directory::error::{
    DeleteError, LockError, OpenDirectoryError, OpenReadError, OpenWriteError,
};
#[cfg(feature = "bench-internals")]
use tantivy::directory::{
    Directory, DirectoryLock, FileHandle, Lock, MmapDirectory, WatchCallback, WatchHandle, WritePtr,
};
use tantivy::query::QueryParser;
use tantivy::schema::{FAST, STORED, STRING, TextFieldIndexing, TextOptions};
use tantivy::tokenizer::{TextAnalyzer, Token, TokenStream, Tokenizer};
use tracing::{debug, instrument, warn};

// ─── Constants ──────────────────────────────────────────────────────────────

/// Name for the custom tokenizer registered with the Tantivy index.
const TOKENIZER_NAME: &str = "frankensearch_default";

/// Default heap size for the Tantivy `IndexWriter` (50 MB).
const WRITER_HEAP_BYTES: usize = 50_000_000;

/// Process-local issuer for opaque benchmark writer attestations.
///
/// A construction ID proves only that a distinct writer was constructed during
/// this process. It is deliberately not a persisted or cross-process identity.
#[cfg(feature = "bench-internals")]
static NEXT_BENCHMARK_WRITER_CONSTRUCTION_ID: AtomicU64 = AtomicU64::new(1);

/// BM25 boost applied to title field matches.
const TITLE_BOOST: f32 = 2.0;

/// Maximum query length in characters. Queries exceeding this are truncated
/// with a warning log. Prevents pathological parsing of enormous inputs.
const MAX_QUERY_LENGTH: usize = 10_000;

/// Default Tantivy snippet window value. Tantivy names this a character limit,
/// but observably compares UTF-8 byte offsets and cuts at token boundaries.
const DEFAULT_SNIPPET_MAX_CHARS: usize = 200;

// ─── Query Explanation ──────────────────────────────────────────────────────

/// Classification of a parsed query for debugging and diagnostics.
///
/// Returned by [`TantivyIndex::search_with_snippets`] to help callers
/// understand how a query was interpreted by Tantivy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum QueryExplanation {
    /// Query was empty or whitespace-only; no search performed.
    Empty,
    /// Single-term query (e.g., `"authentication"`).
    Simple,
    /// Quoted phrase query (e.g., `"error handling"`).
    Phrase,
    /// Multi-term query interpreted as boolean OR (default Tantivy behavior).
    Boolean,
}

impl std::fmt::Display for QueryExplanation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Empty => write!(f, "empty"),
            Self::Simple => write!(f, "simple"),
            Self::Phrase => write!(f, "phrase"),
            Self::Boolean => write!(f, "boolean"),
        }
    }
}

/// Classify a raw query string into a [`QueryExplanation`].
/// Strip the boost from any parenthesized group that contains a negation
/// (bd-f20ye), for the SHIPPING search path only.
///
/// # Why a boost has to be dropped rather than moved
///
/// Tantivy 0.26.1 lowers `(A NOT B)` as a `MustNot` clause OF the enclosing
/// boolean, which excludes, but lowers `(A NOT B)^2` by nesting the negation in
/// its own `BooleanQuery { [(MustNot, …)], msm: 0 }` and attaching THAT as a
/// clause of the outer boolean. A matcher meaning "every document except B"
/// then becomes a positive alternative, so the group stops excluding:
/// `(A NOT B)^2` returns the documents B was supposed to remove, and
/// `(A AND NOT B)^2` fails the other way and returns nothing.
///
/// The repair cannot be done on the parsed tree: `BoostQuery`'s fields are
/// private and it exposes no accessors, so the boolean inside a boost is
/// unreachable. It therefore happens on the query text, before parsing.
///
/// Dropping the boost is exact for MEMBERSHIP, which is the property at stake,
/// and lossy for SCORING: a `MustNot` clause contributes no score, so the boost
/// only ever scaled the positive operands, and those keep their relative order
/// without it. Redistributing the factor onto each positive operand would
/// preserve scores too, but requires splitting arbitrary group syntax by hand —
/// more ways to be wrong, for an ordering nicety, on a shape Tantivy cannot
/// currently express correctly at all.
///
/// Quoted phrases are respected, so a literal `"a NOT b"` never triggers it.
/// Rewrite `A AND NOT B` to `A NOT B` for the SHIPPING path only (bd-eeq0q).
///
/// THE DEFECT, measured on tantivy 0.26.1 with p1="alpha beta", p2="alpha gamma":
///
/// ```text
///   alpha NOT beta            [p2]   correct
///   alpha -beta               [p2]   correct
///   alpha AND NOT beta        []     WRONG — p2 has alpha and no beta
///   (alpha AND NOT beta)      []     WRONG
///   (alpha AND NOT beta)^2    []     WRONG, and untouched by the bd-f20ye repair
/// ```
///
/// `A AND NOT B` lowers to
/// `Bool{[(Must, A), (Must, Bool{[(MustNot, B)], msm: 0})], msm: 0}`. The second
/// `Must` operand is a boolean with only a `MustNot` clause and no positive
/// clause, so it matches nothing and the whole conjunction is empty. The same
/// engine returns the right answer for `A NOT B` and `A -B`, so this is an
/// inconsistency inside one query language rather than a defensible reading.
///
/// The repair deletes the redundant `AND` in front of a `NOT`, which is exactly
/// the spelling the engine already handles. It is textual for the same reason
/// [`repair_boosted_group_negation`] is: the lowering happens inside tantivy's
/// parser, and the resulting `BooleanQuery` cannot be rewritten from outside.
///
/// SCOPE, deliberately narrow. Only the exact token sequence `AND` `NOT` is
/// touched, both uppercase, both standalone. Quoted text is skipped, so a
/// literal `"a AND NOT b"` phrase query is never rewritten. Lowercase `and not`
/// is a pair of ordinary terms in this grammar and is left alone.
///
/// NOT A CONFORMANCE CHANGE. This runs only from
/// [`TantivyIndex::parse_query_shipping`]; every `oracle_observe_*` caller
/// keeps using [`TantivyIndex::parse_query_lenient`] and still reproduces the
/// defect, so the pinned comparator does not move. Quill was MEASURED to share
/// this behaviour (it returns nothing for `A AND NOT B` too, because
/// `wrap_not_for_and` in its parser mirrors the same lowering), which is why
/// repairing this side alone changes no Quill-versus-oracle comparison.
fn repair_and_not(query: &str) -> Cow<'_, str> {
    // Cheap reject: the token pair cannot be present.
    if !query.contains("AND") {
        return Cow::Borrowed(query);
    }

    let bytes = query.as_bytes();
    let mut drop_ranges: Vec<(usize, usize)> = Vec::new();
    let mut in_quotes = false;
    let mut index = 0_usize;

    while index < bytes.len() {
        let byte = bytes[index];
        if byte == b'"' {
            in_quotes = !in_quotes;
            index += 1;
            continue;
        }
        if in_quotes {
            index += 1;
            continue;
        }
        if byte == b'A' && query[index..].starts_with("AND") {
            let starts_token = index.checked_sub(1).is_none_or(|previous| {
                bytes[previous].is_ascii_whitespace() || bytes[previous] == b'('
            });
            // `AND` must be followed by whitespace, then `NOT` as its own token.
            let mut cursor = index + 3;
            let space_start = cursor;
            while cursor < bytes.len() && bytes[cursor].is_ascii_whitespace() {
                cursor += 1;
            }
            let had_space = cursor > space_start;
            let followed_by_not = had_space
                && query[cursor..].starts_with("NOT")
                && bytes
                    .get(cursor + 3)
                    .is_some_and(|next| next.is_ascii_whitespace() || *next == b'(');
            if starts_token && followed_by_not {
                // Drop `AND` and the whitespace that separated it from `NOT`,
                // leaving the preceding separator intact: `a AND NOT b`
                // becomes `a NOT b`, never `aNOT b`.
                drop_ranges.push((index, cursor));
                index = cursor;
                continue;
            }
        }
        index += 1;
    }

    if drop_ranges.is_empty() {
        return Cow::Borrowed(query);
    }
    let mut repaired = String::with_capacity(query.len());
    let mut copied = 0_usize;
    for (start, end) in drop_ranges {
        repaired.push_str(&query[copied..start]);
        copied = end;
    }
    repaired.push_str(&query[copied..]);
    Cow::Owned(repaired)
}

fn repair_boosted_group_negation(query: &str) -> Cow<'_, str> {
    // Cheap reject: no group boost, nothing to repair.
    if !query.contains(")^") {
        return Cow::Borrowed(query);
    }

    let bytes = query.as_bytes();
    // One flag per open group: did THIS group contain a negation directly?
    let mut group_negates: Vec<bool> = Vec::new();
    // Byte ranges of `^<number>` suffixes to remove.
    let mut drop_ranges: Vec<(usize, usize)> = Vec::new();
    let mut in_quotes = false;
    let mut index = 0_usize;

    while index < bytes.len() {
        let byte = bytes[index];
        if byte == b'"' {
            in_quotes = !in_quotes;
            index += 1;
            continue;
        }
        if in_quotes {
            index += 1;
            continue;
        }
        match byte {
            b'(' => group_negates.push(false),
            b')' => {
                let negates = group_negates.pop().unwrap_or(false);
                // A boost suffix is `^` followed by a number, possibly decimal.
                let mut cursor = index + 1;
                if negates && cursor < bytes.len() && bytes[cursor] == b'^' {
                    let start = cursor;
                    cursor += 1;
                    let digits_start = cursor;
                    while cursor < bytes.len()
                        && (bytes[cursor].is_ascii_digit() || bytes[cursor] == b'.')
                    {
                        cursor += 1;
                    }
                    if cursor > digits_start {
                        drop_ranges.push((start, cursor));
                    }
                }
            }
            b'N' => {
                // `NOT` as a standalone token, at this group's own level.
                let is_token = query[index..].starts_with("NOT")
                    && index.checked_sub(1).is_none_or(|previous| {
                        bytes[previous].is_ascii_whitespace() || bytes[previous] == b'('
                    })
                    && bytes
                        .get(index + 3)
                        .is_none_or(|next| next.is_ascii_whitespace() || *next == b'(');
                if is_token && let Some(current) = group_negates.last_mut() {
                    *current = true;
                }
            }
            b'-' => {
                // Prefix exclusion: `-term`, not a hyphen inside a word.
                let is_prefix = index.checked_sub(1).is_none_or(|previous| {
                    bytes[previous].is_ascii_whitespace() || bytes[previous] == b'('
                }) && bytes
                    .get(index + 1)
                    .is_some_and(|next| !next.is_ascii_whitespace());
                if is_prefix && let Some(current) = group_negates.last_mut() {
                    *current = true;
                }
            }
            _ => {}
        }
        index += 1;
    }

    if drop_ranges.is_empty() {
        return Cow::Borrowed(query);
    }
    let mut repaired = String::with_capacity(query.len());
    let mut cursor = 0_usize;
    for (start, end) in drop_ranges {
        repaired.push_str(&query[cursor..start]);
        cursor = end;
    }
    repaired.push_str(&query[cursor..]);
    Cow::Owned(repaired)
}

/// One operand of a boolean level, with its occurrence prefix decoded.
struct LevelOperand {
    negated: bool,
    required: bool,
    text: String,
}

/// A parsed element of one boolean level.
enum LevelItem {
    Operand(LevelOperand),
    And,
    Or,
}

/// Repair a CONJUNCTION that contains a negated operand (bd-8a2a8, **DIV-010**).
///
/// THE DEFECT. The pinned grammar declares `default join := OR; explicit AND has
/// precedence over OR` (`docs/contracts/quill-language-contract.md`), so
/// `a NOT b AND c` reads as `a OR (c AND NOT b)`. Tantivy 0.26.1 lowers the
/// `AND` conjunct to `Bool{[(Must, Bool{[(MustNot, b)], msm: 0}), (Must, c)]}`,
/// whose first operand has no positive clause and therefore matches nothing, so
/// the whole conjunct drops and only `a` survives. MEASURED on the shared
/// Core100 fixture: `release NOT bounds AND small` returns 21 documents
/// (`|release|`) where the declared reading is 41 (`|release ∪ small|`), which
/// is what Quill returns and what this engine ITSELF returns when the same
/// grouping is written out as `release ((small) NOT bounds)`. Two independent
/// implementations agreeing on the explicit form is what attributes the defect
/// to the implicit lowering rather than to either engine's semantics.
///
/// THE REPAIR normalises a whole `AND` chain that contains a negation into the
/// occurrence spelling this engine already lowers correctly: every positive
/// operand becomes `+operand` and every negative one `-operand`, in the operand
/// order the user wrote, so `a NOT b AND c` becomes `a (-b +c)`. That is exact
/// rather than approximate —
/// `+`/`-` ARE the `Must`/`MustNot` the chain means — which matters because the
/// obvious narrow alternative, deleting the `AND`, was measured to break queries
/// that were already correct (`explains NOT bounds AND refactors` answers 60 and
/// dropping the `AND` answers 59). It is textual for the same reason
/// [`repair_and_not`] and [`repair_boosted_group_negation`] are: the lowering
/// happens inside tantivy's parser and the resulting `BooleanQuery` cannot be
/// rewritten from outside.
///
/// SCOPE, deliberately narrow. A chain is rewritten only when it holds more than
/// one operand and at least one of them is negated; a pure-positive `a AND b`
/// keeps its spelling. Anything the scanner cannot decode — an unbalanced quote,
/// a dangling `AND`, an empty operand — returns the query untouched rather than
/// guessing. Quoted text is skipped, so a literal `"a AND NOT b"` phrase is
/// never rewritten, and a `field:(a b)` operand is carried through opaquely.
///
/// A CHAIN THAT SPANS ITS WHOLE LEVEL IS EMITTED WITHOUT PARENTHESES, which is
/// load-bearing rather than cosmetic: [`repair_boosted_group_negation`] records
/// negation against the INNERMOST open group, so wrapping `(a AND NOT b)^2` into
/// `((+a -b))^2` would hide the negation from it and silently regress DIV-009.
///
/// NOT A CONFORMANCE CHANGE. This runs only from
/// [`TantivyIndex::parse_query_shipping`]; every `oracle_observe_*` caller keeps
/// using [`TantivyIndex::parse_query_lenient`] and still reproduces the defect,
/// so the pinned comparator does not move.
fn repair_negated_conjunction(query: &str) -> Cow<'_, str> {
    // Cheap reject: without an explicit `AND` there is no chain to normalise.
    if !query.contains("AND") {
        return Cow::Borrowed(query);
    }
    rewrite_conjunction_level(query).map_or(Cow::Borrowed(query), Cow::Owned)
}

/// Is `token` present at `index` as a standalone token at this level?
fn is_level_token(level: &str, index: usize, token: &str) -> bool {
    let bytes = level.as_bytes();
    level[index..].starts_with(token)
        && index
            .checked_sub(1)
            .is_none_or(|previous| bytes[previous].is_ascii_whitespace() || bytes[previous] == b'(')
        && bytes
            .get(index + token.len())
            .is_none_or(|next| next.is_ascii_whitespace() || *next == b'(')
}

/// Find the `)` matching the `(` at `open`, ignoring parentheses inside quotes.
fn matching_close_paren(level: &str, open: usize) -> Option<usize> {
    let bytes = level.as_bytes();
    let mut depth = 0_usize;
    let mut in_quotes = false;
    for (offset, byte) in bytes[open..].iter().enumerate() {
        let cursor = open + offset;
        match byte {
            b'"' => in_quotes = !in_quotes,
            b'(' if !in_quotes => depth += 1,
            b')' if !in_quotes => {
                depth -= 1;
                if depth == 0 {
                    return Some(cursor);
                }
            }
            _ => {}
        }
    }
    None
}

/// Read one operand body starting at `start`, returning its text, the index just
/// past it, and whether a nested level inside it was rewritten.
fn parse_operand_body(level: &str, start: usize) -> Option<(String, usize, bool)> {
    let bytes = level.as_bytes();
    if start >= bytes.len() {
        return None;
    }
    if bytes[start] == b'(' {
        let close = matching_close_paren(level, start)?;
        let inner = &level[start + 1..close];
        let rewritten = rewrite_conjunction_level(inner);
        let inner_changed = rewritten.is_some();
        let inner_text = rewritten.unwrap_or_else(|| inner.to_string());
        // Trailing modifiers stay attached to the group: `^boost`, `~slop`.
        let mut cursor = close + 1;
        while cursor < bytes.len()
            && !bytes[cursor].is_ascii_whitespace()
            && bytes[cursor] != b')'
            && bytes[cursor] != b'('
        {
            cursor += 1;
        }
        let suffix = &level[close + 1..cursor];
        return Some((format!("({inner_text}){suffix}"), cursor, inner_changed));
    }

    let mut in_quotes = false;
    let mut cursor = start;
    while cursor < bytes.len() {
        let byte = bytes[cursor];
        if byte == b'"' {
            in_quotes = !in_quotes;
            cursor += 1;
            continue;
        }
        if in_quotes {
            cursor += 1;
            continue;
        }
        // A `(` inside a bare operand is a fielded group like `field:(a b)`:
        // carry it through opaquely rather than splitting the operand in two.
        if byte == b'(' {
            cursor = matching_close_paren(level, cursor)? + 1;
            continue;
        }
        if byte.is_ascii_whitespace() || byte == b')' {
            break;
        }
        cursor += 1;
    }
    if in_quotes || cursor == start {
        return None;
    }
    Some((level[start..cursor].to_string(), cursor, false))
}

/// Rewrite every negated `AND` chain at one boolean level, recursing into
/// parenthesised operands. `None` means "nothing to change, or not decodable".
fn rewrite_conjunction_level(level: &str) -> Option<String> {
    let bytes = level.as_bytes();
    let mut items: Vec<LevelItem> = Vec::new();
    let mut nested_changed = false;
    let mut index = 0_usize;

    while index < bytes.len() {
        if bytes[index].is_ascii_whitespace() {
            index += 1;
            continue;
        }
        if is_level_token(level, index, "AND") {
            items.push(LevelItem::And);
            index += 3;
            continue;
        }
        if is_level_token(level, index, "OR") {
            items.push(LevelItem::Or);
            index += 2;
            continue;
        }
        // Occurrence prefixes: any run of negators, and an explicit `+`.
        let mut negated = false;
        let mut required = false;
        loop {
            let byte = *bytes.get(index)?;
            if byte == b'-' || byte == b'+' {
                // A bare `-` or `+` with nothing attached is not an occurrence
                // prefix, and this scanner declines rather than guessing.
                if bytes
                    .get(index + 1)
                    .is_none_or(|next| next.is_ascii_whitespace())
                {
                    return None;
                }
                if byte == b'-' {
                    negated = true;
                } else {
                    required = true;
                }
                index += 1;
                continue;
            }
            if is_level_token(level, index, "NOT") {
                negated = true;
                index += 3;
                while index < bytes.len() && bytes[index].is_ascii_whitespace() {
                    index += 1;
                }
                continue;
            }
            break;
        }
        let (text, next, inner_changed) = parse_operand_body(level, index)?;
        nested_changed |= inner_changed;
        items.push(LevelItem::Operand(LevelOperand {
            negated,
            required,
            text,
        }));
        index = next;
    }

    // Group the level into `AND` chains. `AND` binds tighter than the default
    // join, so a maximal chain is exactly the unit whose lowering is defective.
    let mut chains: Vec<Vec<LevelOperand>> = Vec::new();
    let mut joins: Vec<&'static str> = Vec::new();
    let mut expect_operand = false;
    let mut next_join = " ";
    for item in items {
        match item {
            LevelItem::And => {
                if chains.is_empty() || expect_operand {
                    return None;
                }
                expect_operand = true;
            }
            LevelItem::Or => {
                if chains.is_empty() || expect_operand {
                    return None;
                }
                next_join = " OR ";
            }
            LevelItem::Operand(operand) => {
                if expect_operand {
                    chains.last_mut()?.push(operand);
                    expect_operand = false;
                } else {
                    if !chains.is_empty() {
                        joins.push(next_join);
                    }
                    next_join = " ";
                    chains.push(vec![operand]);
                }
            }
        }
    }
    if expect_operand || chains.is_empty() {
        return None;
    }

    let single_chain = chains.len() == 1;
    let mut rewrote = false;
    let mut rendered: Vec<String> = Vec::with_capacity(chains.len());
    for chain in &chains {
        if chain.len() > 1 && chain.iter().any(|operand| operand.negated) {
            rewrote = true;
            let mut body = String::new();
            for operand in chain {
                if !body.is_empty() {
                    body.push(' ');
                }
                body.push(if operand.negated { '-' } else { '+' });
                body.push_str(&operand.text);
            }
            // Bare when it IS the level, so DIV-009 still sees the negation.
            rendered.push(if single_chain {
                body
            } else {
                format!("({body})")
            });
        } else if chain.len() > 1 {
            rendered.push(
                chain
                    .iter()
                    .map(render_operand)
                    .collect::<Vec<_>>()
                    .join(" AND "),
            );
        } else {
            rendered.push(render_operand(&chain[0]));
        }
    }

    if !rewrote && !nested_changed {
        return None;
    }
    let mut output = rendered.first()?.clone();
    for (position, piece) in rendered.iter().enumerate().skip(1) {
        output.push_str(joins.get(position - 1)?);
        output.push_str(piece);
    }
    Some(output)
}

/// Re-emit an operand outside a rewritten chain, preserving its occurrence.
fn render_operand(operand: &LevelOperand) -> String {
    if operand.negated {
        format!("-{}", operand.text)
    } else if operand.required {
        format!("+{}", operand.text)
    } else {
        operand.text.clone()
    }
}

fn classify_query(query: &str) -> QueryExplanation {
    let trimmed = query.trim();
    if trimmed.is_empty() {
        return QueryExplanation::Empty;
    }
    // Check for quoted phrase: starts and ends with matching quotes.
    if (trimmed.starts_with('"') && trimmed.ends_with('"'))
        || (trimmed.starts_with('\'') && trimmed.ends_with('\''))
    {
        return QueryExplanation::Phrase;
    }
    // Count whitespace-separated tokens.
    let token_count = trimmed.split_whitespace().count();
    if token_count <= 1 {
        QueryExplanation::Simple
    } else {
        QueryExplanation::Boolean
    }
}

// ─── Snippet Configuration ──────────────────────────────────────────────────

/// Configuration for snippet generation in [`TantivyIndex::search_with_snippets`].
#[derive(Debug, Clone)]
pub struct SnippetConfig {
    /// Tantivy snippet window value. Despite the upstream name, the pinned
    /// implementation enforces this against UTF-8 byte offsets at token
    /// boundaries.
    pub max_chars: usize,
    /// HTML tag prefix for highlighted terms (e.g., `"<b>"`).
    pub highlight_prefix: String,
    /// HTML tag postfix for highlighted terms (e.g., `"</b>"`).
    pub highlight_postfix: String,
}

impl Default for SnippetConfig {
    fn default() -> Self {
        Self {
            max_chars: DEFAULT_SNIPPET_MAX_CHARS,
            highlight_prefix: "<b>".to_owned(),
            highlight_postfix: "</b>".to_owned(),
        }
    }
}

// ─── LexicalHit ─────────────────────────────────────────────────────────────

/// An enriched search result from [`TantivyIndex::search_with_snippets`].
///
/// Contains everything in [`ScoredResult`] plus a snippet and query explanation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LexicalHit {
    /// Unique document identifier.
    pub doc_id: String,
    /// BM25 relevance score.
    pub bm25_score: f32,
    /// 0-based rank in the result set.
    pub rank: usize,
    /// Highlighted snippet from the content field, if available.
    pub snippet: Option<String>,
    /// How the query was classified.
    pub query_type: QueryExplanation,
    /// Arbitrary document metadata.
    pub metadata: Option<serde_json::Value>,
}

/// Raw lexical hit containing BM25 score and Tantivy doc address.
///
/// This is useful for callers that need custom field extraction from stored
/// documents while still reusing frankensearch's query execution helpers.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LexicalDocHit {
    /// BM25 relevance score returned by Tantivy.
    pub bm25_score: f32,
    /// 0-based rank in the returned page.
    pub rank: usize,
    /// Tantivy document address inside a segment.
    pub doc_address: DocAddress,
}

/// Paginated lexical search result containing both the matched hits and the
/// total number of documents matching the query.
///
/// The `total_count` reflects **all** matching documents in the index, not just
/// the page returned in `hits`. Clients can use this for pagination UI
/// (e.g., `page 2 of ceil(total_count / page_size)`).
#[derive(Debug, Clone, PartialEq)]
pub struct LexicalSearchResult {
    /// The paginated slice of matching documents.
    pub hits: Vec<LexicalDocHit>,
    /// Total number of documents matching the query across the entire index.
    pub total_count: usize,
}

/// Lightweight lexical hit used by hot paths that only need `doc_id` + score.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LexicalIdHit {
    /// Unique document identifier. `DocId` (`CompactString`, SSO) so the
    /// per-hit id-materialization clone (`ord_table` lookup / docstore) is an
    /// inline memcpy for short ids and needs no `String→CompactString`
    /// re-conversion when it flows into `ScoredResult` at the fusion boundary.
    pub doc_id: DocId,
    /// BM25 relevance score.
    pub bm25_score: f32,
    /// 0-based rank in the returned page.
    pub rank: usize,
}

/// Dev-only ranked oracle evidence retaining Tantivy's full native tie key.
#[cfg(feature = "tantivy-oracle")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OracleRankedHit {
    /// External document identifier used for cross-engine alignment.
    pub doc_id: String,
    /// Exact BM25 score representation.
    pub score_bits: u32,
    /// Native rank in the fetched oracle result list.
    pub rank: usize,
    /// Tantivy segment ordinal (the first half of `DocAddress`).
    pub segment_ord: u32,
    /// Segment-local document ID (the second half of `DocAddress`).
    pub segment_doc_id: u32,
    /// Rendered snippet; `None` remains distinct from an empty snippet.
    pub snippet: Option<String>,
}

/// Dev-only complete observation used by the Quill conformance gauntlet.
#[cfg(feature = "tantivy-oracle")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OracleQueryObservation {
    /// Requested top-k rows in native Tantivy order.
    pub hits: Vec<OracleRankedHit>,
    /// Expanded exact-score group at the top-k cutoff.
    pub cutoff_tie_group: Vec<OracleRankedHit>,
    /// False when the configured expansion budget ended inside the tie group.
    pub cutoff_tie_complete: bool,
    /// Exact total number of matches, independent of top-k.
    pub total_count: usize,
    /// Exact live-document count.
    pub doc_count: usize,
}

/// Dev-only exact counted page used by the Quill replacement witness.
///
/// This is deliberately separate from [`OracleQueryObservation`]: the latter
/// owns cutoff-tie expansion for rank-parity campaigns, while this DTO proves
/// the incumbent's real offset-pagination contract. Shipping callers should
/// not depend on this evidence-only surface.
#[cfg(feature = "tantivy-oracle")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OraclePageObservation {
    /// Ordered page returned by Tantivy's real offset collector.
    pub hits: Vec<OraclePageHit>,
    /// Exact number of matches, independent of `limit` and `offset`.
    pub total_count: usize,
    /// Exact live-document count.
    pub doc_count: usize,
}

/// One ordered hit from [`OraclePageObservation`].
#[cfg(feature = "tantivy-oracle")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OraclePageHit {
    /// Stable external document identifier.
    pub doc_id: String,
    /// Exact BM25 score representation.
    pub score_bits: u32,
    /// Zero-based rank inside this returned page.
    pub page_rank: usize,
    /// Zero-based rank in the complete result stream.
    pub absolute_rank: usize,
}

#[cfg(test)]
std::thread_local! {
    static COUNTED_COLLECTOR_INVOCATIONS: std::cell::Cell<u64> =
        const { std::cell::Cell::new(0) };
    static TOP_K_COLLECTOR_INVOCATIONS: std::cell::Cell<u64> =
        const { std::cell::Cell::new(0) };
}

#[cfg(test)]
fn reset_collector_invocations() {
    COUNTED_COLLECTOR_INVOCATIONS.set(0);
    TOP_K_COLLECTOR_INVOCATIONS.set(0);
}

#[cfg(test)]
fn collector_invocations() -> (u64, u64) {
    (
        COUNTED_COLLECTOR_INVOCATIONS.get(),
        TOP_K_COLLECTOR_INVOCATIONS.get(),
    )
}

/// Execute a pre-built Tantivy query with offset pagination.
/// Execute a Tantivy collector search behind a panic guard.
///
/// The pinned Tantivy 0.26.1 scorer stack contains at least one panic
/// reachable from ordinary user input: a negated phrase whose exact sequence
/// is absent seeks a terminated docset in `PhraseScorer` (bd-nqeb4, found by
/// the bd-bsjw structure-aware campaign). A search engine must degrade, not
/// abort the host process, so the execution boundary converts an engine
/// panic into the same typed error surface as an engine `Err`. The searcher
/// is an immutable snapshot, so the unwind leaves no poisoned state behind.
fn search_guarded<C: tantivy::collector::Collector>(
    searcher: &Searcher,
    query: &dyn tantivy::query::Query,
    collector: &C,
) -> SearchResult<C::Fruit> {
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        searcher.search(query, collector)
    })) {
        Ok(result) => result.map_err(|error| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(error),
        }),
        Err(panic) => {
            let detail = panic
                .downcast_ref::<String>()
                .map(String::as_str)
                .or_else(|| panic.downcast_ref::<&str>().copied())
                .unwrap_or("non-string panic payload");
            warn!(
                panic = detail,
                "tantivy panicked during query execution; degrading to a typed error (bd-nqeb4)"
            );
            Err(SearchError::SubsystemError {
                subsystem: "tantivy",
                source: format!("tantivy panicked during query execution: {detail}").into(),
            })
        }
    }
}

///
/// This helper centralizes error mapping and result-shape normalization so
/// downstream callers can keep custom query construction while reusing the
/// lexical execution core from this crate.
///
/// # Errors
///
/// Returns [`SearchError::SubsystemError`] when Tantivy search fails.
#[instrument(skip(searcher, query), fields(limit = limit, offset = offset))]
pub fn execute_query_with_offset(
    searcher: &Searcher,
    query: &dyn tantivy::query::Query,
    limit: usize,
    offset: usize,
) -> SearchResult<LexicalSearchResult> {
    #[cfg(test)]
    COUNTED_COLLECTOR_INVOCATIONS.set(COUNTED_COLLECTOR_INVOCATIONS.get().saturating_add(1));

    if limit == 0 {
        let total_count = search_guarded(searcher, query, &Count)?;
        return Ok(LexicalSearchResult {
            hits: Vec::new(),
            total_count,
        });
    }

    let (top_docs, total_count) = search_guarded(
        searcher,
        query,
        &(
            TopDocs::with_limit(limit)
                .and_offset(offset)
                .order_by_score(),
            Count,
        ),
    )?;

    let hits = top_docs
        .into_iter()
        .enumerate()
        .map(|(rank, (bm25_score, doc_address))| LexicalDocHit {
            bm25_score,
            rank,
            doc_address,
        })
        .collect();

    Ok(LexicalSearchResult { hits, total_count })
}

/// Execute a query for the top-`limit` hits by BM25 score without computing the
/// total match count.
///
/// Unlike [`execute_query_with_offset`], this omits the [`Count`] collector.
/// `Count` must visit every matching document, while this ID-only path only
/// needs the ranked page.
///
/// # Errors
///
/// Returns [`SearchError::SubsystemError`] when Tantivy search fails.
pub fn execute_top_k(
    searcher: &Searcher,
    query: &dyn tantivy::query::Query,
    limit: usize,
    offset: usize,
) -> SearchResult<Vec<LexicalDocHit>> {
    if limit == 0 {
        return Ok(Vec::new());
    }

    #[cfg(test)]
    TOP_K_COLLECTOR_INVOCATIONS.set(TOP_K_COLLECTOR_INVOCATIONS.get().saturating_add(1));

    let top_docs = search_guarded(
        searcher,
        query,
        &TopDocs::with_limit(limit)
            .and_offset(offset)
            .order_by_score(),
    )?;

    Ok(top_docs
        .into_iter()
        .enumerate()
        .map(|(rank, (bm25_score, doc_address))| LexicalDocHit {
            bm25_score,
            rank,
            doc_address,
        })
        .collect())
}

/// Load a stored Tantivy document by address.
///
/// # Errors
///
/// Returns [`SearchError::SubsystemError`] when document loading fails.
pub fn load_doc(searcher: &Searcher, doc_address: DocAddress) -> SearchResult<TantivyDocument> {
    searcher
        .doc(doc_address)
        .map_err(|e| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(e),
        })
}

/// Try to build a snippet generator for a query/content field pair.
///
/// Returns `None` if snippet generation cannot be initialized. This mirrors the
/// tolerant behavior used by `search_with_snippets`.
#[must_use]
pub fn try_build_snippet_generator(
    searcher: &Searcher,
    query: &dyn tantivy::query::Query,
    content_field: Field,
    snippet_config: &SnippetConfig,
) -> Option<tantivy::snippet::SnippetGenerator> {
    match tantivy::snippet::SnippetGenerator::create(searcher, query, content_field) {
        Ok(mut generator) => {
            generator.set_max_num_chars(snippet_config.max_chars);
            Some(generator)
        }
        Err(e) => {
            debug!(error = %e, "failed to create snippet generator, snippets will be absent");
            None
        }
    }
}

/// Render snippet HTML for a document with caller-specified highlight tags.
#[must_use]
pub fn render_snippet_html(
    snippet_generator: &tantivy::snippet::SnippetGenerator,
    doc: &TantivyDocument,
    highlight_prefix: &str,
    highlight_postfix: &str,
) -> Option<String> {
    let mut snippet = snippet_generator.snippet_from_doc(doc);
    snippet.set_snippet_prefix_postfix(highlight_prefix, highlight_postfix);
    let html = snippet.to_html();
    if html.is_empty() { None } else { Some(html) }
}

// ─── Schema fields ──────────────────────────────────────────────────────────

/// Named fields from the Tantivy schema for type-safe access.
#[derive(Debug, Clone, Copy)]
struct SchemaFields {
    id: Field,
    content: Field,
    title: Field,
    metadata_json: Field,
    /// Dense per-document insertion ordinal, stored as a `u64` FAST (columnar)
    /// field. `None` for indexes created before this field existed (resolved by
    /// name in `from_index`); such indexes materialize ids via the docstore.
    ord: Option<Field>,
}

/// Build the frankensearch Tantivy schema.
fn build_schema() -> (Schema, SchemaFields) {
    build_schema_with_positions(true)
}

fn build_schema_with_positions(positions: bool) -> (Schema, SchemaFields) {
    let mut builder = Schema::builder();

    // ID: exact-match only, stored for retrieval.
    let id = builder.add_text_field("id", STRING | STORED);

    // Content: full-text indexed with our custom tokenizer, stored for snippet use.
    let index_record_option = if positions {
        tantivy::schema::IndexRecordOption::WithFreqsAndPositions
    } else {
        tantivy::schema::IndexRecordOption::Basic
    };
    let content_options = TextOptions::default()
        .set_indexing_options(
            TextFieldIndexing::default()
                .set_tokenizer(TOKENIZER_NAME)
                .set_index_option(index_record_option),
        )
        .set_stored();
    let content = builder.add_text_field("content", content_options);

    // Title: full-text indexed with our custom tokenizer, stored.
    let title_options = TextOptions::default()
        .set_indexing_options(
            TextFieldIndexing::default()
                .set_tokenizer(TOKENIZER_NAME)
                .set_index_option(index_record_option),
        )
        .set_stored();
    let title = builder.add_text_field("title", title_options);

    // Metadata: stored as JSON string, not indexed.
    let metadata_json = builder.add_text_field("metadata_json", STORED);

    // Dense insertion ordinal: a flat bit-packed `u64` FAST column (no
    // dictionary) plus an external `ordinal -> doc_id` table lets id
    // materialization skip the stored-document decompress entirely. STORED too
    // so the table can be rebuilt from a reopened index if needed.
    let ord = builder.add_u64_field("ord", FAST | STORED);

    let schema = builder.build();
    let fields = SchemaFields {
        id,
        content,
        title,
        metadata_json,
        ord: Some(ord),
    };
    (schema, fields)
}

#[cfg(feature = "bench-internals")]
fn validate_benchmark_writer_threads(writer_threads: usize) -> SearchResult<()> {
    if writer_threads == 0 {
        return Err(SearchError::InvalidConfig {
            field: "tantivy.writer_threads".to_owned(),
            value: writer_threads.to_string(),
            reason: "benchmark writer thread count must be positive".to_owned(),
        });
    }
    Ok(())
}

/// Which Tantivy writer constructor a benchmark index literally called.
///
/// This is a constructor identity, not a request record: `ShippingAuto` means
/// [`Index::writer`] was called and Tantivy chose the pool width itself;
/// `Fixed` means [`Index::writer_with_num_threads`] was called with exactly
/// the recorded width.
#[cfg(feature = "bench-internals")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BenchmarkWriterMode {
    /// The shipping default path: `Index::writer(heap)`.
    ShippingAuto,
    /// The pinned path: `Index::writer_with_num_threads(threads, heap)`.
    Fixed {
        /// Exact width handed to Tantivy.
        threads: usize,
    },
}

/// Writer-pool width, and whether it is authenticated or merely unknown.
///
/// Tantivy 0.26.1 computes the `ShippingAuto` width inside `Index::writer`
/// from `available_parallelism()` clamped by the heap budget, and exposes no
/// accessor for it — `pub fn num_threads` does not exist anywhere in that
/// crate. Recomputing it here would mean copying `MAX_NUM_THREAD` and
/// `MEMORY_BUDGET_NUM_BYTES_MIN` into this crate and presenting an inference
/// as an observation, which would drift silently on any version bump. The
/// unknown is therefore typed, not filled in.
#[cfg(feature = "bench-internals")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BenchmarkMaterializedWidth {
    /// The exact width Tantivy was given and used.
    Authenticated(usize),
    /// No trustworthy width is observable; evidence needing one must fail closed.
    Unobservable {
        /// Why the width cannot be authenticated.
        reason: BenchmarkWidthUnobservableReason,
    },
}

#[cfg(feature = "bench-internals")]
impl BenchmarkMaterializedWidth {
    /// The authenticated width, or `None` when no width is observable.
    #[must_use]
    pub const fn authenticated(self) -> Option<usize> {
        match self {
            Self::Authenticated(threads) => Some(threads),
            Self::Unobservable { .. } => None,
        }
    }
}

/// Why a width is not authenticated.
///
/// Typed and version-neutral on purpose: the receipt states *that* the
/// incumbent selects the width internally and publishes no accessor, which
/// stays true across upgrades, instead of pinning a version string that would
/// silently become a lie on the next bump.
#[cfg(feature = "bench-internals")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BenchmarkWidthUnobservableReason {
    /// The engine chose the pool width inside its own constructor and exposes
    /// no accessor for the value it chose.
    EngineSelectedWidthNotExposed,
}

/// Which writer construction the caller explicitly asked for.
///
/// The plan, not the thread count, decides whether a benchmark receipt exists.
/// Inferring "benchmark" from `writer_threads: None` made every ordinary
/// `create`/`open`/`in_memory` index carry a shipping-auto receipt it never
/// asked for, which would let ordinary constructions masquerade as screened
/// benchmark candidates.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WriterPlan {
    /// Ordinary shipping construction through Tantivy's own width selection.
    /// Never produces a benchmark receipt.
    Shipping,
    /// Ordinary construction at a pinned width. Never produces a benchmark
    /// receipt either.
    ///
    /// Width and receipt are independent axes. Collapsing this into
    /// `Shipping` silently moved the single-threaded oracle off
    /// `writer_with_num_threads(1, heap)` and onto Tantivy's auto selection —
    /// a real behaviour change bought only to express "no receipt".
    ///
    /// Gated with its only constructor, so the default build carries no
    /// variant that nothing can build.
    #[cfg(feature = "tantivy-oracle")]
    PinnedWidth(usize),
    /// Explicit benchmark construction through Tantivy's own width selection.
    #[cfg(feature = "bench-internals")]
    BenchmarkShippingAuto,
    /// Explicit benchmark construction at a pinned width.
    #[cfg(feature = "bench-internals")]
    BenchmarkFixed(usize),
}

#[cfg(feature = "bench-internals")]
impl WriterPlan {
    /// Width recorded on the benchmark accessor.
    ///
    /// Only a benchmark plan reports one: `PinnedWidth` pins a width without
    /// claiming any screening identity. Gated with the field it feeds, so the
    /// default build has no unreachable helper to warn about.
    const fn benchmark_threads(self) -> Option<usize> {
        match self {
            Self::BenchmarkFixed(threads) => Some(threads),
            Self::Shipping | Self::BenchmarkShippingAuto => None,
            #[cfg(feature = "tantivy-oracle")]
            Self::PinnedWidth(_) => None,
        }
    }
}

/// Read the positions setting back out of a live index schema.
///
/// The benchmark reopen path receives a caller's `positions` claim but attaches
/// to a schema that already exists, so the claim is an assertion about someone
/// else's bytes. This reads the indexing option actually recorded on the
/// `content` field, which is the only authority.
#[cfg(feature = "bench-internals")]
fn positions_from_live_schema(schema: &Schema) -> Option<bool> {
    let field = schema.get_field("content").ok()?;
    match schema.get_field_entry(field).field_type() {
        tantivy::schema::FieldType::Str(options) => {
            options.get_indexing_options().map(|indexing| {
                indexing.index_option() == tantivy::schema::IndexRecordOption::WithFreqsAndPositions
            })
        }
        _ => None,
    }
}

/// Typed receipt for one benchmark writer construction.
///
/// Oracle identity is exactly what this crate can authenticate in-process: the
/// tokenizer name actually registered, the field names actually present in the
/// live index schema, and the positions flag that built that schema. Tantivy's
/// crate version and source identity are deliberately absent — they are not
/// observable here, and asserting them would be a restatement that can drift.
#[cfg(feature = "bench-internals")]
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct BenchmarkWriterReceipt {
    /// Which constructor was called.
    pub mode: BenchmarkWriterMode,
    /// Heap budget handed to that constructor.
    pub writer_heap_bytes: usize,
    /// Authenticated width, or a typed unknown.
    pub materialized_width: BenchmarkMaterializedWidth,
    /// Positions option read back from the live index schema.
    pub positions: bool,
    /// Field names present in the live index schema, in schema order.
    pub schema_fields: Vec<String>,
    /// Tokenizer registered on this index. Owned so the whole receipt can be
    /// bound into an artifact without borrowing this crate's statics.
    pub tokenizer_name: String,
    /// Whether this writer replaced an earlier joined writer.
    pub writer_rearmed: bool,
}

/// One-shot live capability for a benchmark writer that was actually created.
///
/// This is deliberately neither `Clone` nor serializable/deserializable: it is
/// an in-process hand-off from the successful constructor branch to a live
/// benchmark consumer, not a persisted authentication claim. The descriptive
/// [`BenchmarkWriterReceipt`] remains available separately for diagnostics.
#[cfg(feature = "bench-internals")]
#[doc(hidden)]
#[derive(Debug)]
pub struct BenchmarkWriterAttestation {
    receipt: BenchmarkWriterReceipt,
    construction_id: u64,
}

#[cfg(feature = "bench-internals")]
impl BenchmarkWriterAttestation {
    /// Mint an attestation only after its writer constructor has succeeded.
    fn mint(receipt: BenchmarkWriterReceipt) -> Self {
        let construction_id = NEXT_BENCHMARK_WRITER_CONSTRUCTION_ID
            .try_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                current.checked_add(1)
            })
            .expect("benchmark writer construction IDs exhausted");
        Self {
            receipt,
            construction_id,
        }
    }

    /// Return the authenticated receipt carried by this live capability.
    #[must_use]
    pub const fn receipt(&self) -> &BenchmarkWriterReceipt {
        &self.receipt
    }

    /// Return this process-local writer-construction identity.
    #[must_use]
    pub const fn construction_id(&self) -> u64 {
        self.construction_id
    }
}

#[cfg(feature = "bench-internals")]
impl BenchmarkWriterReceipt {
    /// Seed a receipt from the constructor branch that actually ran.
    ///
    /// `mode` is produced by the branch itself rather than passed in beside it,
    /// so the recorded mode and heap cannot drift from the `Index::writer` or
    /// `writer_with_num_threads` call that really happened. `positions` is read
    /// back from the live schema, never from a caller's claim.
    fn seed(
        mode: BenchmarkWriterMode,
        writer_heap_bytes: usize,
        index: &Index,
    ) -> SearchResult<Self> {
        let materialized_width = match mode {
            BenchmarkWriterMode::ShippingAuto => BenchmarkMaterializedWidth::Unobservable {
                reason: BenchmarkWidthUnobservableReason::EngineSelectedWidthNotExposed,
            },
            BenchmarkWriterMode::Fixed { threads } => {
                BenchmarkMaterializedWidth::Authenticated(threads)
            }
        };
        let schema = index.schema();
        // Absent positions evidence is a missing fact, not a false one. A
        // defaulted `false` would put an unearned claim into every artifact
        // this receipt is later bound into.
        let positions =
            positions_from_live_schema(&schema).ok_or_else(|| SearchError::InvalidConfig {
                field: "tantivy.positions".to_owned(),
                value: "unavailable".to_owned(),
                reason: "live index schema exposes no indexed content field, so the positions \
                         option cannot be authenticated"
                    .to_owned(),
            })?;
        Ok(Self {
            mode,
            writer_heap_bytes,
            materialized_width,
            positions,
            schema_fields: schema
                .fields()
                .map(|(_, entry)| entry.name().to_owned())
                .collect(),
            tokenizer_name: TOKENIZER_NAME.to_owned(),
            writer_rearmed: false,
        })
    }
}

/// Reject a benchmark caller whose `positions` claim disagrees with the schema
/// it is actually attaching to.
///
/// Creating an index builds the schema from this flag, but reopening one only
/// asserts about bytes that already exist. A silent disagreement would put a
/// false positions value into every downstream receipt.
#[cfg(feature = "bench-internals")]
fn reject_positions_disagreement(index: &Index, claimed: bool) -> SearchResult<()> {
    let observed =
        positions_from_live_schema(&index.schema()).ok_or_else(|| SearchError::InvalidConfig {
            field: "tantivy.positions".to_owned(),
            value: claimed.to_string(),
            reason: "live index schema exposes no indexed content field to authenticate positions"
                .to_owned(),
        })?;
    if observed == claimed {
        return Ok(());
    }
    Err(SearchError::InvalidConfig {
        field: "tantivy.positions".to_owned(),
        value: claimed.to_string(),
        reason: format!("live index schema records positions = {observed}"),
    })
}

/// Fused equivalent of Tantivy's `SimpleTokenizer` followed by `LowerCaser`.
///
/// ASCII characters are classified directly from their byte and each token is
/// lowercased without the generic lowercaser's extra `is_ascii` scan. Non-ASCII
/// characters retain the exact `char::is_alphanumeric` and `char::to_lowercase`
/// behavior of the former two-stage analyzer.
#[derive(Clone, Default)]
struct FrankensearchTokenizer {
    token: Token,
}

struct FrankensearchTokenStream<'a> {
    text: &'a str,
    cursor: usize,
    token: &'a mut Token,
}

#[inline]
fn tokenizer_next_char(text: &str, offset: usize) -> Option<(char, usize)> {
    let remaining = text.get(offset..)?;
    let first = *remaining.as_bytes().first()?;
    if first.is_ascii() {
        Some((char::from(first), offset + 1))
    } else {
        let ch = remaining.chars().next()?;
        Some((ch, offset + ch.len_utf8()))
    }
}

#[inline]
fn tokenizer_is_alphanumeric(ch: char) -> bool {
    if ch.is_ascii() {
        ch.is_ascii_alphanumeric()
    } else {
        ch.is_alphanumeric()
    }
}

impl Tokenizer for FrankensearchTokenizer {
    type TokenStream<'a> = FrankensearchTokenStream<'a>;

    fn token_stream<'a>(&'a mut self, text: &'a str) -> Self::TokenStream<'a> {
        self.token.reset();
        FrankensearchTokenStream {
            text,
            cursor: 0,
            token: &mut self.token,
        }
    }
}

impl TokenStream for FrankensearchTokenStream<'_> {
    fn advance(&mut self) -> bool {
        self.token.text.clear();
        self.token.position = self.token.position.wrapping_add(1);

        while let Some((ch, next_cursor)) = tokenizer_next_char(self.text, self.cursor) {
            if !tokenizer_is_alphanumeric(ch) {
                self.cursor = next_cursor;
                continue;
            }

            let offset_from = self.cursor;
            let mut offset_to = next_cursor;
            let mut resume_at = next_cursor;
            let mut all_ascii = ch.is_ascii();
            while let Some((next_ch, after_next)) = tokenizer_next_char(self.text, resume_at) {
                if !tokenizer_is_alphanumeric(next_ch) {
                    resume_at = after_next;
                    break;
                }
                all_ascii &= next_ch.is_ascii();
                offset_to = after_next;
                resume_at = after_next;
            }

            self.token.offset_from = offset_from;
            self.token.offset_to = offset_to;
            let source = &self.text[offset_from..offset_to];
            if all_ascii {
                self.token.text.push_str(source);
                self.token.text.make_ascii_lowercase();
            } else {
                for source_char in source.chars() {
                    self.token.text.extend(source_char.to_lowercase());
                }
            }
            self.cursor = resume_at;
            return true;
        }
        false
    }

    fn token(&self) -> &Token {
        self.token
    }

    fn token_mut(&mut self) -> &mut Token {
        self.token
    }
}

/// Build and register the custom tokenizer.
///
/// Semantics match `SimpleTokenizer` (split on non-alphanumeric characters)
/// followed by `LowerCaser`. `POL-358` therefore becomes `pol`, `358`. For
/// hyphen-preserving tokenization see `cass_ensure_tokenizer`.
fn build_tokenizer() -> TextAnalyzer {
    TextAnalyzer::from(FrankensearchTokenizer::default())
}

/// Return the production analyzer for a same-binary benchmark comparator.
#[cfg(feature = "bench-internals")]
#[doc(hidden)]
#[must_use]
pub fn default_tokenizer_for_bench() -> TextAnalyzer {
    build_tokenizer()
}

// ─── TantivyIndex ───────────────────────────────────────────────────────────

/// Counted receipt for a benchmark-only Tantivy writer lifecycle fence.
///
/// `wait_merging_threads` consumes Tantivy's writer after joining its indexing
/// and segment-updater workers. Warm/update fixtures may rearm the same index
/// with the pinned writer configuration, while terminal bulk measurements
/// deliberately stop after the join so they do not construct and immediately
/// discard an unused replacement writer.
#[cfg(feature = "bench-internals")]
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct BenchmarkWriterJoinReceipt {
    /// Searchable segment count immediately before joining the writer.
    pub searchable_segments_before: usize,
    /// Searchable segment count after every background worker has joined.
    pub searchable_segments_after: usize,
    /// Time spent inside Tantivy's worker/merge join, excluding writer rearm.
    pub join_elapsed_ns: u64,
    /// Whether a replacement writer was successfully constructed after joining.
    pub writer_rearmed: bool,
}

/// Read-only Tantivy search handle retained across a terminal writer join.
///
/// This deliberately owns no writer.  A terminal benchmark obtains it only by
/// consuming [`TantivyIndex`] through
/// [`TantivyIndex::benchmark_join_workers_retaining_reader`], which joins the
/// real Tantivy workers first and leaves this handle alive for the required
/// post-join searchable-tail query.
#[cfg(feature = "bench-internals")]
#[doc(hidden)]
pub struct BenchmarkRetainedTantivyReader {
    fields: SchemaFields,
    reader: IndexReader,
}

#[cfg(feature = "bench-internals")]
impl BenchmarkRetainedTantivyReader {
    /// Run an exact stored-ID query through the reader retained after a writer
    /// join.
    ///
    /// This is intentionally a narrow benchmark seam rather than a general
    /// second lexical API: it proves that the terminal prepared-tail document
    /// is searchable *after* workers have quiesced, without creating or
    /// rearming a writer.
    ///
    /// # Errors
    ///
    /// Returns a typed Tantivy search failure.
    pub fn benchmark_search_exact_id(&self, document_id: &str) -> SearchResult<Vec<DocId>> {
        let query = TermQuery::new(
            Term::from_field_text(self.fields.id, document_id),
            IndexRecordOption::Basic,
        );
        let searcher = self.reader.searcher();
        let top_docs = search_guarded(&searcher, &query, &TopDocs::with_limit(2).order_by_score())?;

        // The exact `id` term itself authenticates membership.  Do not add a
        // stored-document hydration that Quill's matching IDHASH probe does
        // not pay; terminal proof cost is part of the timed lifecycle.
        Ok(top_docs
            .into_iter()
            .map(|_| document_id.to_owned().into())
            .collect())
    }
}

/// Ordered searchable-segment geometry from the pinned Tantivy oracle.
///
/// This conformance-only receipt preserves Tantivy's native `segment_ord`
/// assignment as well as physical and live document counts. It is absent from
/// normal shipping builds.
#[cfg(feature = "tantivy-oracle")]
#[doc(hidden)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OracleSegmentLayout {
    /// Native Tantivy segment ordinal used in `DocAddress` tie-breaking.
    pub segment_ord: u32,
    /// Physical document cardinality, including deleted rows.
    pub max_doc: u32,
    /// Live document cardinality.
    pub num_docs: u32,
}

/// High bit marks a nonce as armed but not yet observed by the directory.
#[cfg(feature = "bench-internals")]
const BENCHMARK_DIRECTORY_SYNC_ARMED: u64 = 1 << 63;

/// Terminal state for an armed nonce that saw more than one directory sync.
#[cfg(feature = "bench-internals")]
const BENCHMARK_DIRECTORY_SYNC_AMBIGUOUS: u64 = u64::MAX;

/// Shared state between the benchmark-only directory wrapper and its caller.
///
/// The arm is installed before the timed interval. A successful real
/// `Directory::sync_directory` changes `ARMED(nonce)` into `OBSERVED(nonce)`;
/// a second successful call changes it into the ambiguous terminal state. The
/// state intentionally records neither a caller-supplied treatment label nor a
/// timestamp: Tantivy's real directory call is the observation.
#[cfg(feature = "bench-internals")]
#[derive(Debug)]
struct BenchmarkDirectorySyncState {
    next_nonce: AtomicU64,
    session: AtomicU64,
}

#[cfg(feature = "bench-internals")]
impl BenchmarkDirectorySyncState {
    fn new() -> Self {
        Self {
            next_nonce: AtomicU64::new(1),
            session: AtomicU64::new(0),
        }
    }

    fn arm(&self) -> SearchResult<u64> {
        let nonce = self
            .next_nonce
            .try_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
                (current < BENCHMARK_DIRECTORY_SYNC_ARMED - 1).then_some(current + 1)
            })
            .map_err(|_| SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync_nonce".to_owned(),
                value: "exhausted".to_owned(),
                reason: "benchmark directory-sync session nonce space exhausted".to_owned(),
            })?;
        self.session
            .compare_exchange(
                0,
                nonce | BENCHMARK_DIRECTORY_SYNC_ARMED,
                Ordering::AcqRel,
                Ordering::Acquire,
            )
            .map_err(|_| SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync_session".to_owned(),
                value: "already_armed".to_owned(),
                reason: "a previous benchmark directory-sync observation is still active"
                    .to_owned(),
            })?;
        Ok(nonce)
    }

    fn observe_successful_sync(&self) {
        loop {
            let current = self.session.load(Ordering::Acquire);
            if current == 0 || current == BENCHMARK_DIRECTORY_SYNC_AMBIGUOUS {
                return;
            }
            let next = if current & BENCHMARK_DIRECTORY_SYNC_ARMED != 0 {
                current & !BENCHMARK_DIRECTORY_SYNC_ARMED
            } else {
                BENCHMARK_DIRECTORY_SYNC_AMBIGUOUS
            };
            if self
                .session
                .compare_exchange(current, next, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                return;
            }
        }
    }
}

/// Transparent `MmapDirectory` observer used only by the QG-4 benchmark path.
///
/// It delegates all Tantivy directory behavior. Only a successful delegated
/// directory sync updates the shared observation state.
#[cfg(feature = "bench-internals")]
#[derive(Clone, Debug)]
struct ObservedMmapDirectory {
    inner: MmapDirectory,
    state: Arc<BenchmarkDirectorySyncState>,
}

#[cfg(feature = "bench-internals")]
impl ObservedMmapDirectory {
    fn open(
        path: &Path,
        state: Arc<BenchmarkDirectorySyncState>,
    ) -> Result<Self, OpenDirectoryError> {
        Ok(Self {
            inner: MmapDirectory::open(path)?,
            state,
        })
    }
}

#[cfg(feature = "bench-internals")]
impl Directory for ObservedMmapDirectory {
    fn get_file_handle(&self, path: &Path) -> Result<Arc<dyn FileHandle>, OpenReadError> {
        self.inner.get_file_handle(path)
    }

    fn delete(&self, path: &Path) -> Result<(), DeleteError> {
        self.inner.delete(path)
    }

    fn exists(&self, path: &Path) -> Result<bool, OpenReadError> {
        self.inner.exists(path)
    }

    fn open_write(&self, path: &Path) -> Result<WritePtr, OpenWriteError> {
        self.inner.open_write(path)
    }

    fn atomic_read(&self, path: &Path) -> Result<Vec<u8>, OpenReadError> {
        self.inner.atomic_read(path)
    }

    fn atomic_write(&self, path: &Path, data: &[u8]) -> std::io::Result<()> {
        self.inner.atomic_write(path, data)
    }

    fn sync_directory(&self) -> std::io::Result<()> {
        let result = self.inner.sync_directory();
        if result.is_ok() {
            self.state.observe_successful_sync();
        }
        result
    }

    fn acquire_lock(&self, lock: &Lock) -> Result<DirectoryLock, LockError> {
        self.inner.acquire_lock(lock)
    }

    fn watch(&self, watch_callback: WatchCallback) -> tantivy::Result<WatchHandle> {
        self.inner.watch(watch_callback)
    }
}

/// Live arm for one controlled QG-4 Tantivy commit observation.
///
/// Construct this immediately before the timed benchmark commit and call
/// [`Self::finish`] after the timer stops. It is neither serializable nor
/// cloneable, so a caller cannot replay it as a declarative receipt.
#[cfg(feature = "bench-internals")]
#[doc(hidden)]
#[derive(Debug)]
pub struct BenchmarkTantivyDirectorySyncArm {
    state: Arc<BenchmarkDirectorySyncState>,
    root: PathBuf,
    nonce: u64,
    commit_opstamp: Option<u64>,
    finished: bool,
}

/// Engine-observed result of one controlled QG-4 Tantivy commit.
#[cfg(feature = "bench-internals")]
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BenchmarkTantivyDirectorySyncReceipt {
    /// On-disk root whose wrapped Tantivy directory emitted the observation.
    pub root: PathBuf,
    /// Opaque session identity minted before the timed commit.
    pub session_nonce: u64,
    /// Opstamp returned by the same blocking Tantivy commit.
    pub commit_opstamp: u64,
    /// Successful directory-sync calls observed in the armed session.
    pub observed_sync_count: u8,
}

#[cfg(feature = "bench-internals")]
impl BenchmarkTantivyDirectorySyncArm {
    /// Finalize the receipt outside the timed interval.
    ///
    /// # Errors
    ///
    /// Returns an error when the timed commit did not retain its opstamp or
    /// the armed directory-sync session observed anything other than exactly
    /// one successful sync for this arm.
    pub fn finish(&mut self) -> SearchResult<BenchmarkTantivyDirectorySyncReceipt> {
        let observed = self.state.session.swap(0, Ordering::AcqRel);
        self.finished = true;
        if observed == self.nonce {
            let commit_opstamp =
                self.commit_opstamp
                    .take()
                    .ok_or_else(|| SearchError::InvalidConfig {
                        field: "tantivy.qg4.directory_sync_receipt".to_owned(),
                        value: "missing_commit_opstamp".to_owned(),
                        reason: "the armed QG-4 commit did not stamp Tantivy's returned opstamp"
                            .to_owned(),
                    })?;
            return Ok(BenchmarkTantivyDirectorySyncReceipt {
                root: self.root.clone(),
                session_nonce: self.nonce,
                commit_opstamp,
                observed_sync_count: 1,
            });
        }
        let (value, reason) = if observed == (self.nonce | BENCHMARK_DIRECTORY_SYNC_ARMED) {
            (
                "zero_syncs",
                "the timed commit returned without an observed successful directory sync",
            )
        } else if observed == BENCHMARK_DIRECTORY_SYNC_AMBIGUOUS {
            (
                "multiple_syncs",
                "more than one successful directory sync occurred while the session was armed",
            )
        } else {
            (
                "foreign_or_disarmed_session",
                "the armed directory-sync session was replaced or cleared before finalization",
            )
        };
        Err(SearchError::InvalidConfig {
            field: "tantivy.qg4.directory_sync_receipt".to_owned(),
            value: value.to_owned(),
            reason: reason.to_owned(),
        })
    }
}

#[cfg(feature = "bench-internals")]
impl Drop for BenchmarkTantivyDirectorySyncArm {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        let armed = self.nonce | BENCHMARK_DIRECTORY_SYNC_ARMED;
        let _ = self
            .state
            .session
            .compare_exchange(armed, 0, Ordering::AcqRel, Ordering::Acquire);
        let _ =
            self.state
                .session
                .compare_exchange(self.nonce, 0, Ordering::AcqRel, Ordering::Acquire);
        let _ = self.state.session.compare_exchange(
            BENCHMARK_DIRECTORY_SYNC_AMBIGUOUS,
            0,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
    }
}

/// A Tantivy-backed full-text search index implementing [`LexicalSearch`].
///
/// Thread-safe for concurrent reads. Writes are serialized internally via
/// the Tantivy `IndexWriter` (which requires `&mut self` for `add_document`
/// but is wrapped here for the trait interface).
pub struct TantivyIndex {
    index: Index,
    fields: SchemaFields,
    reader: IndexReader,
    writer: Mutex<IndexWriter>,
    doc_count: AtomicUsize,
    /// Append-only `ordinal -> doc_id` table backing the fast id-materialization
    /// path. Index `i` holds the `doc_id` of the document assigned ordinal `i`.
    /// Grows by one per indexed document (including re-upserts); ordinals are
    /// monotonic and never reused, so it stays correct across deletes/merges
    /// (a deleted doc's ordinal simply never appears in search results).
    ord_table: RwLock<Vec<DocId>>,
    path: Option<PathBuf>,
    /// Exact writer-pool width accepted by Tantivy's benchmark constructor.
    #[cfg(feature = "bench-internals")]
    benchmark_writer_threads: Option<usize>,
    /// Typed receipt for the benchmark writer construction, when this index
    /// was built through a benchmark seam.
    #[cfg(feature = "bench-internals")]
    benchmark_writer_receipt: Option<BenchmarkWriterReceipt>,
    /// One-shot live attestation for the benchmark writer construction.
    #[cfg(feature = "bench-internals")]
    benchmark_writer_attestation: Option<BenchmarkWriterAttestation>,
    /// Shared only with the benchmark-created on-disk directory wrapper.
    #[cfg(feature = "bench-internals")]
    benchmark_directory_sync_state: Option<Arc<BenchmarkDirectorySyncState>>,
    /// Set only by the fresh-fixture QG-4 no-merge setup API.
    #[cfg(feature = "bench-internals")]
    benchmark_qg4_no_merge_prepared: AtomicBool,
    /// Which Tantivy writer constructor this index actually invoked.
    ///
    /// Per-instance and test-only: a plan or receipt records what the caller
    /// *asked for*, so a test reading either proves nothing about the call that
    /// ran. This is written by the helper that performs the call itself. It is
    /// deliberately not a global counter — parallel tests would race one.
    #[cfg(test)]
    observed_writer_call: WriterCall,
}

/// The Tantivy writer constructor a `TantivyIndex` actually invoked.
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WriterCall {
    /// `Index::writer(heap)` — Tantivy selected the width.
    Auto,
    /// `Index::writer_with_num_threads(threads, heap)`.
    ///
    /// Gated exactly as `call_fixed_writer` is: the only thing that can build
    /// this variant is that helper, so without those features it would be a
    /// variant nothing constructs.
    #[cfg(any(feature = "tantivy-oracle", feature = "bench-internals"))]
    Fixed(usize),
}

/// Perform the shipping-auto Tantivy call, recording that it was the one made.
fn call_auto_writer(
    index: &Index,
    writer_heap_bytes: usize,
    #[cfg(test)] observed: &mut WriterCall,
) -> tantivy::Result<IndexWriter> {
    #[cfg(test)]
    {
        *observed = WriterCall::Auto;
    }
    index.writer(writer_heap_bytes)
}

/// Perform the pinned-width Tantivy call, recording that it was the one made.
///
/// Gated to the features that actually reach it — the oracle's pinned plan and
/// the benchmark seams — so the default build has no helper without a caller.
#[cfg(any(feature = "tantivy-oracle", feature = "bench-internals"))]
fn call_fixed_writer(
    index: &Index,
    threads: usize,
    writer_heap_bytes: usize,
    #[cfg(test)] observed: &mut WriterCall,
) -> tantivy::Result<IndexWriter> {
    #[cfg(test)]
    {
        *observed = WriterCall::Fixed(threads);
    }
    index.writer_with_num_threads(threads, writer_heap_bytes)
}

impl std::fmt::Debug for TantivyIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TantivyIndex")
            .field(
                "staged_doc_count_hint",
                &self.doc_count.load(Ordering::Relaxed),
            )
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

impl TantivyIndex {
    fn checked_searcher_doc_count(searcher: &Searcher) -> SearchResult<usize> {
        usize::try_from(searcher.num_docs()).map_err(|_| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: "current Tantivy reader document count does not fit usize".into(),
        })
    }

    fn map_writer_lock_error(phase: &str, error: asupersync::sync::LockError) -> SearchError {
        match error {
            asupersync::sync::LockError::Poisoned => SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(std::io::Error::other("writer mutex poisoned")),
            },
            asupersync::sync::LockError::Cancelled => SearchError::Cancelled {
                phase: phase.into(),
                reason: "writer lock cancelled".into(),
            },
            asupersync::sync::LockError::PolledAfterCompletion => SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(std::io::Error::other(format!(
                    "writer mutex future reused after completion during {phase}"
                ))),
            },
            asupersync::sync::LockError::TimedOut(deadline) => SearchError::Cancelled {
                phase: phase.into(),
                reason: format!("writer lock timed out at {deadline:?}"),
            },
        }
    }

    /// Return the writer-pool width successfully materialized by the
    /// benchmark-only Tantivy constructor.
    ///
    /// `None` means no width is authenticated, which is the honest answer for
    /// the shipping-auto path; it is never a stand-in for an inferred width.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    #[must_use]
    pub const fn benchmark_materialized_writer_threads(&self) -> Option<usize> {
        self.benchmark_writer_threads
    }

    /// Typed receipt for the benchmark writer this index was constructed with.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    #[must_use]
    pub const fn benchmark_writer_receipt(&self) -> Option<&BenchmarkWriterReceipt> {
        self.benchmark_writer_receipt.as_ref()
    }

    /// Take the one-shot live attestation for this benchmark writer.
    ///
    /// The attestation is minted only after the writer constructor succeeds.
    /// Taking it does not remove the descriptive receipt, so a later rearm can
    /// mint a fresh attestation for the replacement writer.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn take_benchmark_writer_attestation(&mut self) -> Option<BenchmarkWriterAttestation> {
        self.benchmark_writer_attestation.take()
    }

    /// Construct an in-memory oracle through Tantivy's **shipping** writer
    /// selection: `Index::writer(heap)` is called literally, and the resulting
    /// pool width is reported as unobservable rather than guessed.
    ///
    /// # Errors
    ///
    /// Returns the ordinary Tantivy writer-construction error, including the
    /// heap-too-small case, which stays fail-closed here.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn in_memory_with_shipping_auto_writer(
        writer_heap_bytes: usize,
        positions: bool,
    ) -> SearchResult<Self> {
        let (schema, fields) = build_schema_with_positions(positions);
        let index = Index::create_in_ram(schema.clone());
        reject_positions_disagreement(&index, positions)?;
        Self::from_index_with_writer_threads(
            index,
            schema,
            fields,
            None,
            writer_heap_bytes,
            WriterPlan::BenchmarkShippingAuto,
            None,
        )
    }

    /// Create a new Tantivy index at the given directory path.
    ///
    /// If the directory does not exist, it will be created.
    /// If an index already exists at this path, it will be opened.
    ///
    /// # Errors
    ///
    /// Returns `SearchError::SubsystemError` if the Tantivy index cannot be
    /// created or opened.
    pub fn create(path: &Path) -> SearchResult<Self> {
        let (schema, fields) = build_schema();

        std::fs::create_dir_all(path).map_err(|e| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(e),
        })?;

        let index = Index::create_in_dir(path, schema.clone())
            .or_else(|_| {
                // If creation fails (already exists), try opening instead.
                Index::open_in_dir(path)
            })
            .map_err(|e| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(e),
            })?;

        Self::from_index(
            index,
            schema,
            fields,
            Some(path.to_path_buf()),
            WRITER_HEAP_BYTES,
        )
    }

    /// Open an existing Tantivy index at the given directory path.
    ///
    /// # Errors
    ///
    /// Returns `SearchError::IndexNotFound` if the path does not exist.
    /// Returns `SearchError::SubsystemError` if the index cannot be opened.
    pub fn open(path: &Path) -> SearchResult<Self> {
        if !path.exists() {
            return Err(SearchError::IndexNotFound {
                path: path.to_path_buf(),
            });
        }

        let (schema, fields) = build_schema();
        let index = Index::open_in_dir(path).map_err(|e| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(e),
        })?;

        Self::from_index(
            index,
            schema,
            fields,
            Some(path.to_path_buf()),
            WRITER_HEAP_BYTES,
        )
    }

    /// Create an in-memory Tantivy index (useful for testing).
    ///
    /// # Errors
    ///
    /// Returns `SearchError::SubsystemError` if the index cannot be created.
    pub fn in_memory() -> SearchResult<Self> {
        let (schema, fields) = build_schema();
        let index = Index::create_in_ram(schema.clone());
        Self::from_index(index, schema, fields, None, WRITER_HEAP_BYTES)
    }

    /// Create an in-memory oracle with one deterministic indexing worker.
    ///
    /// This is reserved for differential campaigns that compare Tantivy's
    /// native `DocAddress` tie order across repeated runs. Shipping callers
    /// should use [`Self::in_memory`], which retains Tantivy's default writer
    /// parallelism.
    ///
    /// # Errors
    ///
    /// Returns `SearchError::SubsystemError` if the index writer cannot be
    /// created.
    #[cfg(feature = "tantivy-oracle")]
    #[doc(hidden)]
    pub fn in_memory_single_threaded_oracle() -> SearchResult<Self> {
        let (schema, fields) = build_schema();
        let index = Index::create_in_ram(schema.clone());
        Self::from_index_with_writer_threads(
            index,
            schema,
            fields,
            None,
            WRITER_HEAP_BYTES,
            // An ordinary single-threaded oracle, not a benchmark candidate:
            // it really does pin width 1, and claims no screening receipt.
            WriterPlan::PinnedWidth(1),
            #[cfg(feature = "bench-internals")]
            None,
        )
    }

    /// Disable automatic merging for an exact oracle segment-topology proof.
    ///
    /// This method is intentionally separate from the benchmark-only helper:
    /// conformance fixtures use Tantivy's shipping indexing path but must keep
    /// explicit commit boundaries observable for native `DocAddress` ties.
    ///
    /// # Errors
    ///
    /// Returns a typed cancellation or writer-lock error.
    #[cfg(feature = "tantivy-oracle")]
    #[doc(hidden)]
    pub async fn oracle_disable_auto_merge(&self, cx: &Cx) -> SearchResult<()> {
        let writer = self
            .writer
            .lock(cx)
            .await
            .map_err(|error| Self::map_writer_lock_error("tantivy.oracle_no_merge", error))?;
        writer.set_merge_policy(Box::new(tantivy::merge_policy::NoMergePolicy));
        Ok(())
    }

    /// Return searchable oracle segments in native `segment_ord` order.
    ///
    /// # Errors
    ///
    /// Returns an invalid-config error if a segment ordinal cannot fit
    /// Tantivy's public address type.
    #[cfg(feature = "tantivy-oracle")]
    #[doc(hidden)]
    pub fn oracle_segment_layout(&self) -> SearchResult<Vec<OracleSegmentLayout>> {
        self.reader
            .searcher()
            .segment_readers()
            .iter()
            .enumerate()
            .map(|(segment_ord, segment)| {
                let segment_ord =
                    u32::try_from(segment_ord).map_err(|_| SearchError::InvalidConfig {
                        field: "tantivy.segment_ord".to_owned(),
                        value: segment_ord.to_string(),
                        reason: "segment ordinal must fit in u32".to_owned(),
                    })?;
                Ok(OracleSegmentLayout {
                    segment_ord,
                    max_doc: segment.max_doc(),
                    num_docs: segment.num_docs(),
                })
            })
            .collect()
    }

    /// Create an in-memory index with an explicit writer heap budget.
    ///
    /// This exists only for same-binary benchmark comparisons of Tantivy's
    /// writer parallelism. Shipping callers always use [`Self::in_memory`].
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn in_memory_with_writer_heap_bytes(writer_heap_bytes: usize) -> SearchResult<Self> {
        let (schema, fields) = build_schema();
        let index = Index::create_in_ram(schema.clone());
        Self::from_index(index, schema, fields, None, writer_heap_bytes)
    }

    /// Create an in-memory oracle with an explicitly pinned benchmark schema,
    /// writer count, and heap budget.
    ///
    /// This is the same shipping analyzer, document conversion, writer, and
    /// commit path used by [`LexicalSearch`]. Only the knobs that the Quill QG
    /// matrix must hold equal across engines are exposed. Shipping callers use
    /// [`Self::in_memory`] instead.
    ///
    /// # Errors
    ///
    /// Returns an invalid-config error for zero writer threads, or the ordinary
    /// Tantivy writer-construction error for an unsupported heap budget.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn in_memory_with_benchmark_config(
        writer_heap_bytes: usize,
        writer_threads: usize,
        positions: bool,
    ) -> SearchResult<Self> {
        validate_benchmark_writer_threads(writer_threads)?;
        let (schema, fields) = build_schema_with_positions(positions);
        let index = Index::create_in_ram(schema.clone());
        reject_positions_disagreement(&index, positions)?;
        Self::from_index_with_writer_threads(
            index,
            schema,
            fields,
            None,
            writer_heap_bytes,
            WriterPlan::BenchmarkFixed(writer_threads),
            None,
        )
    }

    /// Create an on-disk oracle with the same explicit benchmark pins as
    /// [`Self::in_memory_with_benchmark_config`].
    ///
    /// # Errors
    ///
    /// Returns a typed filesystem, invalid-config, or Tantivy construction
    /// error.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn create_with_benchmark_config(
        path: &Path,
        writer_heap_bytes: usize,
        writer_threads: usize,
        positions: bool,
    ) -> SearchResult<Self> {
        validate_benchmark_writer_threads(writer_threads)?;
        let (schema, fields) = build_schema_with_positions(positions);
        std::fs::create_dir_all(path).map_err(|error| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(error),
        })?;
        let benchmark_directory_sync_state = Arc::new(BenchmarkDirectorySyncState::new());
        let directory = ObservedMmapDirectory::open(path, benchmark_directory_sync_state.clone())
            .map_err(|error| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(error),
        })?;
        let index = Index::create(directory, schema.clone(), tantivy::IndexSettings::default())
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?;
        reject_positions_disagreement(&index, positions)?;
        Self::from_index_with_writer_threads(
            index,
            schema,
            fields,
            Some(path.to_path_buf()),
            writer_heap_bytes,
            WriterPlan::BenchmarkFixed(writer_threads),
            Some(benchmark_directory_sync_state),
        )
    }

    /// Reopen an on-disk oracle with the benchmark's pinned writer budget.
    ///
    /// # Errors
    ///
    /// Returns a typed missing-index, invalid-config, or Tantivy construction
    /// error.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn open_with_benchmark_config(
        path: &Path,
        writer_heap_bytes: usize,
        writer_threads: usize,
        positions: bool,
    ) -> SearchResult<Self> {
        validate_benchmark_writer_threads(writer_threads)?;
        if !path.exists() {
            return Err(SearchError::IndexNotFound {
                path: path.to_path_buf(),
            });
        }
        let (schema, fields) = build_schema_with_positions(positions);
        let benchmark_directory_sync_state = Arc::new(BenchmarkDirectorySyncState::new());
        let directory = ObservedMmapDirectory::open(path, benchmark_directory_sync_state.clone())
            .map_err(|error| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(error),
        })?;
        let index = Index::open(directory).map_err(|error| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(error),
        })?;
        reject_positions_disagreement(&index, positions)?;
        Self::from_index_with_writer_threads(
            index,
            schema,
            fields,
            Some(path.to_path_buf()),
            writer_heap_bytes,
            WriterPlan::BenchmarkFixed(writer_threads),
            Some(benchmark_directory_sync_state),
        )
    }

    /// Join every indexing and merge worker, then rearm the same benchmark index.
    ///
    /// The returned duration measures only Tantivy's
    /// [`IndexWriter::wait_merging_threads`] call. Constructing the replacement
    /// writer is excluded because it is harness bookkeeping, not incumbent
    /// maintenance. Searchable segment counts make the lifecycle boundary
    /// auditable without relying on timing variance.
    ///
    /// # Errors
    ///
    /// Returns an invalid writer-thread configuration, poisoned writer mutex,
    /// Tantivy worker/merge failure, segment metadata failure, or writer
    /// reconstruction failure.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn benchmark_join_workers_and_rearm(
        self,
        writer_heap_bytes: usize,
        writer_threads: usize,
    ) -> SearchResult<(Self, BenchmarkWriterJoinReceipt)> {
        validate_benchmark_writer_threads(writer_threads)?;
        let Self {
            index,
            fields,
            reader,
            writer,
            doc_count,
            ord_table,
            path,
            benchmark_writer_threads: _,
            benchmark_writer_receipt,
            benchmark_writer_attestation: _,
            benchmark_directory_sync_state,
            benchmark_qg4_no_merge_prepared: _,
            #[cfg(test)]
                observed_writer_call: _,
        } = self;
        let mut receipt = Self::benchmark_join_writer(&index, writer)?;
        // The rearm reconstructs through the same helper the fixed plan uses,
        // so its observation is the call it actually made rather than the one
        // the old writer had made.
        #[cfg(test)]
        let mut observed_writer_call = WriterCall::Auto;
        let writer = call_fixed_writer(
            &index,
            writer_threads,
            writer_heap_bytes,
            #[cfg(test)]
            &mut observed_writer_call,
        )
        .map_err(|error| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(error),
        })?;
        receipt.writer_rearmed = true;
        let benchmark_writer_receipt =
            benchmark_writer_receipt.map(|previous| BenchmarkWriterReceipt {
                mode: BenchmarkWriterMode::Fixed {
                    threads: writer_threads,
                },
                writer_heap_bytes,
                materialized_width: BenchmarkMaterializedWidth::Authenticated(writer_threads),
                writer_rearmed: true,
                ..previous
            });
        let benchmark_writer_attestation = benchmark_writer_receipt
            .as_ref()
            .map(|receipt| BenchmarkWriterAttestation::mint(receipt.clone()));
        Ok((
            Self {
                index,
                fields,
                reader,
                writer: Mutex::new(writer),
                doc_count,
                ord_table,
                path,
                benchmark_writer_threads: Some(writer_threads),
                benchmark_writer_receipt,
                benchmark_writer_attestation,
                benchmark_directory_sync_state,
                benchmark_qg4_no_merge_prepared: AtomicBool::new(false),
                #[cfg(test)]
                observed_writer_call,
            },
            receipt,
        ))
    }

    /// Join every indexing and merge worker while retaining a read-only search
    /// handle and without constructing another writer.
    ///
    /// The returned handle is the only terminal benchmark surface capable of
    /// proving that a query returned after the actual worker join.  Segment
    /// metadata is retained in the receipt for diagnostics but is not a
    /// searchability proof.
    ///
    /// # Errors
    ///
    /// Returns a poisoned writer-mutex, Tantivy worker/merge, or segment
    /// metadata error.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn benchmark_join_workers_retaining_reader(
        self,
    ) -> SearchResult<(BenchmarkRetainedTantivyReader, BenchmarkWriterJoinReceipt)> {
        let Self {
            index,
            fields,
            reader,
            writer,
            doc_count,
            ord_table,
            path,
            benchmark_writer_threads,
            benchmark_writer_receipt,
            benchmark_writer_attestation: _,
            benchmark_directory_sync_state: _,
            benchmark_qg4_no_merge_prepared: _,
            #[cfg(test)]
                observed_writer_call: _,
        } = self;
        let receipt = Self::benchmark_join_writer(&index, writer)?;
        drop((doc_count, ord_table, path, benchmark_writer_threads));
        drop(benchmark_writer_receipt);
        Ok((BenchmarkRetainedTantivyReader { fields, reader }, receipt))
    }

    /// Join every indexing and merge worker without constructing another writer.
    ///
    /// This is the terminal lifecycle fence for one-shot bulk measurements. It
    /// consumes the benchmark index, waits for every incumbent background
    /// worker, and returns only the counted receipt. Callers that will perform
    /// subsequent writes must use [`Self::benchmark_join_workers_and_rearm`].
    ///
    /// # Errors
    ///
    /// Returns a poisoned writer-mutex, Tantivy worker/merge, or segment
    /// metadata error.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn benchmark_join_workers(self) -> SearchResult<BenchmarkWriterJoinReceipt> {
        let (_reader, receipt) = self.benchmark_join_workers_retaining_reader()?;
        Ok(receipt)
    }

    #[cfg(feature = "bench-internals")]
    fn benchmark_join_writer(
        index: &Index,
        writer: Mutex<IndexWriter>,
    ) -> SearchResult<BenchmarkWriterJoinReceipt> {
        let searchable_segments_before = index
            .searchable_segment_ids()
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?
            .len();
        let writer = writer
            .into_inner()
            .map_err(|error| Self::map_writer_lock_error("tantivy.benchmark_join", error))?;
        let timer = std::time::Instant::now();
        writer
            .wait_merging_threads()
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?;
        let join_elapsed_ns = u64::try_from(timer.elapsed().as_nanos()).unwrap_or(u64::MAX);
        let searchable_segments_after = index
            .searchable_segment_ids()
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?
            .len();
        Ok(BenchmarkWriterJoinReceipt {
            searchable_segments_before,
            searchable_segments_after,
            join_elapsed_ns,
            writer_rearmed: false,
        })
    }

    /// Disable automatic segment merging for a force-merge benchmark setup.
    ///
    /// # Errors
    ///
    /// Returns a typed cancellation or writer-lock error.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub async fn benchmark_disable_auto_merge(&self, cx: &Cx) -> SearchResult<()> {
        let writer =
            self.writer.lock(cx).await.map_err(|error| {
                Self::map_writer_lock_error("tantivy.benchmark_no_merge", error)
            })?;
        writer.set_merge_policy(Box::new(tantivy::merge_policy::NoMergePolicy));
        Ok(())
    }

    /// Prepare a fresh benchmark index for a causally bound QG-4 directory-sync observation.
    ///
    /// This must run before any document is indexed. It installs Tantivy's real
    /// `NoMergePolicy`, so the one armed commit cannot be confused with an
    /// asynchronous merge-completion metadata save.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub async fn benchmark_prepare_qg4_no_merge_directory_sync(&self, cx: &Cx) -> SearchResult<()> {
        if self.benchmark_directory_sync_state.is_none() {
            return Err(SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync".to_owned(),
                value: "not_on_disk_benchmark_index".to_owned(),
                reason: "QG-4 directory-sync observation requires an on-disk benchmark index"
                    .to_owned(),
            });
        }
        let writer = self.writer.lock(cx).await.map_err(|error| {
            Self::map_writer_lock_error("tantivy.qg4.directory_sync_no_merge", error)
        })?;
        if self.doc_count.load(Ordering::Acquire) != 0 {
            return Err(SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync_no_merge".to_owned(),
                value: "documents_already_indexed".to_owned(),
                reason: "QG-4 no-merge setup must precede the warm fixture".to_owned(),
            });
        }
        writer.set_merge_policy(Box::new(tantivy::merge_policy::NoMergePolicy));
        self.benchmark_qg4_no_merge_prepared
            .store(true, Ordering::Release);
        debug!(
            has_shared_observer = true,
            "prepared QG-4 Tantivy no-merge fixture"
        );
        Ok(())
    }

    /// Arm a shared directory observer immediately before the timed QG-4 commit.
    ///
    /// Receipt construction is deliberately deferred to
    /// [`BenchmarkTantivyDirectorySyncArm::finish`], after the timed call
    /// returns its actual Tantivy opstamp.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn benchmark_arm_qg4_directory_sync(
        &self,
    ) -> SearchResult<BenchmarkTantivyDirectorySyncArm> {
        if !self.benchmark_qg4_no_merge_prepared.load(Ordering::Acquire) {
            return Err(SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync_no_merge".to_owned(),
                value: "not_prepared".to_owned(),
                reason:
                    "call benchmark_prepare_qg4_no_merge_directory_sync before warming the fixture"
                        .to_owned(),
            });
        }
        let state = self
            .benchmark_directory_sync_state
            .as_ref()
            .ok_or_else(|| SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync".to_owned(),
                value: "not_on_disk_benchmark_index".to_owned(),
                reason: "QG-4 directory-sync observation requires an on-disk benchmark index"
                    .to_owned(),
            })?
            .clone();
        let root = self
            .path
            .clone()
            .ok_or_else(|| SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync".to_owned(),
                value: "missing_index_root".to_owned(),
                reason: "the benchmark index has no on-disk root to bind into the receipt"
                    .to_owned(),
            })?;
        let nonce = state.arm()?;
        Ok(BenchmarkTantivyDirectorySyncArm {
            state,
            root,
            nonce,
            commit_opstamp: None,
            finished: false,
        })
    }

    /// Execute the same commit path as [`LexicalWrite::commit`] while an already-armed
    /// QG-4 observer watches Tantivy's real directory sync.
    ///
    /// The only observation work in the timed commit is the fixed atomic state
    /// transition performed by the wrapped successful `sync_directory` call.
    /// The returned opstamp is stamped into the supplied arm and finalized into
    /// a receipt after timing.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub async fn benchmark_commit_qg4_directory_sync(
        &self,
        cx: &Cx,
        arm: &mut BenchmarkTantivyDirectorySyncArm,
    ) -> SearchResult<()> {
        let state = self
            .benchmark_directory_sync_state
            .as_ref()
            .ok_or_else(|| SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync".to_owned(),
                value: "not_on_disk_benchmark_index".to_owned(),
                reason: "QG-4 directory-sync observation requires an on-disk benchmark index"
                    .to_owned(),
            })?;
        if !Arc::ptr_eq(state, &arm.state) {
            return Err(SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync".to_owned(),
                value: "foreign_arm".to_owned(),
                reason: "the supplied QG-4 directory-sync arm belongs to another index".to_owned(),
            });
        }

        let opstamp = {
            let mut writer = self
                .writer
                .lock(cx)
                .await
                .map_err(|error| Self::map_writer_lock_error("tantivy.qg4.commit", error))?;
            writer
                .commit()
                .map_err(|error| SearchError::SubsystemError {
                    subsystem: "tantivy",
                    source: Box::new(error),
                })?
        };

        self.reader
            .reload()
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?;
        let searcher = self.reader.searcher();
        let actual = usize::try_from(searcher.num_docs()).unwrap_or(usize::MAX);
        self.doc_count.store(actual, Ordering::Relaxed);
        self.persist_ord_table();
        arm.commit_opstamp = Some(opstamp);
        debug!(doc_count = actual, opstamp, "QG-4 Tantivy commit completed");
        Ok(())
    }

    /// Drive a second real wrapped sync in a focused ambiguity test.
    #[cfg(all(test, feature = "bench-internals"))]
    fn benchmark_test_second_armed_directory_sync(&self) -> SearchResult<()> {
        let state = self
            .benchmark_directory_sync_state
            .as_ref()
            .ok_or_else(|| SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync".to_owned(),
                value: "not_on_disk_benchmark_index".to_owned(),
                reason: "QG-4 directory-sync observation requires an on-disk benchmark index"
                    .to_owned(),
            })?
            .clone();
        let root = self
            .path
            .as_deref()
            .ok_or_else(|| SearchError::InvalidConfig {
                field: "tantivy.qg4.directory_sync".to_owned(),
                value: "missing_index_root".to_owned(),
                reason: "the benchmark index has no on-disk root to bind into the receipt"
                    .to_owned(),
            })?;
        ObservedMmapDirectory::open(root, state)
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?
            .sync_directory()
            .map_err(SearchError::from)
    }

    /// Force-merge every currently searchable segment and reload the reader.
    ///
    /// This exists only for QG-5's same-binary oracle arm. It invokes
    /// Tantivy's real merge machinery and waits for the merge future; no
    /// benchmark-only codec or document path is involved.
    ///
    /// # Errors
    ///
    /// Returns a typed cancellation, writer-lock, merge, or reader-reload
    /// error.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub async fn benchmark_force_merge(&self, cx: &Cx) -> SearchResult<()> {
        let segment_ids =
            self.index
                .searchable_segment_ids()
                .map_err(|error| SearchError::SubsystemError {
                    subsystem: "tantivy",
                    source: Box::new(error),
                })?;
        if segment_ids.len() < 2 {
            return Ok(());
        }
        {
            let mut writer = self
                .writer
                .lock(cx)
                .await
                .map_err(|error| Self::map_writer_lock_error("tantivy.force_merge", error))?;
            writer
                .merge(&segment_ids)
                .wait()
                .map_err(|error| SearchError::SubsystemError {
                    subsystem: "tantivy",
                    source: Box::new(error),
                })?;
        }
        self.reader
            .reload()
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?;
        Ok(())
    }

    /// Return `(searchable_segments, managed_index_bytes)` for index-build benchmarks.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn benchmark_index_layout(&self) -> SearchResult<(usize, u64)> {
        let usage =
            self.reader
                .searcher()
                .space_usage()
                .map_err(|e| SearchError::SubsystemError {
                    subsystem: "tantivy",
                    source: Box::new(e),
                })?;
        let segment_count = usage.segments().len();
        let index_bytes = usage.total().get_bytes();
        Ok((segment_count, index_bytes))
    }

    /// Internal constructor shared by `create`, `open`, and `in_memory`.
    fn from_index(
        index: Index,
        schema: Schema,
        fields: SchemaFields,
        path: Option<PathBuf>,
        writer_heap_bytes: usize,
    ) -> SearchResult<Self> {
        Self::from_index_with_writer_threads(
            index,
            schema,
            fields,
            path,
            writer_heap_bytes,
            WriterPlan::Shipping,
            #[cfg(feature = "bench-internals")]
            None,
        )
    }

    fn from_index_with_writer_threads(
        index: Index,
        _schema: Schema,
        mut fields: SchemaFields,
        path: Option<PathBuf>,
        writer_heap_bytes: usize,
        plan: WriterPlan,
        #[cfg(feature = "bench-internals")] benchmark_directory_sync_state: Option<
            Arc<BenchmarkDirectorySyncState>,
        >,
    ) -> SearchResult<Self> {
        // Resolve the `ord` fast field against the *actual* index schema so
        // indexes created before this field existed (no `ord`) cleanly fall back
        // to docstore materialization instead of using a phantom field handle.
        fields.ord = index.schema().get_field("ord").ok();

        // Register our custom tokenizer.
        let tokenizer_manager = index.tokenizers().clone();
        tokenizer_manager.register(TOKENIZER_NAME, build_tokenizer());

        let reader = index
            .reader_builder()
            .reload_policy(ReloadPolicy::OnCommitWithDelay)
            .try_into()
            .map_err(|e| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(e),
            })?;

        // The selection branch is the single source of both the writer and its
        // receipt seed. Nothing downstream can relabel a `writer_with_num_threads`
        // construction as shipping-auto, or vice versa, because the mode is
        // produced here by the arm that actually ran.
        #[cfg(feature = "bench-internals")]
        let mut benchmark_writer_receipt = None;
        #[cfg(feature = "bench-internals")]
        let mut benchmark_writer_attestation = None;
        // Default is overwritten by whichever helper actually runs below; the
        // helper is the only writer of this value.
        #[cfg(test)]
        let mut observed_writer_call = WriterCall::Auto;
        let writer = match plan {
            // Ordinary shipping construction reaches the same Tantivy call as a
            // benchmark shipping-auto construction, and deliberately produces no
            // receipt: only an explicit benchmark plan may claim one.
            WriterPlan::Shipping => call_auto_writer(
                &index,
                writer_heap_bytes,
                #[cfg(test)]
                &mut observed_writer_call,
            ),
            // Pinned but unscreened: the same Tantivy call a benchmark fixed
            // plan makes, deliberately without a receipt.
            #[cfg(feature = "tantivy-oracle")]
            WriterPlan::PinnedWidth(thread_count) => call_fixed_writer(
                &index,
                thread_count,
                writer_heap_bytes,
                #[cfg(test)]
                &mut observed_writer_call,
            ),
            #[cfg(feature = "bench-internals")]
            WriterPlan::BenchmarkShippingAuto => {
                let writer = call_auto_writer(
                    &index,
                    writer_heap_bytes,
                    #[cfg(test)]
                    &mut observed_writer_call,
                );
                if writer.is_ok() {
                    let receipt = BenchmarkWriterReceipt::seed(
                        BenchmarkWriterMode::ShippingAuto,
                        writer_heap_bytes,
                        &index,
                    )?;
                    benchmark_writer_attestation =
                        Some(BenchmarkWriterAttestation::mint(receipt.clone()));
                    benchmark_writer_receipt = Some(receipt);
                }
                writer
            }
            #[cfg(feature = "bench-internals")]
            WriterPlan::BenchmarkFixed(thread_count) => {
                let writer = call_fixed_writer(
                    &index,
                    thread_count,
                    writer_heap_bytes,
                    #[cfg(test)]
                    &mut observed_writer_call,
                );
                if writer.is_ok() {
                    let receipt = BenchmarkWriterReceipt::seed(
                        BenchmarkWriterMode::Fixed {
                            threads: thread_count,
                        },
                        writer_heap_bytes,
                        &index,
                    )?;
                    benchmark_writer_attestation =
                        Some(BenchmarkWriterAttestation::mint(receipt.clone()));
                    benchmark_writer_receipt = Some(receipt);
                }
                writer
            }
        }
        .map_err(|e| SearchError::SubsystemError {
            subsystem: "tantivy",
            source: Box::new(e),
        })?;

        // Count existing documents.
        let searcher = reader.searcher();
        let doc_count = usize::try_from(searcher.num_docs()).unwrap_or(usize::MAX);

        // Restore the ordinal→doc_id table for a reopened on-disk index from its
        // sidecar so id materialization keeps the fast path instead of falling
        // back to the docstore. The sidecar is best-effort: if it is absent,
        // corrupt, or stale the table is left short and those ordinals resolve
        // via the docstore (correct, just unaccelerated).
        let mut ord_table = match (path.as_deref(), fields.ord) {
            (Some(dir), Some(_)) => Self::load_ord_table_sidecar(dir).unwrap_or_default(),
            _ => Vec::new(),
        };
        if fields.ord.is_some() {
            // Guard against a stale-short sidecar (e.g. a persist that failed on
            // the last commit): `Column::max_value` is O(1) columnar metadata, so
            // padding the table to cover the highest existing ordinal keeps the
            // next assigned ordinal (`ord_table.len()`) collision-free, and the
            // padded empty slots fall back to the docstore on read.
            let mut max_ord = 0u64;
            let mut saw_ord = false;
            for sr in searcher.segment_readers() {
                if let Ok(col) = sr.fast_fields().u64("ord")
                    && col.num_docs() > 0
                {
                    max_ord = max_ord.max(col.max_value());
                    saw_ord = true;
                }
            }
            if saw_ord {
                let needed = usize::try_from(max_ord)
                    .unwrap_or(usize::MAX)
                    .saturating_add(1);
                if ord_table.len() < needed {
                    ord_table.resize(needed, DocId::default());
                }
            }
        }

        Ok(Self {
            index,
            fields,
            reader,
            writer: Mutex::new(writer),
            doc_count: AtomicUsize::new(doc_count),
            ord_table: RwLock::new(ord_table),
            path,
            #[cfg(feature = "bench-internals")]
            benchmark_writer_threads: plan.benchmark_threads(),
            // Seeded above by the selection branch itself, so the record and
            // the call it describes cannot disagree.
            //
            // This constructor is shared with the default build, so the field
            // needs the same gate as its neighbour above — without it the
            // no-feature build names a field that does not exist.
            #[cfg(feature = "bench-internals")]
            benchmark_writer_receipt,
            #[cfg(feature = "bench-internals")]
            benchmark_writer_attestation,
            #[cfg(feature = "bench-internals")]
            benchmark_directory_sync_state,
            #[cfg(feature = "bench-internals")]
            benchmark_qg4_no_merge_prepared: AtomicBool::new(false),
            #[cfg(test)]
            observed_writer_call,
        })
    }

    /// Load the persisted `ordinal → doc_id` table sidecar (`ord_table.json`)
    /// from an on-disk index directory. Returns `None` on any error or absence
    /// so the caller can fall back to docstore materialization.
    fn load_ord_table_sidecar(dir: &Path) -> Option<Vec<DocId>> {
        let file = std::fs::File::open(dir.join("ord_table.json")).ok()?;
        serde_json::from_reader(std::io::BufReader::new(file)).ok()
    }

    /// Persist the `ordinal → doc_id` table to the index directory sidecar so a
    /// later `open` can restore the fast id-materialization path. Best-effort:
    /// errors are logged and swallowed (the in-memory fast path is unaffected;
    /// only a future reopen would fall back to the docstore). Written atomically
    /// via a temp file + rename. No-op for in-memory indexes / pre-`ord` schemas.
    fn persist_ord_table(&self) {
        let Some(dir) = self.path.as_ref() else {
            return;
        };
        if self.fields.ord.is_none() {
            return;
        }
        let Ok(table) = self.ord_table.read() else {
            return;
        };
        let tmp = dir.join("ord_table.json.tmp");
        let final_path = dir.join("ord_table.json");
        let write = std::fs::File::create(&tmp).and_then(|file| {
            let mut writer = std::io::BufWriter::new(file);
            serde_json::to_writer(&mut writer, &*table).map_err(std::io::Error::other)?;
            std::io::Write::flush(&mut writer)
        });
        match write {
            Ok(()) => {
                if let Err(e) = std::fs::rename(&tmp, &final_path) {
                    debug!(error = %e, "ord_table sidecar rename failed; reopen will use docstore");
                }
            }
            Err(e) => {
                debug!(error = %e, "ord_table sidecar write failed; reopen will use docstore");
                let _ = std::fs::remove_file(&tmp);
            }
        }
    }

    /// Convert an `IndexableDocument` to a Tantivy document.
    fn to_tantivy_doc(&self, doc: &IndexableDocument) -> TantivyDocument {
        let mut tantivy_doc = TantivyDocument::new();
        tantivy_doc.add_text(self.fields.id, &doc.id);
        tantivy_doc.add_text(self.fields.content, &doc.content);
        tantivy_doc.add_text(self.fields.title, doc.title.as_deref().unwrap_or(""));

        // Serialize metadata as JSON string.
        if !doc.metadata.is_empty()
            && let Ok(json) = serde_json::to_string(&doc.metadata)
        {
            tantivy_doc.add_text(self.fields.metadata_json, &json);
        }

        tantivy_doc
    }

    /// Assign the next dense ordinal to `tantivy_doc` and append `doc_id` to the
    /// `ord_table` so id materialization can skip the docstore decompress.
    ///
    /// Must be called while holding the writer lock: that serializes ordinal
    /// assignment with `add_document`, so ordinal `i` always corresponds to
    /// `ord_table[i]`. No-op when the schema has no `ord` field (pre-`ord`
    /// indexes) or when the table lock is poisoned (the doc is left without an
    /// ordinal and that hit falls back to docstore materialization).
    fn assign_ord(&self, tantivy_doc: &mut TantivyDocument, doc_id: &str) {
        if let Some(ord_field) = self.fields.ord
            && let Ok(mut table) = self.ord_table.write()
        {
            let ord = u64::try_from(table.len()).unwrap_or(u64::MAX);
            table.push(DocId::from(doc_id));
            tantivy_doc.add_u64(ord_field, ord);
        }
    }

    /// Build a `QueryParser` for BM25 search with title boost.
    fn query_parser(&self) -> QueryParser {
        let mut parser =
            QueryParser::for_index(&self.index, vec![self.fields.content, self.fields.title]);
        parser.set_field_boost(self.fields.title, TITLE_BOOST);
        parser
    }

    /// Parse for the SHIPPING search path: lenient, plus the bd-f20ye repair.
    ///
    /// THE TWO ROLES OF THIS CRATE DIVERGE HERE, AND ONLY HERE.
    /// `frankensearch-lexical` is both the shipping Tantivy backend and the
    /// Quill gauntlet's pinned conformance oracle. Every `oracle_observe_*`
    /// method keeps calling [`Self::parse_query_lenient`] and stays bit-faithful
    /// to Tantivy 0.26.1, because the oracle is a pinned COMPARATOR and moving
    /// it would silently move the target Quill is measured against. Every
    /// user-facing `search*` method calls THIS instead, because a boost that
    /// changes boolean MEMBERSHIP is a defect by any reading and shipping it to
    /// users is not defensible.
    ///
    /// The resulting divergence between the two roles is registered as
    /// **DIV-009** in `docs/contracts/quill-divergence-register.md`, disposition
    /// accepted-with-rationale. Do not "unify" these two paths without
    /// superseding that entry: the shipping path is deliberately NOT
    /// bit-faithful to the oracle for this one query shape.
    fn parse_query_shipping(&self, query: &str) -> Box<dyn tantivy::query::Query> {
        // ORDER IS LOAD-BEARING. bd-8a2a8 runs first because it decodes whole
        // `AND` chains, and it needs to see the `AND` that bd-eeq0q deletes:
        // after that deletion `a AND NOT b AND c` reads as the unrelated chain
        // `NOT b AND c` and would be normalised to the wrong grouping. Both
        // repairs leave a `-` or `NOT` inside the group they touch, so the
        // bd-f20ye repair still recognises `(a AND NOT b)^2` as negating — it
        // records negation against the innermost open group, which is why
        // bd-8a2a8 emits a whole-level chain without adding parentheses.
        let conjunction = repair_negated_conjunction(query);
        let repaired = repair_and_not(&conjunction);
        self.parse_query_lenient(&repair_boosted_group_negation(&repaired))
    }

    /// Parse a query using lenient mode (never fails, returns best-effort query).
    ///
    /// Unknown field prefixes, unbalanced quotes, and other syntax issues are
    /// silently ignored rather than producing errors. This makes user-facing
    /// search robust against arbitrary input.
    ///
    /// BIT-FAITHFUL TO THE PINNED ORACLE. Callers in the `oracle_observe_*`
    /// family depend on this reproducing Tantivy 0.26.1 exactly, defects
    /// included — see [`Self::parse_query_shipping`] and DIV-009.
    fn parse_query_lenient(&self, query: &str) -> Box<dyn tantivy::query::Query> {
        let parser = self.query_parser();
        let (parsed, errors) = parser.parse_query_lenient(query);
        if let Some(first_error) = errors.first() {
            debug!(
                error_count = errors.len(),
                first_error = %first_error,
                "lenient query parse produced warnings"
            );
        }
        parsed
    }

    /// Delete a document by its ID.
    ///
    /// A successful return commits the deletion and refreshes the readable
    /// generation before releasing the writer lock.
    ///
    /// # Errors
    ///
    /// Returns `SearchError::SubsystemError` if the writer lock is poisoned
    /// or cancelled.
    pub async fn delete_document(&self, cx: &Cx, doc_id: &str) -> SearchResult<()> {
        let term = Term::from_field_text(self.fields.id, doc_id);
        let mut writer = self
            .writer
            .lock(cx)
            .await
            .map_err(|error| Self::map_writer_lock_error("tantivy.delete", error))?;
        writer.delete_term(term);
        writer
            .commit()
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?;

        self.reader
            .reload()
            .map_err(|error| SearchError::SubsystemError {
                subsystem: "tantivy",
                source: Box::new(error),
            })?;

        let actual = Self::checked_searcher_doc_count(&self.reader.searcher())?;
        self.doc_count.store(actual, Ordering::Relaxed);

        debug!(doc_count = actual, %doc_id, "tantivy delete committed and reloaded");
        Ok(())
    }

    /// Returns the directory path for this index, if on-disk.
    #[must_use]
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Cloneable handle to the underlying Tantivy index.
    ///
    /// This is primarily used by durability wrappers that protect/verify
    /// segment artifacts outside the lexical crate.
    #[must_use]
    pub fn index_handle(&self) -> Index {
        self.index.clone()
    }

    /// Truncate an overlong query and log a warning.
    fn truncate_query(query: &str) -> &str {
        // UTF-8 uses at least one byte per character, so this is a cheap
        // common-case proof that the query is within the character limit.
        if query.len() <= MAX_QUERY_LENGTH {
            return query;
        }

        // `char_indices().nth(MAX_QUERY_LENGTH)` points at the first character
        // outside the allowed prefix. If it is absent, the string exceeds the
        // byte count but still contains at most MAX_QUERY_LENGTH characters.
        let Some((end, _)) = query.char_indices().nth(MAX_QUERY_LENGTH) else {
            return query;
        };
        warn!(
            original_len_bytes = query.len(),
            max_chars = MAX_QUERY_LENGTH,
            "query truncated to MAX_QUERY_LENGTH"
        );
        &query[..end]
    }

    /// Search with snippet generation and query explanation.
    ///
    /// Returns [`LexicalHit`] results enriched with highlighted snippets
    /// from the content field and a [`QueryExplanation`] indicating how
    /// the query was parsed.
    ///
    /// # Errors
    ///
    /// Returns `SearchError` if the query cannot be parsed or search fails.
    #[instrument(skip_all, fields(query = %query, limit = limit))]
    pub fn search_with_snippets(
        &self,
        _cx: &Cx,
        query: &str,
        limit: usize,
        snippet_config: &SnippetConfig,
    ) -> SearchResult<Vec<LexicalHit>> {
        let query = Self::truncate_query(query);
        let explanation = classify_query(query);

        if explanation == QueryExplanation::Empty {
            return Ok(Vec::new());
        }

        let parsed = self.parse_query_shipping(query);

        let searcher = self.reader.searcher();
        let search_result = execute_query_with_offset(&searcher, &*parsed, limit, 0)?;
        let snippet_gen =
            try_build_snippet_generator(&searcher, &*parsed, self.fields.content, snippet_config);

        debug!(
            hits = search_result.hits.len(),
            total_count = search_result.total_count,
            query_type = %explanation,
            "tantivy search_with_snippets completed"
        );

        let mut results = Vec::with_capacity(search_result.hits.len());
        for hit in search_result.hits {
            let doc = load_doc(&searcher, hit.doc_address)?;

            let doc_id = doc
                .get_first(self.fields.id)
                .and_then(|v| v.as_str())
                .unwrap_or_else(|| {
                    debug!("tantivy document missing id field, using empty doc_id");
                    ""
                })
                .to_owned();

            let metadata = doc
                .get_first(self.fields.metadata_json)
                .and_then(|v| v.as_str())
                .and_then(|s| match serde_json::from_str(s) {
                    Ok(val) => Some(val),
                    Err(e) => {
                        debug!(doc_id = %doc_id, error = %e, "failed to deserialize metadata JSON");
                        None
                    }
                });

            // Generate snippet from the document.
            let snippet = snippet_gen.as_ref().and_then(|generator| {
                render_snippet_html(
                    generator,
                    &doc,
                    &snippet_config.highlight_prefix,
                    &snippet_config.highlight_postfix,
                )
            });

            results.push(LexicalHit {
                doc_id,
                bm25_score: hit.bm25_score,
                rank: hit.rank,
                snippet,
                query_type: explanation,
                metadata,
            });
        }

        Ok(results)
    }

    /// Observe the shipping parser/search/snippet path for Quill conformance.
    ///
    /// This surface is deliberately feature-gated: it retains the full Tantivy
    /// `DocAddress`, exact count, score bits, and an expanded cutoff tie group.
    /// Shipping consumers should use the ordinary lexical APIs instead.
    ///
    /// # Errors
    ///
    /// Returns `SearchError` if query execution or stored-field loading fails.
    #[cfg(feature = "tantivy-oracle")]
    #[instrument(skip_all, fields(query = %query, limit = limit, tie_expansion_limit = tie_expansion_limit))]
    pub fn oracle_observe_query(
        &self,
        _cx: &Cx,
        query: &str,
        limit: usize,
        tie_expansion_limit: usize,
        snippet_config: &SnippetConfig,
    ) -> SearchResult<OracleQueryObservation> {
        let query = Self::truncate_query(query);
        let searcher = self.reader.searcher();
        let doc_count = Self::checked_searcher_doc_count(&searcher)?;
        if query.trim().is_empty() {
            return Ok(OracleQueryObservation {
                hits: Vec::new(),
                cutoff_tie_group: Vec::new(),
                cutoff_tie_complete: true,
                total_count: 0,
                doc_count,
            });
        }

        let parsed = self.parse_query_lenient(query);
        let fetch_limit = if limit == 0 {
            0
        } else {
            limit.saturating_add(tie_expansion_limit)
        };
        // Preserve the exact shipping TopDocs-only path for both `hits` and
        // the expanded tie evidence. Tantivy may choose a different score
        // accumulation or cutoff strategy when `TopDocs` is paired with
        // `Count`, and a larger collector limit may select a different member
        // of an exact-score cutoff tie. Count therefore runs independently,
        // and the expanded query may describe the tie envelope but must never
        // redefine the incumbent result whose latency and rank we compare.
        let native_hits = execute_top_k(&searcher, &*parsed, limit, 0)?;
        let expanded_hits = execute_top_k(&searcher, &*parsed, fetch_limit, 0)?;
        let total_count = execute_query_with_offset(&searcher, &*parsed, 0, 0)?.total_count;
        let snippet_gen =
            try_build_snippet_generator(&searcher, &*parsed, self.fields.content, snippet_config);
        let materialize = |hit: LexicalDocHit| -> SearchResult<OracleRankedHit> {
            let doc = load_doc(&searcher, hit.doc_address)?;
            let doc_id = doc
                .get_first(self.fields.id)
                .and_then(|value| value.as_str())
                .unwrap_or_default()
                .to_owned();
            let snippet = snippet_gen.as_ref().and_then(|generator| {
                render_snippet_html(
                    generator,
                    &doc,
                    &snippet_config.highlight_prefix,
                    &snippet_config.highlight_postfix,
                )
            });
            Ok(OracleRankedHit {
                doc_id,
                score_bits: hit.bm25_score.to_bits(),
                rank: hit.rank,
                segment_ord: hit.doc_address.segment_ord,
                segment_doc_id: hit.doc_address.doc_id,
                snippet,
            })
        };
        let hits = native_hits
            .into_iter()
            .map(&materialize)
            .collect::<SearchResult<Vec<_>>>()?;
        let expanded_hits = expanded_hits
            .into_iter()
            .map(materialize)
            .collect::<SearchResult<Vec<_>>>()?;

        let cutoff_bits = hits.last().map(|hit| hit.score_bits);
        let cutoff_tie_group = cutoff_bits.map_or_else(Vec::new, |cutoff| {
            expanded_hits
                .iter()
                .filter(|hit| {
                    f32::from_bits(hit.score_bits)
                        .total_cmp(&f32::from_bits(cutoff))
                        .is_eq()
                })
                .cloned()
                .collect()
        });
        let cutoff_tie_complete = cutoff_bits.is_none_or(|cutoff| {
            total_count <= fetch_limit
                || expanded_hits.last().is_none_or(|last| {
                    !f32::from_bits(last.score_bits)
                        .total_cmp(&f32::from_bits(cutoff))
                        .is_eq()
                })
        });

        Ok(OracleQueryObservation {
            hits,
            cutoff_tie_group,
            cutoff_tie_complete,
            total_count,
            doc_count,
        })
    }

    /// Observe Tantivy's real exact-count offset-pagination path.
    ///
    /// This method exists only for the replacement conformance harness. It
    /// intentionally uses the same private lenient parser, reader snapshot,
    /// stored-ID materialization, and [`execute_query_with_offset`] collector
    /// as the incumbent engine. The exact count is returned by Tantivy's
    /// [`Count`] collector and is never inferred from the page length.
    ///
    /// # Errors
    ///
    /// Returns a typed search failure when query execution, rank arithmetic,
    /// or stored-document materialization fails.
    #[cfg(feature = "tantivy-oracle")]
    #[instrument(skip_all, fields(query = %query, limit = limit, offset = offset))]
    pub fn oracle_observe_page(
        &self,
        _cx: &Cx,
        query: &str,
        limit: usize,
        offset: usize,
    ) -> SearchResult<OraclePageObservation> {
        let query = Self::truncate_query(query);
        let searcher = self.reader.searcher();
        let doc_count = Self::checked_searcher_doc_count(&searcher)?;
        if query.trim().is_empty() {
            return Ok(OraclePageObservation {
                hits: Vec::new(),
                total_count: 0,
                doc_count,
            });
        }

        let parsed = self.parse_query_lenient(query);
        let search_result = execute_query_with_offset(&searcher, &*parsed, limit, offset)?;
        let mut hits = Vec::with_capacity(search_result.hits.len());
        for hit in search_result.hits {
            let doc = load_doc(&searcher, hit.doc_address)?;
            let doc_id = doc
                .get_first(self.fields.id)
                .and_then(|value| value.as_str())
                .unwrap_or_default()
                .to_owned();
            let absolute_rank =
                offset
                    .checked_add(hit.rank)
                    .ok_or_else(|| SearchError::InvalidConfig {
                        field: "tantivy.oracle_page_rank".to_owned(),
                        value: format!("{offset}+{}", hit.rank),
                        reason: "absolute result rank must fit usize".to_owned(),
                    })?;
            hits.push(OraclePageHit {
                doc_id,
                score_bits: hit.bm25_score.to_bits(),
                page_rank: hit.rank,
                absolute_rank,
            });
        }

        Ok(OraclePageObservation {
            hits,
            total_count: search_result.total_count,
            doc_count,
        })
    }

    /// Search and return only `(doc_id, score, rank)` rows.
    ///
    /// This avoids metadata JSON decoding and is intended for latency-critical
    /// callers that only require identifiers plus BM25 scores.
    ///
    /// # Errors
    ///
    /// Returns `SearchError` if the query cannot be parsed or search fails.
    #[instrument(skip_all, fields(query = %query, limit = limit))]
    pub fn search_doc_ids(
        &self,
        _cx: &Cx,
        query: &str,
        limit: usize,
    ) -> SearchResult<Vec<LexicalIdHit>> {
        let query = Self::truncate_query(query);
        if query.trim().is_empty() {
            return Ok(Vec::new());
        }

        let parsed = self.parse_query_shipping(query);
        let searcher = self.reader.searcher();
        let hits = execute_top_k(&searcher, &*parsed, limit, 0)?;
        self.collect_id_hits(&searcher, hits)
    }

    /// Enumerate every live document identifier in the committed index.
    ///
    /// This is intended for generation reconciliation and repair paths that
    /// cannot trust an external manifest. Results are sorted and deduplicated
    /// so callers can stage deterministic deletes even when an older index
    /// contains duplicate IDs.
    ///
    /// # Errors
    ///
    /// Returns `SearchError` if a live stored document cannot be loaded or the
    /// segment ordinal cannot be represented by Tantivy's address type.
    pub fn all_doc_ids(&self) -> SearchResult<Vec<DocId>> {
        let searcher = self.reader.searcher();
        let mut ids = Vec::with_capacity(self.doc_count.load(Ordering::Relaxed));
        for (segment_ord, segment) in searcher.segment_readers().iter().enumerate() {
            let segment_ord =
                u32::try_from(segment_ord).map_err(|_| SearchError::InvalidConfig {
                    field: "tantivy.segment_ord".to_owned(),
                    value: segment_ord.to_string(),
                    reason: "segment ordinal must fit in u32".to_owned(),
                })?;
            for doc_id in 0..segment.max_doc() {
                if segment.is_deleted(doc_id) {
                    continue;
                }
                let doc = load_doc(&searcher, DocAddress::new(segment_ord, doc_id))?;
                if let Some(doc_id) = doc
                    .get_first(self.fields.id)
                    .and_then(|value| value.as_str())
                {
                    ids.push(DocId::from(doc_id));
                }
            }
        }
        ids.sort_unstable();
        ids.dedup();
        Ok(ids)
    }

    /// Export every live committed document for exact-generation shadow replay.
    ///
    /// Results are ordered by document id. Duplicate ids from legacy indexes
    /// collapse deterministically to the last live segment/document address.
    ///
    /// # Errors
    ///
    /// Returns `SearchError` if a stored live document cannot be loaded or its
    /// metadata payload is malformed.
    pub fn all_documents(&self) -> SearchResult<Vec<IndexableDocument>> {
        let searcher = self.reader.searcher();
        let mut documents = std::collections::BTreeMap::new();
        for (segment_ord, segment) in searcher.segment_readers().iter().enumerate() {
            let segment_ord =
                u32::try_from(segment_ord).map_err(|_| SearchError::InvalidConfig {
                    field: "tantivy.segment_ord".to_owned(),
                    value: segment_ord.to_string(),
                    reason: "segment ordinal must fit in u32".to_owned(),
                })?;
            for doc_id in 0..segment.max_doc() {
                if segment.is_deleted(doc_id) {
                    continue;
                }
                let doc = load_doc(&searcher, DocAddress::new(segment_ord, doc_id))?;
                let Some(id) = doc
                    .get_first(self.fields.id)
                    .and_then(|value| value.as_str())
                else {
                    continue;
                };
                let content = doc
                    .get_first(self.fields.content)
                    .and_then(|value| value.as_str())
                    .unwrap_or_default()
                    .to_owned();
                let title = doc
                    .get_first(self.fields.title)
                    .and_then(|value| value.as_str())
                    .filter(|value| !value.is_empty())
                    .map(str::to_owned);
                let metadata = doc
                    .get_first(self.fields.metadata_json)
                    .and_then(|value| value.as_str())
                    .map_or_else(
                        || Ok(std::collections::HashMap::new()),
                        |json| {
                            serde_json::from_str(json).map_err(|error| {
                                SearchError::SubsystemError {
                                    subsystem: "tantivy.shadow_export",
                                    source: Box::new(error),
                                }
                            })
                        },
                    )?;
                documents.insert(
                    id.to_owned(),
                    IndexableDocument {
                        id: id.to_owned(),
                        content,
                        title,
                        metadata,
                    },
                );
            }
        }
        Ok(documents.into_values().collect())
    }

    /// Pre-optimization baseline for [`Self::search_doc_ids`] that retains the
    /// discarded total-count collector. This is used only by the `doc_ids_topk`
    /// benchmark so the optimized and counted paths can be compared in one
    /// binary.
    #[doc(hidden)]
    #[instrument(skip_all, fields(query = %query, limit = limit))]
    pub fn search_doc_ids_counted(
        &self,
        _cx: &Cx,
        query: &str,
        limit: usize,
    ) -> SearchResult<Vec<LexicalIdHit>> {
        let query = Self::truncate_query(query);
        if query.trim().is_empty() {
            return Ok(Vec::new());
        }

        let parsed = self.parse_query_shipping(query);
        let searcher = self.reader.searcher();
        let search_result = execute_query_with_offset(&searcher, &*parsed, limit, 0)?;
        self.collect_id_hits(&searcher, search_result.hits)
    }

    /// Pre-optimization baseline for [`Self::search_doc_ids`] that forces the
    /// docstore id-materialization path (ignoring the `ord` fast field + table).
    /// Used only by the `search_doc_ids_materialize` benchmark to A/B the fast
    /// materialization wiring in one binary; not for production use.
    #[doc(hidden)]
    #[instrument(skip_all, fields(query = %query, limit = limit))]
    pub fn search_doc_ids_via_docstore(
        &self,
        _cx: &Cx,
        query: &str,
        limit: usize,
    ) -> SearchResult<Vec<LexicalIdHit>> {
        let query = Self::truncate_query(query);
        if query.trim().is_empty() {
            return Ok(Vec::new());
        }

        let parsed = self.parse_query_shipping(query);
        let searcher = self.reader.searcher();
        let hits = execute_top_k(&searcher, &*parsed, limit, 0)?;
        let mut results = Vec::with_capacity(hits.len());
        for hit in hits {
            results.push(LexicalIdHit {
                doc_id: self.docstore_id(&searcher, hit.doc_address)?,
                bm25_score: hit.bm25_score,
                rank: hit.rank,
            });
        }
        Ok(results)
    }

    /// Read a single hit's `doc_id` from the stored document (the docstore
    /// fallback path: decompresses the stored block to read the `id` field).
    fn docstore_id(&self, searcher: &Searcher, addr: DocAddress) -> SearchResult<DocId> {
        let doc = load_doc(searcher, addr)?;
        Ok(DocId::from(
            doc.get_first(self.fields.id)
                .and_then(|v| v.as_str())
                .unwrap_or_else(|| {
                    debug!("tantivy document missing id field, using empty doc_id");
                    ""
                }),
        ))
    }

    /// Materialize ranked Tantivy hits into [`LexicalIdHit`] rows.
    ///
    /// Fast path: read each hit's dense ordinal from the `ord` `u64` FAST column
    /// (a flat bit-packed read — no stored-document decompress, no dictionary
    /// seek) and resolve it through the in-memory `ord_table`. Falls back
    /// per-hit to [`Self::docstore_id`] for any ordinal the table cannot resolve
    /// (documents written before `ord` existed, a reopened-but-not-rebuilt
    /// table, or a poisoned lock), so results are identical either way.
    // The `ord_table` read guard is intentionally held across the whole hit
    // loop — it is the once-per-call snapshot every hit resolves against.
    #[allow(clippy::significant_drop_tightening)]
    fn collect_id_hits(
        &self,
        searcher: &Searcher,
        hits: Vec<LexicalDocHit>,
    ) -> SearchResult<Vec<LexicalIdHit>> {
        let mut results = Vec::with_capacity(hits.len());

        // Take the table snapshot once; `None` when the field is absent or the
        // table is empty → pure docstore path. `ord` columns are opened lazily
        // per *touched* segment (top-k hits cluster in a few segments, so we
        // avoid paying for segments no hit lands in).
        let table = self.fields.ord.and_then(|_| {
            let table = self.ord_table.read().ok()?;
            if table.is_empty() { None } else { Some(table) }
        });
        // Cache the opened `ord` column per segment in a flat Vec indexed by
        // `segment_ord` — O(1), no per-hit hash — while still opening each
        // column lazily on first touch (outer `None` = not yet opened) so
        // segments no hit lands in are never opened. `segment_ord` is a dense
        // in-range index for hits from this `searcher`. Only sized on the
        // fast-field path (`table` present); the docstore path never indexes it.
        let mut columns: Vec<Option<Option<tantivy::columnar::Column<u64>>>> = Vec::new();
        if table.is_some() {
            columns.resize_with(searcher.segment_readers().len(), || None);
        }

        for hit in hits {
            let addr = hit.doc_address;
            let doc_id = match table.as_ref().and_then(|table| {
                columns[addr.segment_ord as usize]
                    .get_or_insert_with(|| {
                        searcher
                            .segment_reader(addr.segment_ord)
                            .fast_fields()
                            .u64("ord")
                            .ok()
                    })
                    .as_ref()
                    .and_then(|c| c.first(addr.doc_id))
                    .and_then(|ord| usize::try_from(ord).ok())
                    .and_then(|ord| table.get(ord))
                    // Empty = a padded/stale slot (sidecar didn't cover this
                    // ordinal) → fall back to the docstore for the real id.
                    .filter(|id| !id.is_empty())
                    .cloned()
            }) {
                Some(id) => id,
                None => self.docstore_id(searcher, addr)?,
            };

            results.push(LexicalIdHit {
                doc_id,
                bm25_score: hit.bm25_score,
                rank: hit.rank,
            });
        }

        Ok(results)
    }

    /// Hydrate winners from an explicitly supplied searcher.
    ///
    /// A Tantivy `Searcher` holds a fixed segment set, so passing the *same*
    /// searcher that produced the scores is what makes hydration read the
    /// scoring generation rather than the newest one (`bd-8nqz.1`).
    fn hydrate_with_searcher(
        &self,
        searcher: &Searcher,
        results: &mut [ScoredResult],
        unscored: bool,
    ) -> SearchResult<()> {
        let clauses: Vec<(Occur, Box<dyn Query>)> = results
            .iter()
            .filter(|result| result.lexical_score.is_some() && result.metadata.is_none())
            .map(|result| {
                let term = Term::from_field_text(self.fields.id, result.doc_id.as_str());
                (
                    Occur::Should,
                    Box::new(TermQuery::new(term, IndexRecordOption::Basic)) as Box<dyn Query>,
                )
            })
            .collect();
        if clauses.is_empty() {
            return Ok(());
        }

        let limit = clauses.len();
        let query = BooleanQuery::new(clauses);
        let doc_addresses: Vec<DocAddress> = if unscored {
            // Every clause is an exact lookup on the unique `id` field. Hydration
            // consumes neither BM25 scores nor hit order, so asking Tantivy to
            // score and heap-sort these documents is pure overhead.
            search_guarded(searcher, &query, &DocSetCollector)?
                .into_iter()
                .collect()
        } else {
            search_guarded(
                searcher,
                &query,
                &TopDocs::with_limit(limit).order_by_score(),
            )?
            .into_iter()
            .map(|(_, doc_address)| doc_address)
            .collect()
        };

        for doc_address in doc_addresses {
            let doc = load_doc(searcher, doc_address)?;
            let doc_id = doc
                .get_first(self.fields.id)
                .and_then(|value| value.as_str())
                .unwrap_or_else(|| {
                    debug!("tantivy document missing id field while hydrating metadata");
                    ""
                });
            let metadata = doc
                .get_first(self.fields.metadata_json)
                .and_then(|value| value.as_str())
                .and_then(|raw| match serde_json::from_str(raw) {
                    Ok(value) => Some(value),
                    Err(error) => {
                        debug!(%doc_id, %error, "failed to deserialize metadata JSON");
                        None
                    }
                });
            if let Some(result) = results
                .iter_mut()
                .find(|result| result.doc_id.as_str() == doc_id)
            {
                result.metadata = metadata;
            }
        }

        Ok(())
    }

    /// Scored-collector baseline retained for the exact hydration A/B benchmark.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn hydrate_fusion_metadata_scored_for_bench<'a>(
        &'a self,
        _cx: &'a Cx,
        results: &'a mut [ScoredResult],
    ) -> SearchFuture<'a, ()> {
        // The scored-collector baseline deliberately reads the CURRENT
        // generation, matching what the retired combined-trait path did, so the
        // A/B keeps comparing collectors rather than pinning strategies.
        Box::pin(async move { self.hydrate_with_searcher(&self.reader.searcher(), results, false) })
    }

    /// Unscored-collector arm of the same A/B.
    ///
    /// The shipping path reaches this through `hydrate_candidates` with a
    /// pinned searcher; the benchmark needs it without a batch in hand, and on
    /// the same current-generation footing as the scored baseline above, so
    /// the measured difference stays the collector and nothing else.
    #[cfg(feature = "bench-internals")]
    #[doc(hidden)]
    pub fn hydrate_fusion_metadata_unscored_for_bench<'a>(
        &'a self,
        _cx: &'a Cx,
        results: &'a mut [ScoredResult],
    ) -> SearchFuture<'a, ()> {
        Box::pin(async move { self.hydrate_with_searcher(&self.reader.searcher(), results, true) })
    }
}

// ─── LexicalSearch implementation ───────────────────────────────────────────

impl frankensearch_core::traits::LexicalRead for TantivyIndex {
    #[instrument(skip_all, fields(query = %query, limit = limit))]
    fn search<'a>(
        &'a self,
        _cx: &'a Cx,
        query: &'a str,
        limit: usize,
    ) -> SearchFuture<'a, Vec<ScoredResult>> {
        Box::pin(async move {
            let query = Self::truncate_query(query);

            if query.trim().is_empty() || limit == 0 {
                return Ok(Vec::new());
            }

            let parsed = self.parse_query_shipping(query);

            let searcher = self.reader.searcher();
            let top_docs = search_guarded(
                &searcher,
                &*parsed,
                &TopDocs::with_limit(limit).order_by_score(),
            )?;

            debug!(hits = top_docs.len(), "tantivy BM25 search completed");

            let mut results = Vec::with_capacity(top_docs.len());
            for (bm25_score, doc_address) in top_docs {
                let doc: TantivyDocument =
                    searcher
                        .doc(doc_address)
                        .map_err(|e| SearchError::SubsystemError {
                            subsystem: "tantivy",
                            source: Box::new(e),
                        })?;

                let doc_id = doc
                    .get_first(self.fields.id)
                    .and_then(|v| v.as_str())
                    .unwrap_or_else(|| {
                        debug!("tantivy document missing id field, using empty doc_id");
                        ""
                    })
                    .to_owned();

                let metadata = doc
                    .get_first(self.fields.metadata_json)
                    .and_then(|v| v.as_str())
                    .and_then(|s| match serde_json::from_str(s) {
                        Ok(val) => Some(val),
                        Err(e) => {
                            debug!(doc_id = %doc_id, error = %e, "failed to deserialize metadata JSON");
                            None
                        }
                    });

                results.push(ScoredResult {
                    doc_id: doc_id.into(),
                    score: bm25_score,
                    source: ScoreSource::Lexical,
                    index: None,
                    fast_score: None,
                    quality_score: None,
                    lexical_score: Some(bm25_score),
                    rerank_score: None,
                    explanation: None,
                    metadata,
                });
            }

            Ok(results)
        })
    }

    /// Score candidates and pin the searcher that produced them.
    ///
    /// Tantivy's deferred-metadata path skips loading stored fields for the
    /// whole candidate pool and restores them only for the winners. The batch
    /// carries the exact [`Searcher`] used for scoring: a Tantivy searcher
    /// holds a fixed segment set, so it *is* the immutable generation handle
    /// this bead requires, and hydration through it cannot observe a commit
    /// that landed after scoring.
    fn search_candidates<'a>(
        &'a self,
        cx: &'a Cx,
        query: &'a str,
        limit: usize,
    ) -> SearchFuture<'a, LexicalCandidateBatch> {
        Box::pin(async move {
            let truncated = Self::truncate_query(query);
            // One searcher for scoring AND hydration. Taking a second one at
            // hydration time is exactly the generation race this pins shut.
            let searcher = self.reader.searcher();
            // An empty query or a zero limit still returns a *pinned* batch
            // rather than an eager one. Keeping the shape uniform means a
            // `None` context always signals caller misuse, so hydration can
            // reject it without having to guess whether the batch was legitimately
            // eager.
            let hits = if truncated.trim().is_empty() || limit == 0 {
                Vec::new()
            } else {
                let parsed = self.parse_query_shipping(truncated);
                execute_top_k(&searcher, &*parsed, limit, 0)?
            };
            let candidates = self
                .collect_id_hits(&searcher, hits)?
                .into_iter()
                .map(|hit| ScoredResult {
                    doc_id: hit.doc_id,
                    score: hit.bm25_score,
                    source: ScoreSource::Lexical,
                    index: None,
                    fast_score: None,
                    quality_score: None,
                    lexical_score: Some(hit.bm25_score),
                    rerank_score: None,
                    explanation: None,
                    metadata: None,
                })
                .collect();
            let _ = cx;
            Ok(LexicalCandidateBatch::deferred(
                candidates,
                LexicalHydrationContext::new("tantivy", Box::new(searcher)),
            ))
        })
    }

    /// Restore winner metadata from the pinned scoring searcher.
    ///
    /// Rejects a missing or foreign context with a typed error rather than
    /// silently reading the current generation.
    fn hydrate_candidates<'a>(
        &'a self,
        _cx: &'a Cx,
        context: Option<&'a LexicalHydrationContext>,
        results: &'a mut [ScoredResult],
    ) -> SearchFuture<'a, ()> {
        Box::pin(async move {
            let Some(context) = context else {
                return Err(SearchError::SubsystemError {
                    subsystem: "tantivy.hydration",
                    source: "deferred Tantivy candidates require their batch context; \
                             none was provided"
                        .into(),
                });
            };
            let Some(searcher) = context.downcast_ref::<Searcher>() else {
                return Err(SearchError::SubsystemError {
                    subsystem: "tantivy.hydration",
                    source: format!(
                        "hydration context from backend {:?} is not a Tantivy searcher pin; \
                         refusing cross-engine hydration",
                        context.backend()
                    )
                    .into(),
                });
            };
            self.hydrate_with_searcher(searcher, results, true)
        })
    }

    fn doc_count(&self) -> SearchResult<usize> {
        Self::checked_searcher_doc_count(&self.reader.searcher())
    }
}

impl frankensearch_core::traits::LexicalWrite for TantivyIndex {
    fn index_document<'a>(
        &'a self,
        cx: &'a Cx,
        doc: &'a IndexableDocument,
    ) -> SearchFuture<'a, ()> {
        Box::pin(async move {
            let mut tantivy_doc = self.to_tantivy_doc(doc);

            {
                let writer = self
                    .writer
                    .lock(cx)
                    .await
                    .map_err(|e| Self::map_writer_lock_error("tantivy.index", e))?;

                // Delete any existing document with same ID (upsert semantics).
                let term = Term::from_field_text(self.fields.id, &doc.id);
                writer.delete_term(term);
                self.assign_ord(&mut tantivy_doc, &doc.id);
                writer
                    .add_document(tantivy_doc)
                    .map_err(|e| SearchError::SubsystemError {
                        subsystem: "tantivy",
                        source: Box::new(e),
                    })?;
            }

            self.doc_count.fetch_add(1, Ordering::Relaxed);
            Ok(())
        })
    }

    fn index_documents<'a>(
        &'a self,
        cx: &'a Cx,
        docs: &'a [IndexableDocument],
    ) -> SearchFuture<'a, ()> {
        Box::pin(async move {
            {
                let writer = self
                    .writer
                    .lock(cx)
                    .await
                    .map_err(|e| Self::map_writer_lock_error("tantivy.batch_index", e))?;

                for doc in docs {
                    let mut tantivy_doc = self.to_tantivy_doc(doc);
                    // Upsert: delete existing then add.
                    let term = Term::from_field_text(self.fields.id, &doc.id);
                    writer.delete_term(term);
                    self.assign_ord(&mut tantivy_doc, &doc.id);
                    writer
                        .add_document(tantivy_doc)
                        .map_err(|e| SearchError::SubsystemError {
                            subsystem: "tantivy",
                            source: Box::new(e),
                        })?;
                }
            }

            self.doc_count.fetch_add(docs.len(), Ordering::Relaxed);

            debug!(count = docs.len(), "batch indexed documents");
            Ok(())
        })
    }

    fn commit<'a>(&'a self, cx: &'a Cx) -> SearchFuture<'a, ()> {
        Box::pin(async move {
            {
                let mut writer = self
                    .writer
                    .lock(cx)
                    .await
                    .map_err(|e| Self::map_writer_lock_error("tantivy.commit", e))?;

                writer.commit().map_err(|e| SearchError::SubsystemError {
                    subsystem: "tantivy",
                    source: Box::new(e),
                })?;
            }

            // Reload the reader to pick up committed changes.
            self.reader
                .reload()
                .map_err(|e| SearchError::SubsystemError {
                    subsystem: "tantivy",
                    source: Box::new(e),
                })?;

            // Re-count after commit for accuracy.
            let searcher = self.reader.searcher();
            let actual = usize::try_from(searcher.num_docs()).unwrap_or(usize::MAX);
            self.doc_count.store(actual, Ordering::Relaxed);

            // Persist the ordinal→doc_id table so a reopen keeps the fast path.
            self.persist_ord_table();

            debug!(doc_count = actual, "tantivy commit completed");
            Ok(())
        })
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    // The split capabilities, so `idx.search(..)` / `idx.doc_count()` resolve
    // now that the combined trait is gone. B1 deliberately kept these out of
    // module scope to avoid method ambiguity while both surfaces coexisted.
    use frankensearch_core::traits::{LexicalRead, LexicalWrite};
    use frankensearch_core::types::IndexableDocument;

    /// Helper: run async test code with a `Cx`.
    fn run_with_cx<F, Fut>(f: F)
    where
        F: FnOnce(Cx) -> Fut,
        Fut: Future<Output = ()>,
    {
        asupersync::test_utils::run_test_with_cx(f);
    }

    /// bd-f20ye: BOOSTING A GROUP CHANGES ITS BOOLEAN MEANING in tantivy
    /// 0.26.1 whenever the group contains a negation. Pinned, not fixed.
    ///
    /// The bead was filed — by me — claiming the lenient-parse fallback "drops"
    /// the negation, which is what the Divergence Register had said about this
    /// shape since DIV-007. Probing the parser falsified all of it: nothing is
    /// dropped, the `MustNot` clause is present in the parsed query, strict and
    /// lenient parses agree, and `parse_query_lenient` reports NO errors. The
    /// mechanism is structural.
    ///
    /// An unboosted group lowers its negation as a `MustNot` clause OF the
    /// enclosing boolean, which excludes. A BOOSTED group instead nests the
    /// negation in its own `BooleanQuery { [(MustNot, ...)], msm: 0 }` and
    /// attaches THAT as a clause of the outer boolean — so a matcher meaning
    /// "every document except B" becomes a positive alternative, and the group
    /// stops meaning what it read as.
    ///
    /// Both directions are wrong, which is why this is pinned as behaviour
    /// rather than reasoned about:
    ///
    ///   (alpha NOT beta)        [p2]      correct exclusion
    ///   (alpha NOT beta)^2      [p1, p2]  the excluded document comes back
    ///   (alpha AND NOT beta)^2  []        and the AND form loses everything
    ///
    /// NOT FIXED HERE, deliberately. `frankensearch-lexical` is simultaneously
    /// the shipping tantivy backend and the gauntlet's PINNED CONFORMANCE
    /// ORACLE. Rewriting queries here to restore the intuitive meaning would
    /// silently move the conformance target that Quill is measured against —
    /// the exact shape of "weaken the oracle to make the comparison pass". Quill
    /// executes these shapes correctly, so the divergence is registered
    /// (DIV-009, blocking on bd-f20ye) and this test exists so that a tantivy
    /// upgrade which changes the behaviour becomes VISIBLE instead of quietly
    /// shifting that target. Same posture as bd-nqeb4's `#[should_panic]` pin.
    /// bd-eeq0q: `A AND NOT B` returns A-minus-B on the SHIPPING path, while
    /// the ORACLE path still reproduces tantivy 0.26.1's empty result.
    ///
    /// PLANTED NEGATIVES RUN BOTH DIRECTIONS, because this repair can fail two
    /// opposite ways and only one of them is obvious. If the repair stops
    /// working, the shipping assertions go red. If it LEAKS into the oracle
    /// surface, the oracle assertions go red — that direction matters more,
    /// since a repaired oracle would silently move the conformance target Quill
    /// is measured against, which is the "weaken the oracle to make the
    /// comparison pass" failure this crate's two-role split exists to prevent.
    ///
    /// The quoted control is the third direction: a literal `"a AND NOT b"`
    /// phrase must never be rewritten, or the repair would corrupt user text
    /// rather than user syntax.
    #[cfg(feature = "tantivy-oracle")]
    #[test]
    fn and_not_returns_a_minus_b_on_shipping_while_the_oracle_stays_bit_faithful() {
        run_with_cx(|cx| async move {
            let index = TantivyIndex::in_memory().expect("bd-eeq0q index");
            index
                .index_documents(
                    &cx,
                    &[
                        IndexableDocument::new("p1", "alpha beta"),
                        IndexableDocument::new("p2", "alpha gamma"),
                    ],
                )
                .await
                .expect("index bd-eeq0q documents");
            index.commit(&cx).await.expect("commit bd-eeq0q documents");

            let ship = |query: &'static str| {
                let index = &index;
                let cx = &cx;
                async move {
                    let mut ids = index
                        .search(cx, query, 10)
                        .await
                        .expect("bd-eeq0q shipping search")
                        .into_iter()
                        .map(|hit| hit.doc_id)
                        .collect::<Vec<_>>();
                    ids.sort();
                    ids
                }
            };

            // Every spelling of "alpha but not beta" agrees on the shipping
            // path. The first two already worked; the rest are the repair.
            for query in [
                "alpha NOT beta",
                "alpha -beta",
                "alpha AND NOT beta",
                "(alpha AND NOT beta)",
                "(alpha AND NOT beta)^2",
            ] {
                assert_eq!(
                    ship(query).await,
                    vec!["p2".to_owned()],
                    "shipping {query:?} must return A-minus-B"
                );
            }

            // Repeated exclusion still excludes, and does not resurrect p1.
            assert_eq!(
                ship("alpha AND NOT beta AND NOT delta").await,
                vec!["p2".to_owned()],
                "a second AND NOT must keep excluding"
            );

            // A literal phrase is user TEXT, not user SYNTAX: never rewritten.
            assert!(
                ship("\"alpha AND NOT beta\"").await.is_empty(),
                "a quoted phrase must not be rewritten into an operator form"
            );

            // THE ORACLE HAS NOT MOVED. Same index, same queries, through the
            // conformance surface: tantivy 0.26.1's behaviour, defect included.
            let oracle_ids = |query: &'static str| {
                let mut ids = index
                    .oracle_observe_query(&cx, query, 10, 64, &SnippetConfig::default())
                    .expect("bd-eeq0q oracle observation")
                    .hits
                    .into_iter()
                    .map(|hit| hit.doc_id)
                    .collect::<Vec<_>>();
                ids.sort();
                ids
            };
            let oracle_empty = oracle_ids("alpha AND NOT beta");
            assert!(
                oracle_empty.is_empty(),
                "the oracle must still reproduce the tantivy 0.26.1 defect, got {oracle_empty:?}"
            );
            assert!(
                oracle_ids("(alpha AND NOT beta)^2").is_empty(),
                "the boosted form must stay defective on the oracle surface too"
            );
            assert_eq!(
                oracle_ids("alpha NOT beta"),
                vec!["p2".to_owned()],
                "the oracle's own correct spelling must be unaffected"
            );
        });
    }

    /// bd-8a2a8: the normal form the repair emits, asserted as TEXT.
    ///
    /// The end-to-end test below proves the answers; this one pins the shape,
    /// because two of the properties that make the repair safe are invisible in
    /// a result set. `(a AND NOT b)^2` must keep its `-` DIRECTLY inside the
    /// boosted group — `repair_boosted_group_negation` records negation against
    /// the innermost open group, so an extra layer of parentheses would silently
    /// un-repair DIV-009 while every membership assertion stayed green. And a
    /// query with nothing to repair must come back BORROWED, which is both the
    /// allocation contract and a check that the scanner declines rather than
    /// guesses on input it cannot decode.
    #[test]
    fn a_negated_conjunction_normalises_to_explicit_occurrences() {
        for (query, expected) in [
            // The reported defect: `AND` binds tighter than the default join.
            // Operand ORDER is preserved; only the occurrences become explicit.
            ("alpha NOT beta AND gamma", "alpha (-beta +gamma)"),
            // A chain that IS the level keeps its operand order and adds no
            // parentheses.
            ("alpha AND NOT beta AND gamma", "+alpha -beta +gamma"),
            ("gamma AND NOT beta", "+gamma -beta"),
            ("NOT beta AND gamma", "-beta +gamma"),
            // DIV-009 interlock: the `-` stays directly inside the boost.
            ("(alpha AND NOT beta)^2", "(+alpha -beta)^2"),
            // Operands are carried through whole: phrases, fields, boosts, and
            // a fielded group that must not be split at its parenthesis.
            ("alpha AND NOT \"beta gamma\"", "+alpha -\"beta gamma\""),
            ("content:alpha^2 AND NOT beta", "+content:alpha^2 -beta"),
            (
                "field:(alpha beta) AND NOT gamma",
                "+field:(alpha beta) -gamma",
            ),
            // Occurrence outside the chain survives: a `+` that is dropped
            // turns a Must clause into a Should one.
            ("+alpha delta AND NOT beta", "+alpha (+delta -beta)"),
            // Recursion into a group, with the outer level left alone.
            (
                "(alpha NOT beta AND gamma) OR delta",
                "(alpha (-beta +gamma)) OR delta",
            ),
            // Stacked negators lower to one exclusion.
            ("alpha NOT -beta AND gamma", "alpha (-beta +gamma)"),
            // bd-iiidv: an ALL-NEGATIVE chain normalises too, in either operand
            // order, and the normal form carries no `AND` -- which is why the
            // repair already covered this shape while the register recorded it
            // as agreement. There is no `+` to add: every operand is excluded,
            // and the complement anchoring is the parser's job, not this
            // rewrite's.
            ("NOT beta AND NOT gamma", "-beta -gamma"),
            ("NOT gamma AND NOT beta", "-gamma -beta"),
        ] {
            assert_eq!(
                repair_negated_conjunction(query).as_ref(),
                expected,
                "normal form for {query:?}"
            );
        }

        // PLANTED NEGATIVES: everything here must be returned untouched, and
        // `Cow::Borrowed` proves the scanner did not merely round-trip it.
        for untouched in [
            // No explicit `AND`: nothing to normalise.
            "alpha NOT beta",
            "alpha -beta",
            "alpha beta",
            // A pure-positive conjunction is not defective; leave the spelling.
            "alpha AND gamma",
            "alpha AND beta AND gamma",
            // User TEXT, not user syntax.
            "\"alpha AND NOT beta\"",
            // Lowercase `and` is a pair of ordinary terms in this grammar.
            "alpha and not beta",
            // Undecodable input is declined, never guessed at.
            "alpha AND",
            "AND NOT beta",
            "alpha AND OR beta",
            "alpha AND \"unbalanced",
        ] {
            assert!(
                matches!(repair_negated_conjunction(untouched), Cow::Borrowed(_)),
                "{untouched:?} must be left untouched, got {:?}",
                repair_negated_conjunction(untouched)
            );
        }
    }

    /// bd-8a2a8: `A NOT B AND C` returns the declared reading on the SHIPPING
    /// path, while the ORACLE path still reproduces tantivy 0.26.1's answer.
    ///
    /// THE DECLARED READING is `default join := OR; explicit AND has precedence
    /// over OR` (`docs/contracts/quill-language-contract.md`), so
    /// `alpha NOT beta AND gamma` is `alpha OR (gamma AND NOT beta)`. Tantivy
    /// 0.26.1 lowers the conjunct's negation into a positive-less boolean, so
    /// the conjunct matches nothing and the whole `AND` clause disappears —
    /// `p3` is the document that only the correct reading returns.
    ///
    /// THE ATTRIBUTION CONTROL is the same query with its grouping written out.
    /// `alpha ((gamma) NOT beta)` carries no `AND`, is therefore untouched by
    /// every repair, and this engine answers it CORRECTLY on both roles. So the
    /// engine already agrees with the declared reading when the grouping is
    /// explicit, which is what places the defect in the implicit lowering
    /// rather than in either side's semantics.
    ///
    /// PLANTED NEGATIVES RUN THREE DIRECTIONS. If the repair stops working the
    /// shipping assertions go red; if it LEAKS into the oracle surface the
    /// oracle assertions go red, which is the direction that matters more,
    /// because a repaired oracle silently moves the conformance target Quill is
    /// measured against. The third is the repair ORDER: `repair_and_not` deletes
    /// the `AND` in front of a `NOT`, so if it ran first, `alpha AND NOT beta
    /// AND gamma` would arrive here as the unrelated chain `NOT beta AND gamma`
    /// and normalise to `alpha (+gamma -beta)` — a disjunction returning three
    /// documents where the conjunction returns one.
    #[cfg(feature = "tantivy-oracle")]
    #[test]
    fn a_negated_conjunction_reads_as_a_disjunct_on_shipping_while_the_oracle_stays_bit_faithful() {
        run_with_cx(|cx| async move {
            let index = TantivyIndex::in_memory().expect("bd-8a2a8 index");
            index
                .index_documents(
                    &cx,
                    &[
                        IndexableDocument::new("p1", "alpha beta"),
                        IndexableDocument::new("p2", "alpha gamma"),
                        IndexableDocument::new("p3", "gamma"),
                        IndexableDocument::new("p4", "beta gamma"),
                        IndexableDocument::new("p5", "delta"),
                    ],
                )
                .await
                .expect("index bd-8a2a8 documents");
            index.commit(&cx).await.expect("commit bd-8a2a8 documents");

            let ship = |query: &'static str| {
                let index = &index;
                let cx = &cx;
                async move {
                    let mut ids = index
                        .search(cx, query, 10)
                        .await
                        .expect("bd-8a2a8 shipping search")
                        .into_iter()
                        .map(|hit| hit.doc_id)
                        .collect::<Vec<_>>();
                    ids.sort();
                    ids
                }
            };
            let ids =
                |wanted: &[&str]| wanted.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();

            // THE DEFECT, and the same reading spelled three other ways. `p3`
            // matches `gamma` without `beta`, so it appears only when the `AND`
            // conjunct survives.
            for query in [
                "alpha NOT beta AND gamma",
                "alpha NOT -beta AND gamma",
                "alpha ((gamma) NOT beta)",
                "alpha (gamma AND NOT beta)",
            ] {
                assert_eq!(
                    ship(query).await,
                    ids(&["p1", "p2", "p3"]),
                    "shipping {query:?} must return alpha OR (gamma minus beta)"
                );
            }

            // THE CHAIN STILL BINDS AS A CONJUNCTION. This is the repair-order
            // negative: a disjunctive reading here would return three documents.
            assert_eq!(
                ship("alpha AND NOT beta AND gamma").await,
                ids(&["p2"]),
                "a single AND chain must stay a conjunction"
            );
            for query in ["gamma AND NOT beta", "NOT beta AND gamma"] {
                assert_eq!(
                    ship(query).await,
                    ids(&["p2", "p3"]),
                    "shipping {query:?} must return gamma minus beta"
                );
            }

            // The contract's all-documents literal is an operand like any
            // other, and must survive being given an explicit occurrence.
            assert_eq!(
                ship("* AND NOT beta").await,
                ids(&["p2", "p3", "p5"]),
                "every document except the excluded ones"
            );

            // Controls: a pure-positive conjunction is unchanged, an explicit
            // `+` still means Must, and a quoted phrase is text.
            assert_eq!(ship("alpha AND gamma").await, ids(&["p2"]));
            assert_eq!(
                ship("+alpha delta AND NOT beta").await,
                ids(&["p1", "p2"]),
                "a required clause must not be demoted to optional"
            );
            assert_eq!(
                ship("alpha delta AND NOT beta").await,
                ids(&["p1", "p2", "p5"]),
                "without the `+` the same query is a disjunction"
            );
            assert!(
                ship("\"alpha NOT beta AND gamma\"").await.is_empty(),
                "a quoted phrase must not be rewritten into an operator form"
            );

            // THE ORACLE HAS NOT MOVED. Same index, same queries, through the
            // conformance surface: tantivy 0.26.1's behaviour, defect included.
            let oracle_ids = |query: &'static str| {
                let mut ids = index
                    .oracle_observe_query(&cx, query, 10, 64, &SnippetConfig::default())
                    .expect("bd-8a2a8 oracle observation")
                    .hits
                    .into_iter()
                    .map(|hit| hit.doc_id)
                    .collect::<Vec<_>>();
                ids.sort();
                ids
            };
            assert_eq!(
                oracle_ids("alpha NOT beta AND gamma"),
                ids(&["p1", "p2"]),
                "the oracle must still drop the AND conjunct entirely"
            );
            assert!(
                oracle_ids("gamma AND NOT beta").is_empty(),
                "the oracle must still return nothing for a bare negated conjunction"
            );
            assert_eq!(
                oracle_ids("alpha ((gamma) NOT beta)"),
                ids(&["p1", "p2", "p3"]),
                "the explicit grouping is answered correctly by BOTH roles, which \
                 is what attributes the defect to the implicit lowering"
            );
        });
    }

    /// bd-iiidv: an ALL-NEGATIVE conjunction is DIV-010's defect too, and the
    /// register said it was agreement.
    ///
    /// The Divergence Register's DIV-010 entry claimed `NOT alpha AND NOT beta`
    /// "still returns nothing on both, because an exclusion-only conjunction
    /// has no positive term — that is agreement, not a defect, and is pinned so
    /// a later change cannot silently turn it into match-all". Measured, it is
    /// not agreement and there was no such pin. This is the pin.
    ///
    /// The claim is wrong twice over. An all-negative ROOT does not match
    /// nothing — both engines give it complement semantics for every spelling
    /// that carries no explicit `AND` — and the `AND` spelling does not agree:
    /// the pinned oracle empties it while the declared reading, Quill and the
    /// repaired shipping path all return the complement.
    ///
    /// It is the SAME mechanism as the rest of DIV-010, not a new one: an
    /// explicit `AND` whose operand is a negation lowers to a positive-less
    /// boolean that matches nothing and empties the conjunction. That is why
    /// `repair_negated_conjunction` already fixes it — the normal form carries
    /// no `AND` — and why the fix needed no new repair, only this proof that it
    /// covers the shape.
    #[cfg(feature = "tantivy-oracle")]
    #[test]
    fn an_all_negative_conjunction_is_complement_on_shipping_and_empty_on_the_oracle() {
        run_with_cx(|cx| async move {
            let index = TantivyIndex::in_memory().expect("bd-iiidv index");
            index
                .index_documents(
                    &cx,
                    &[
                        IndexableDocument::new("p1", "alpha beta"),
                        IndexableDocument::new("p2", "alpha gamma"),
                        IndexableDocument::new("p3", "delta gamma"),
                        IndexableDocument::new("p4", "epsilon"),
                    ],
                )
                .await
                .expect("index bd-iiidv documents");
            index.commit(&cx).await.expect("commit bd-iiidv documents");

            let shipping = |query: &'static str| {
                let index = &index;
                let cx = &cx;
                async move {
                    let mut ids = index
                        .search(cx, query, 10)
                        .await
                        .expect("bd-iiidv search")
                        .into_iter()
                        .map(|hit| hit.doc_id)
                        .collect::<Vec<_>>();
                    ids.sort();
                    ids
                }
            };
            let oracle = |query: &'static str| {
                let index = &index;
                let cx = &cx;
                async move {
                    let mut ids = index
                        .oracle_observe_query(cx, query, 10, 64, &SnippetConfig::default())
                        .expect("bd-iiidv oracle observation")
                        .hits
                        .into_iter()
                        .map(|hit| hit.doc_id)
                        .collect::<Vec<_>>();
                    ids.sort();
                    ids
                }
            };

            // THE DEFECT, in both operand orders. `p4` is the only document
            // matching neither term, so the complement is exactly `[p4]` and an
            // empty answer is not "no positive term" -- it is the conjunct
            // being emptied.
            for query in ["NOT beta AND NOT gamma", "NOT gamma AND NOT beta"] {
                assert_eq!(
                    oracle(query).await,
                    Vec::<String>::new(),
                    "the pinned oracle must still empty an all-negative conjunction: {query}"
                );
                assert_eq!(
                    shipping(query).await,
                    vec!["p4".to_owned()],
                    "the shipping path must answer the complement: {query}"
                );
            }

            // THE ATTRIBUTION, and the refutation of the "agreement" claim in
            // one measurement: the SAME oracle answers every spelling of the
            // same intent that carries no explicit `AND` with the complement.
            // An engine that gives an all-negative root complement semantics
            // whenever the conjunction is spelled another way is mislowering
            // the `AND` form, not asserting that exclusion-only matches
            // nothing.
            for query in ["NOT beta NOT gamma", "-beta -gamma", "NOT beta -gamma"] {
                assert_eq!(
                    oracle(query).await,
                    vec!["p4".to_owned()],
                    "the oracle gives an all-negative root complement semantics here: {query}"
                );
                assert_eq!(
                    shipping(query).await,
                    vec!["p4".to_owned()],
                    "and the shipping path agrees, so these spellings are not divergent: {query}"
                );
            }

            // NOT match-all, which is the failure the register's own sentence
            // was worried about: a single negation still excludes, and the
            // complement of a term that matches nothing is still bounded by the
            // corpus.
            assert_eq!(
                shipping("NOT beta").await,
                vec!["p2".to_owned(), "p3".to_owned(), "p4".to_owned()]
            );
            assert_eq!(
                oracle("NOT beta").await,
                vec!["p2".to_owned(), "p3".to_owned(), "p4".to_owned()]
            );
        });
    }

    #[cfg(feature = "tantivy-oracle")]
    #[test]
    fn boosting_a_group_that_negates_changes_its_meaning_in_the_pinned_oracle() {
        run_with_cx(|cx| async move {
            let index = TantivyIndex::in_memory().expect("bd-f20ye index");
            index
                .index_documents(
                    &cx,
                    &[
                        IndexableDocument::new("p1", "alpha beta"),
                        IndexableDocument::new("p2", "alpha gamma"),
                    ],
                )
                .await
                .expect("index bd-f20ye documents");
            index.commit(&cx).await.expect("commit bd-f20ye documents");

            // The SHIPPING role, through the public search surface.
            let hits = |query: &'static str| {
                let index = &index;
                let cx = &cx;
                async move {
                    let mut ids = index
                        .search(cx, query, 10)
                        .await
                        .expect("bd-f20ye search")
                        .into_iter()
                        .map(|hit| hit.doc_id)
                        .collect::<Vec<_>>();
                    ids.sort();
                    ids
                }
            };
            // The ORACLE role, through the conformance observation surface.
            let oracle_hits = |query: &'static str| {
                let index = &index;
                let cx = &cx;
                async move {
                    let mut ids = index
                        .oracle_observe_query(cx, query, 10, 64, &SnippetConfig::default())
                        .expect("bd-f20ye oracle observation")
                        .hits
                        .into_iter()
                        .map(|hit| hit.doc_id)
                        .collect::<Vec<_>>();
                    ids.sort();
                    ids
                }
            };

            // The negation is NOT dropped and recovery is NOT involved: the
            // lenient parser reports no errors at all for the broken shape.
            let (_parsed, errors) = index
                .query_parser()
                .parse_query_lenient("(alpha NOT beta)^2");
            assert!(
                errors.is_empty(),
                "bd-f20ye is not a lenient-recovery defect; the parser reported {errors:?}"
            );

            // CORRECT, unboosted — both roles agree here.
            assert_eq!(hits("alpha NOT beta").await, vec!["p2".to_owned()]);
            assert_eq!(hits("(alpha NOT beta)").await, vec!["p2".to_owned()]);
            assert!(hits("(alpha NOT alpha)").await.is_empty());

            // The page-observation surface must ALSO stay bit-faithful: a
            // repair leaking into any oracle_observe_* method is what would
            // move the conformance target without a comparison going red.
            let page = index
                .oracle_observe_page(&cx, "(alpha NOT beta)^2", 10, 0)
                .expect("bd-f20ye oracle page observation");
            assert_eq!(
                page.hits.len(),
                2,
                "the oracle page surface must reproduce the defect, not the repair"
            );

            // STILL WRONG IN THE ORACLE ROLE, and that is the point: the
            // comparator must reproduce Tantivy 0.26.1 byte for byte, defects
            // included, or the conformance target moves under Quill.
            assert_eq!(
                oracle_hits("(alpha NOT beta)^2").await,
                vec!["p1".to_owned(), "p2".to_owned()],
                "if this is now [p2], tantivy fixed the boosted-group negation and DIV-009 \
                 must be re-measured before it is retired"
            );
            assert_eq!(
                oracle_hits("(alpha NOT alpha)^2").await,
                vec!["p1".to_owned(), "p2".to_owned()],
                "if this is now empty, tantivy fixed the boosted-group negation"
            );
            assert!(
                oracle_hits("(alpha AND NOT beta)^2").await.is_empty(),
                "if this is now [p2], tantivy fixed the boosted-group negation"
            );

            // REPAIRED IN THE SHIPPING ROLE (bd-f20ye owner ruling): a boost
            // must never change which documents match.
            assert_eq!(
                hits("(alpha NOT beta)^2").await,
                vec!["p2".to_owned()],
                "the shipping path must not return a document the query excluded"
            );
            assert!(
                hits("(alpha NOT alpha)^2").await.is_empty(),
                "a self-contradictory group must match nothing however it is boosted"
            );
            // THE INVARIANT THE RULING ASKS FOR, stated as an invariant rather
            // than as hardcoded expectations: a boost must never change WHICH
            // documents match. Asserting `boosted == unboosted` says exactly
            // that, and stays true whatever the unboosted form happens to
            // return.
            for group in [
                "(alpha NOT beta)",
                "(alpha NOT alpha)",
                "(alpha AND NOT beta)",
                "(alpha -beta)",
                "(alpha OR beta)",
            ] {
                let boosted = format!("{group}^2");
                assert_eq!(
                    hits(Box::leak(boosted.into_boxed_str())).await,
                    hits(Box::leak(group.to_owned().into_boxed_str())).await,
                    "boosting {group} changed which documents match in the shipping path"
                );
            }
            // SUPERSEDED BY bd-eeq0q, deliberately flipped rather than deleted.
            // When this test landed, `A AND NOT B` returned nothing on the
            // shipping path too — a SEPARATE defect from the boosted-group one,
            // filed as bd-eeq0q and repaired there by `repair_and_not`. This
            // assertion recorded the defect as it stood; it now records the
            // repair. The invariant ABOVE is what belongs to this bead and is
            // unchanged: a boost may not alter membership. Keeping the line
            // (rather than dropping it) preserves the fact that the two defects
            // were separable and were separated.
            assert_eq!(
                hits("alpha AND NOT beta").await,
                vec!["p2".to_owned()],
                "bd-eeq0q repairs the ungrouped form on the shipping path"
            );
            // NESTED, so the repair is not merely a whole-query special case.
            assert_eq!(
                hits("beta OR (alpha NOT beta)^2").await,
                vec!["p1".to_owned(), "p2".to_owned()]
            );
            assert_eq!(
                hits("(alpha -beta)^3").await,
                vec!["p2".to_owned()],
                "the `-term` exclusion form must be repaired too"
            );

            // CONTROL: a boosted group WITHOUT a negation keeps its meaning in
            // BOTH roles, so the repair is specific to negation and does not
            // quietly disarm boosts in general.
            for query in ["(alpha OR beta)^2", "(beta)^2"] {
                assert_eq!(
                    hits(query).await,
                    oracle_hits(query).await,
                    "{query} must be identical in both roles"
                );
            }
            assert_eq!(
                hits("(alpha OR beta)^2").await,
                vec!["p1".to_owned(), "p2".to_owned()]
            );
            assert_eq!(hits("(beta)^2").await, vec!["p1".to_owned()]);
        });
    }

    fn sample_docs() -> Vec<IndexableDocument> {
        vec![
            IndexableDocument::new("doc-1", "Rust is a systems programming language")
                .with_title("Rust Overview")
                .with_metadata("lang", "en"),
            IndexableDocument::new(
                "doc-2",
                "Python is great for data science and machine learning",
            )
            .with_title("Python for ML"),
            IndexableDocument::new("doc-3", "The Rust borrow checker prevents data races")
                .with_title("Rust Safety"),
            IndexableDocument::new(
                "doc-4",
                "Distributed consensus algorithms like Raft and Paxos",
            )
            .with_title("Consensus Algorithms"),
            IndexableDocument::new(
                "doc-5",
                "Machine learning models for natural language processing",
            )
            .with_title("NLP Models"),
        ]
    }

    fn shared_full120_docs() -> Vec<IndexableDocument> {
        let fixture: serde_json::Value =
            serde_json::from_str(include_str!("../../../tests/fixtures/corpus.json"))
                .expect("parse committed Full120 corpus");
        let documents = fixture["documents"]
            .as_array()
            .expect("fixture documents array");
        assert_eq!(documents.len(), 120, "Full120 fixture count drifted");
        documents
            .iter()
            .enumerate()
            .map(|(ordinal, document)| {
                let mut metadata = document["metadata"]
                    .as_object()
                    .expect("fixture metadata")
                    .iter()
                    .map(|(key, value)| {
                        (
                            key.clone(),
                            value
                                .as_str()
                                .map_or_else(|| value.to_string(), str::to_owned),
                        )
                    })
                    .collect::<std::collections::HashMap<_, _>>();
                metadata.insert(
                    "created_at".to_owned(),
                    document["created_at"]
                        .as_str()
                        .expect("fixture created_at")
                        .to_owned(),
                );
                metadata.insert(
                    "doc_type".to_owned(),
                    document["doc_type"]
                        .as_str()
                        .expect("fixture doc_type")
                        .to_owned(),
                );
                metadata.insert("created_at_ms".to_owned(), ordinal.to_string());
                IndexableDocument {
                    id: document["doc_id"]
                        .as_str()
                        .expect("fixture doc_id")
                        .to_owned(),
                    content: document["content"]
                        .as_str()
                        .expect("fixture content")
                        .to_owned(),
                    title: Some(
                        document["title"]
                            .as_str()
                            .expect("fixture title")
                            .to_owned(),
                    ),
                    metadata,
                }
            })
            .collect()
    }

    fn optional_score_bits(score: Option<f32>) -> Option<u32> {
        score.map(f32::to_bits)
    }

    fn assert_scored_result_contract(
        actual: &ScoredResult,
        expected: &ScoredResult,
        context: &str,
    ) {
        assert_eq!(actual.doc_id, expected.doc_id, "doc_id: {context}");
        assert_eq!(
            actual.score.to_bits(),
            expected.score.to_bits(),
            "score: {context}"
        );
        assert_eq!(actual.source, expected.source, "source: {context}");
        assert_eq!(actual.index, expected.index, "index: {context}");
        assert_eq!(
            optional_score_bits(actual.fast_score),
            optional_score_bits(expected.fast_score),
            "fast score: {context}"
        );
        assert_eq!(
            optional_score_bits(actual.quality_score),
            optional_score_bits(expected.quality_score),
            "quality score: {context}"
        );
        assert_eq!(
            optional_score_bits(actual.lexical_score),
            optional_score_bits(expected.lexical_score),
            "lexical score: {context}"
        );
        assert_eq!(
            optional_score_bits(actual.rerank_score),
            optional_score_bits(expected.rerank_score),
            "rerank score: {context}"
        );
        assert_eq!(
            serde_json::to_value(&actual.explanation).expect("serialize actual explanation"),
            serde_json::to_value(&expected.explanation).expect("serialize expected explanation"),
            "explanation: {context}"
        );
        assert_eq!(
            actual.metadata.as_deref(),
            expected.metadata.as_deref(),
            "metadata: {context}"
        );
    }

    async fn assert_live_lexical_contract(
        idx: &TantivyIndex,
        cx: &Cx,
        query: &str,
        limit: usize,
        expected_total_count: usize,
    ) {
        let context = format!("query={query:?}, limit={limit}");
        let full = idx.search(cx, query, limit).await.expect("full search");
        let id_hits = idx
            .search_doc_ids(cx, query, limit)
            .expect("ord-table ID search");
        let docstore_hits = idx
            .search_doc_ids_via_docstore(cx, query, limit)
            .expect("docstore ID search");
        let candidate_batch = idx
            .search_candidates(cx, query, limit)
            .await
            .expect("fusion candidate search");
        let (mut candidates, candidate_pin) = candidate_batch.into_parts();

        assert_eq!(
            id_hits, docstore_hits,
            "ordinal table must independently resolve the same IDs as stored documents: {context}"
        );
        assert_eq!(full.len(), id_hits.len(), "full/id length: {context}");
        assert_eq!(
            full.len(),
            candidates.len(),
            "full/candidate length: {context}"
        );
        assert_eq!(
            full.len(),
            limit.min(expected_total_count),
            "result count: {context}"
        );

        for (rank, ((expected, id_hit), candidate)) in
            full.iter().zip(&id_hits).zip(&candidates).enumerate()
        {
            let row_context = format!("{context}, rank={rank}");
            assert_eq!(id_hit.rank, rank, "ID rank: {row_context}");
            assert_eq!(id_hit.doc_id, expected.doc_id, "ID doc_id: {row_context}");
            assert_eq!(
                id_hit.bm25_score.to_bits(),
                expected.score.to_bits(),
                "ID score: {row_context}"
            );
            assert_eq!(
                candidate.doc_id, expected.doc_id,
                "candidate doc_id: {row_context}"
            );
            assert_eq!(
                candidate.score.to_bits(),
                expected.score.to_bits(),
                "candidate score: {row_context}"
            );
            assert_eq!(
                optional_score_bits(candidate.lexical_score),
                optional_score_bits(expected.lexical_score),
                "candidate lexical score: {row_context}"
            );
            assert_eq!(candidate.source, expected.source, "source: {row_context}");
            assert_eq!(candidate.index, expected.index, "index: {row_context}");
            assert_eq!(
                optional_score_bits(candidate.fast_score),
                optional_score_bits(expected.fast_score),
                "fast score: {row_context}"
            );
            assert_eq!(
                optional_score_bits(candidate.quality_score),
                optional_score_bits(expected.quality_score),
                "quality score: {row_context}"
            );
            assert_eq!(
                optional_score_bits(candidate.rerank_score),
                optional_score_bits(expected.rerank_score),
                "rerank score: {row_context}"
            );
            assert_eq!(
                serde_json::to_value(&candidate.explanation)
                    .expect("serialize candidate explanation"),
                serde_json::to_value(&expected.explanation)
                    .expect("serialize expected explanation"),
                "explanation: {row_context}"
            );
            assert!(
                candidate.metadata.is_none(),
                "candidate metadata must be deferred: {row_context}"
            );
        }

        idx.hydrate_candidates(cx, candidate_pin.as_ref(), &mut candidates)
            .await
            .expect("hydrate fusion metadata");
        for (rank, (candidate, expected)) in candidates.iter().zip(&full).enumerate() {
            assert_scored_result_contract(
                candidate,
                expected,
                &format!("{context}, hydrated rank={rank}"),
            );
        }

        let parsed = idx.parse_query_lenient(query);
        let counted = execute_query_with_offset(&idx.reader.searcher(), &*parsed, limit, 0)
            .expect("exact counted search");
        assert_eq!(
            counted.total_count, expected_total_count,
            "Count must remain exact and independent of k: {context}"
        );
    }

    // ─── Schema tests ───────────────────────────────────────────────────

    #[test]
    fn schema_has_required_fields() {
        let (schema, fields) = build_schema();
        assert!(schema.get_field_entry(fields.id).is_stored());
        assert!(schema.get_field_entry(fields.content).is_stored());
        assert!(schema.get_field_entry(fields.title).is_stored());
        assert!(schema.get_field_entry(fields.metadata_json).is_stored());
    }

    // ─── Index lifecycle tests ──────────────────────────────────────────

    #[test]
    fn create_in_memory() {
        let idx = TantivyIndex::in_memory().expect("create");
        assert_eq!(idx.doc_count().expect("document count"), 0);
    }

    #[test]
    fn create_on_disk() {
        let dir = tempfile::tempdir().expect("tempdir");
        let idx = TantivyIndex::create(dir.path()).expect("create");
        assert_eq!(idx.doc_count().expect("document count"), 0);
        assert_eq!(idx.path(), Some(dir.path()));
    }

    #[test]
    fn open_nonexistent_returns_error() {
        let result = TantivyIndex::open(Path::new("/nonexistent/tantivy_index_xyz"));
        assert!(result.is_err());
    }

    /// Pins the ORACLE's behavior for stacked unary prefixes (`NOT -x`,
    /// `NOT NOT x`), which sit OUTSIDE the contract grammar's single-prefix
    /// fragment rule (`docs/contracts/quill-language-contract.md` §"fragment").
    /// The pinned Tantivy 0.26.1 parser is the normative behavior for such
    /// sequences; Quill's lowering must reproduce whatever this test observes
    /// (bd-251nt — found by the bd-bsjw structure-aware campaign).
    #[test]
    fn stacked_negation_prefixes_pin_oracle_semantics() {
        run_with_cx(|cx| async move {
            let docs = vec![
                IndexableDocument::new("doc-a", "alpha need"),
                IndexableDocument::new("doc-b", "alpha other"),
                IndexableDocument::new("doc-c", "need only"),
                IndexableDocument::new("doc-d", "plain filler"),
            ];
            let idx = TantivyIndex::in_memory().expect("create");
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let observe = |query: &str| {
                let mut ids = idx
                    .search_doc_ids(&cx, query, 10)
                    .expect("search")
                    .into_iter()
                    .map(|hit| hit.doc_id)
                    .collect::<Vec<_>>();
                ids.sort_unstable();
                ids
            };

            assert_eq!(
                observe("NOT -need"),
                vec!["doc-b".to_owned(), "doc-d".to_owned()],
                "oracle collapses NOT + '-' to a single exclusion of `need`"
            );
            assert_eq!(
                observe("NOT NOT need"),
                vec![
                    "doc-a".to_owned(),
                    "doc-b".to_owned(),
                    "doc-c".to_owned(),
                    "doc-d".to_owned(),
                ],
                "oracle treats NOT NOT as a lenient-parse match-all, NOT as \
                 logical double negation"
            );
            assert_eq!(
                observe("alpha NOT -need"),
                vec!["doc-b".to_owned()],
                "oracle: alpha-docs minus need-docs"
            );

            // In-GROUP stacked prefixes (bd-bsjw finding 4). `observe` here is
            // the SHIPPING surface (`search_doc_ids`), which bd-f20ye repaired,
            // so this now pins the repaired behaviour: a boost on the group no
            // longer changes membership.
            //
            // The original assertion recorded the opposite and explained it as
            // "the lenient fallback DROPS the negations". Measurement under
            // bd-f20ye falsified that account — nothing is dropped, the
            // `MustNot` survives parsing, and the lenient parser reports no
            // errors. The defect was that a boosted group re-nests its negation
            // as a positive alternative. The ORACLE-side pin of the unrepaired
            // behaviour, which is what this test's name is about, now lives in
            // `boosting_a_group_that_negates_changes_its_meaning_in_the_pinned_oracle`,
            // where it is observed through `oracle_observe_*` rather than
            // through a shipping method.
            assert_eq!(
                observe("(alpha NOT -need)"),
                vec!["doc-b".to_owned()],
                "unboosted group keeps the stacked-prefix collapse"
            );
            assert_eq!(
                observe("(alpha NOT -need)^2"),
                observe("(alpha NOT -need)"),
                "bd-f20ye: in the shipping path a boost must not change which \
                 documents match"
            );
            assert_eq!(
                observe("(alpha NOT need)^2"),
                observe("(alpha NOT need)"),
                "bd-f20ye: plain NOT under a group boost is repaired in the \
                 shipping path too, not just the stacked-prefix form"
            );
        });
    }

    /// Tantivy 0.26.1's `PhraseScorer` panics on an illegal post-termination
    /// seek when a NEGATED PHRASE rides beside a positive term — found by the
    /// bd-bsjw structure-aware campaign (`generic NOT "indexes Parser or
    /// minimal"`). Quill executes the same shape without incident. The
    /// shipping execution boundary converts the upstream panic into a typed
    /// degradation instead of aborting the host process, and the index stays
    /// fully usable afterwards (bd-nqeb4). When the pinned oracle is upgraded
    /// past the upstream defect, the typed-error assertion here fails —
    /// making the fix visible instead of silently shifting the target.
    #[test]
    fn oracle_negated_phrase_beside_term_degrades_typed_instead_of_panicking() {
        run_with_cx(|cx| async move {
            let docs = vec![
                IndexableDocument::new("doc-a", "alpha need only"),
                IndexableDocument::new("doc-b", "alpha other"),
                IndexableDocument::new("doc-c", "need only"),
            ];
            let idx = TantivyIndex::in_memory().expect("create");
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");
            // The phrase's terms exist but the SEQUENCE does not, so the
            // phrase docset terminates immediately — the precondition for the
            // upstream illegal seek.
            let error = idx
                .search_doc_ids(&cx, "alpha NOT \"only need\"", 10)
                .expect_err("upstream PhraseScorer defect must surface as a typed error");
            assert!(
                error
                    .to_string()
                    .contains("panicked during query execution"),
                "degradation must name the panic boundary: {error}"
            );

            // The availability property: the same index keeps serving ordinary
            // queries after the guarded failure.
            let survivors = idx
                .search_doc_ids(&cx, "alpha", 10)
                .expect("index must remain fully usable after a guarded panic");
            assert_eq!(survivors.len(), 2);
        });
    }

    #[test]
    fn reopen_on_disk_restores_fast_id_materialization() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().to_path_buf();
        run_with_cx(|cx| async move {
            let docs: Vec<IndexableDocument> = (0..20)
                .map(|i| {
                    IndexableDocument::new(
                        format!("doc-{i:03}"),
                        format!("alpha beta document number {i} searchable content"),
                    )
                })
                .collect();

            let ids_before = {
                let idx = TantivyIndex::create(&path).expect("create");
                idx.index_documents(&cx, &docs).await.expect("index");
                idx.commit(&cx).await.expect("commit");
                idx.search_doc_ids(&cx, "document", 20)
                    .expect("search")
                    .into_iter()
                    .map(|h| h.doc_id)
                    .collect::<Vec<_>>()
            }; // original index (and its writer lock) dropped here

            // Commit persisted the ordinal→doc_id sidecar.
            assert!(
                path.join("ord_table.json").exists(),
                "ord_table sidecar should be written on commit"
            );

            // Reopen: the sidecar restores the fast materialization path, and
            // results must be byte-identical to the pre-close ranking.
            let reopened = TantivyIndex::open(&path).expect("open");
            let ids_after = reopened
                .search_doc_ids(&cx, "document", 20)
                .expect("search")
                .into_iter()
                .map(|h| h.doc_id)
                .collect::<Vec<_>>();

            assert!(!ids_after.is_empty(), "reopened index should return hits");
            assert_eq!(
                ids_before, ids_after,
                "reopened index must return identical ranked doc_ids"
            );
        });
    }

    // ─── Indexing tests ─────────────────────────────────────────────────

    #[test]
    fn map_writer_lock_error_polled_after_completion_maps_to_subsystem_error() {
        let err = TantivyIndex::map_writer_lock_error(
            "tantivy.index",
            asupersync::sync::LockError::PolledAfterCompletion,
        );
        assert!(
            matches!(err, SearchError::SubsystemError { .. }),
            "expected subsystem error, got {err:?}"
        );
        if let SearchError::SubsystemError { source, .. } = err {
            assert!(
                source
                    .to_string()
                    .contains("writer mutex future reused after completion during tantivy.index")
            );
        }
    }

    #[test]
    fn index_single_document() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "Hello world");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");
            assert_eq!(idx.doc_count().expect("document count"), 1);
        });
    }

    #[test]
    fn index_batch_documents() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("batch index");
            idx.commit(&cx).await.expect("commit");
            assert_eq!(idx.doc_count().expect("document count"), 5);
        });
    }

    #[test]
    fn upsert_replaces_existing_document() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc_v1 = IndexableDocument::new("doc-1", "Version one content");
            idx.index_document(&cx, &doc_v1).await.expect("index v1");
            idx.commit(&cx).await.expect("commit v1");

            let doc_v2 = IndexableDocument::new("doc-1", "Version two content updated");
            idx.index_document(&cx, &doc_v2).await.expect("index v2");
            idx.commit(&cx).await.expect("commit v2");

            let results = idx.search(&cx, "updated", 10).await.expect("search");
            assert_eq!(results.len(), 1);
            assert_eq!(results[0].doc_id, "doc-1");
        });
    }

    // ─── Search tests ───────────────────────────────────────────────────

    #[cfg(feature = "bench-internals")]
    #[test]
    fn benchmark_schema_without_positions_uses_presence_only_postings() {
        let idx = TantivyIndex::in_memory_with_benchmark_config(50_000_000, 1, false)
            .expect("create position-free benchmark oracle");
        run_with_cx(|cx| async move {
            idx.index_documents(
                &cx,
                &[
                    IndexableDocument::new(
                        "repeated",
                        "term00001 term00001 term00001 term00001 term00001 qgpreflight",
                    ),
                    IndexableDocument::new("single", "term00001 qgpreflight"),
                    IndexableDocument::new("decoy", "term00002 qgpreflight"),
                ],
            )
            .await
            .expect("index position-free oracle fixture");
            idx.commit(&cx)
                .await
                .expect("commit position-free oracle fixture");

            let hits = idx
                .search(&cx, "term00001", 2)
                .await
                .expect("search position-free oracle fixture");
            let ids: Vec<_> = hits.iter().map(|hit| hit.doc_id.as_str()).collect();
            assert_eq!(ids, ["single", "repeated"]);
        });
    }

    #[cfg(feature = "bench-internals")]
    #[test]
    fn benchmark_writer_join_rearms_without_changing_searchable_state() {
        let idx = TantivyIndex::in_memory_with_benchmark_config(50_000_000, 1, true)
            .expect("create benchmark oracle");
        run_with_cx(|cx| async move {
            idx.index_document(
                &cx,
                &IndexableDocument::new("before-join", "lifecycle fence"),
            )
            .await
            .expect("index pre-fence document");
            idx.commit(&cx).await.expect("commit pre-fence document");

            let (idx, receipt) = idx
                .benchmark_join_workers_and_rearm(50_000_000, 1)
                .expect("join workers and rearm writer");
            assert!(receipt.searchable_segments_before > 0);
            assert!(receipt.searchable_segments_after > 0);
            assert!(receipt.writer_rearmed);
            assert_eq!(
                idx.search(&cx, "lifecycle", 10)
                    .await
                    .expect("search pre-fence document")
                    .len(),
                1
            );

            idx.index_document(
                &cx,
                &IndexableDocument::new("after-join", "writer remains usable"),
            )
            .await
            .expect("index post-fence document");
            idx.commit(&cx).await.expect("commit post-fence document");
            assert_eq!(
                idx.search(&cx, "writer", 10)
                    .await
                    .expect("search post-fence document")
                    .len(),
                1
            );
        });
    }

    #[cfg(feature = "bench-internals")]
    #[test]
    fn benchmark_writer_join_terminal_retains_searchable_reader_without_rearm() {
        let idx = TantivyIndex::in_memory_with_benchmark_config(50_000_000, 1, true)
            .expect("create benchmark oracle");
        run_with_cx(|cx| async move {
            idx.index_document(
                &cx,
                &IndexableDocument::new("terminal-join", "one shot bulk fixture"),
            )
            .await
            .expect("index terminal-fence document");
            idx.commit(&cx)
                .await
                .expect("commit terminal-fence document");

            let (reader, receipt) = idx
                .benchmark_join_workers_retaining_reader()
                .expect("join workers while retaining the terminal reader");
            assert!(receipt.searchable_segments_before > 0);
            assert!(receipt.searchable_segments_after > 0);
            assert!(!receipt.writer_rearmed);
            let tail_ids = reader
                .benchmark_search_exact_id("terminal-join")
                .expect("search the prepared terminal tail after worker join");
            assert_eq!(
                tail_ids.iter().map(DocId::as_str).collect::<Vec<_>>(),
                ["terminal-join"],
                "a counted segment is not accepted in place of a post-join tail search"
            );
            assert!(
                reader
                    .benchmark_search_exact_id("missing-terminal-tail")
                    .expect("search missing terminal tail after worker join")
                    .is_empty(),
                "planted negative: the retained reader must not fabricate tail visibility"
            );
        });
    }

    #[test]
    fn search_empty_query_returns_empty() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "", 10).await.expect("search");
            assert!(results.is_empty());

            let results = idx.search(&cx, "   ", 10).await.expect("search whitespace");
            assert!(results.is_empty());
        });
    }

    #[test]
    fn deferred_fusion_candidates_restore_exact_metadata() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let full = idx.search(&cx, "Rust", 10).await.expect("full search");
            let batch = idx
                .search_candidates(&cx, "Rust", 10)
                .await
                .expect("fusion candidates");

            // `is_deferred` is the split-trait replacement for the retired
            // `fusion_metadata_is_deferred` capability flag.
            assert!(batch.is_deferred());
            let (mut candidates, pin) = batch.into_parts();
            assert_eq!(candidates.len(), full.len());
            assert!(candidates.iter().all(|result| result.metadata.is_none()));
            for (candidate, expected) in candidates.iter().zip(&full) {
                assert_eq!(candidate.doc_id, expected.doc_id);
                assert_eq!(candidate.score.to_bits(), expected.score.to_bits());
                assert_eq!(
                    candidate.lexical_score.map(f32::to_bits),
                    expected.lexical_score.map(f32::to_bits)
                );
            }

            idx.hydrate_candidates(&cx, pin.as_ref(), &mut candidates)
                .await
                .expect("hydrate winners");
            for (candidate, expected) in candidates.iter().zip(&full) {
                assert_eq!(candidate.metadata, expected.metadata);
            }
        });
    }

    #[test]
    fn search_returns_relevant_results() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "Rust", 10).await.expect("search");
            assert!(!results.is_empty(), "should find documents mentioning Rust");
            let ids: Vec<&str> = results.iter().map(|r| r.doc_id.as_str()).collect();
            assert!(ids.contains(&"doc-1"), "should find doc-1");
            assert!(ids.contains(&"doc-3"), "should find doc-3");
        });
    }

    #[test]
    fn search_respects_limit() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx
                .search(&cx, "machine learning", 1)
                .await
                .expect("search");
            assert_eq!(results.len(), 1);
        });
    }

    #[test]
    fn search_results_have_lexical_source() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "Rust", 5).await.expect("search");
            for r in &results {
                assert_eq!(r.source, ScoreSource::Lexical);
                assert!(r.lexical_score.is_some());
                assert!(r.lexical_score.unwrap() > 0.0);
                assert!(r.fast_score.is_none());
                assert!(r.quality_score.is_none());
                assert!(r.rerank_score.is_none());
                assert!(r.explanation.is_none());
            }
        });
    }

    #[test]
    fn search_scores_are_descending() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "language", 10).await.expect("search");
            if results.len() > 1 {
                for pair in results.windows(2) {
                    assert!(
                        pair[0].score >= pair[1].score,
                        "scores should be descending: {} >= {}",
                        pair[0].score,
                        pair[1].score
                    );
                }
            }
        });
    }

    #[test]
    fn title_boost_affects_ranking() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc_a =
                IndexableDocument::new("doc-a", "consensus algorithm for distributed systems");
            let doc_b = IndexableDocument::new("doc-b", "some distributed system design")
                .with_title("Consensus Protocol");

            idx.index_document(&cx, &doc_a).await.expect("index a");
            idx.index_document(&cx, &doc_b).await.expect("index b");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "consensus", 2).await.expect("search");
            assert_eq!(results.len(), 2);
            assert_eq!(
                results[0].doc_id, "doc-b",
                "title-boosted document should rank first"
            );
        });
    }

    #[test]
    fn metadata_preserved_in_results() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "test content")
                .with_metadata("source", "unit_test")
                .with_metadata("lang", "en");

            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "test", 1).await.expect("search");
            assert_eq!(results.len(), 1);

            let meta = results[0].metadata.as_ref().expect("metadata present");
            assert_eq!(meta["source"], "unit_test");
            assert_eq!(meta["lang"], "en");
        });
    }

    #[test]
    fn no_results_for_unmatched_query() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "xylophone", 10).await.expect("search");
            assert!(results.is_empty(), "no documents mention xylophone");
        });
    }

    #[test]
    fn zero_limit_returns_empty_without_collector_panic() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            idx.index_document(&cx, &IndexableDocument::new("doc-1", "searchable text"))
                .await
                .expect("index");
            idx.commit(&cx).await.expect("commit");

            let parsed = idx.parse_query_lenient("searchable");
            let searcher = idx.reader.searcher();
            let counted = execute_query_with_offset(&searcher, &*parsed, 0, 0)
                .expect("counted zero-limit search");
            assert!(counted.hits.is_empty());
            assert_eq!(counted.total_count, 1);
            assert!(
                execute_top_k(&searcher, &*parsed, 0, 0)
                    .expect("count-free zero-limit search")
                    .is_empty()
            );

            assert!(
                idx.search(&cx, "searchable", 0)
                    .await
                    .expect("search")
                    .is_empty()
            );
            assert!(
                idx.search_doc_ids(&cx, "searchable", 0)
                    .expect("id search")
                    .is_empty()
            );
            assert!(
                idx.search_with_snippets(&cx, "searchable", 0, &SnippetConfig::default())
                    .expect("snippet search")
                    .is_empty()
            );
        });
    }

    #[cfg(feature = "tantivy-oracle")]
    #[test]
    fn oracle_tie_expansion_preserves_the_shipping_top_k() {
        let idx = TantivyIndex::in_memory_single_threaded_oracle().expect("create oracle");
        run_with_cx(|cx| async move {
            idx.writer
                .lock(&cx)
                .await
                .expect("lock writer")
                .set_merge_policy(Box::new(tantivy::merge_policy::NoMergePolicy));

            const DOC_COUNT: usize = 256;
            const SEGMENT_SIZE: usize = 32;
            const LIMIT: usize = 100;
            const QUERY: &str = "term00001 term00007 generated record";
            for segment_start in (0..DOC_COUNT).step_by(SEGMENT_SIZE) {
                let docs = (segment_start..segment_start + SEGMENT_SIZE)
                    .map(|ordinal| {
                        IndexableDocument::new(
                            format!("tie-{ordinal:03}"),
                            "term00001 term00007 generated record",
                        )
                    })
                    .collect::<Vec<_>>();
                idx.index_documents(&cx, &docs)
                    .await
                    .expect("index tie segment");
                idx.commit(&cx).await.expect("commit tie segment");
            }

            let native = idx
                .search_doc_ids(&cx, QUERY, LIMIT)
                .expect("shipping top-k");
            let observed = idx
                .oracle_observe_query(
                    &cx,
                    QUERY,
                    LIMIT,
                    DOC_COUNT,
                    &SnippetConfig {
                        max_chars: 0,
                        ..SnippetConfig::default()
                    },
                )
                .expect("expanded oracle observation");
            let native_rows = native
                .iter()
                .map(|hit| (hit.doc_id.as_str(), hit.bm25_score.to_bits()))
                .collect::<Vec<_>>();
            let observed_rows = observed
                .hits
                .iter()
                .map(|hit| (hit.doc_id.as_str(), hit.score_bits))
                .collect::<Vec<_>>();

            assert_eq!(
                observed_rows, native_rows,
                "expanded tie evidence must not redefine the shipping top-k"
            );
            assert_eq!(observed.total_count, DOC_COUNT);
            assert!(observed.cutoff_tie_complete);
            assert_eq!(observed.cutoff_tie_group.len(), DOC_COUNT);
        });
    }

    #[cfg(feature = "tantivy-oracle")]
    #[test]
    fn oracle_counted_pages_keep_exact_totals_and_absolute_ranks() {
        let idx = TantivyIndex::in_memory_single_threaded_oracle().expect("create oracle");
        run_with_cx(|cx| async move {
            let docs = (0..9)
                .map(|ordinal| {
                    IndexableDocument::new(
                        format!("doc-{ordinal:02}"),
                        format!("shared counted-page term document {ordinal}"),
                    )
                })
                .collect::<Vec<_>>();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            idx.index_document(
                &cx,
                &IndexableDocument::new("staged-doc", "shared counted-page term document staged"),
            )
            .await
            .expect("stage uncommitted document");

            let count_only = idx
                .oracle_observe_page(&cx, "counted-page", 0, 0)
                .expect("count-only page");
            let first = idx
                .oracle_observe_page(&cx, "counted-page", 3, 0)
                .expect("first page");
            let second = idx
                .oracle_observe_page(&cx, "counted-page", 3, 3)
                .expect("second page");
            let prefix = idx
                .oracle_observe_page(&cx, "counted-page", 6, 0)
                .expect("combined prefix");
            let past_end = idx
                .oracle_observe_page(&cx, "counted-page", 3, 100)
                .expect("past-end page");
            let ranked = idx
                .oracle_observe_query(&cx, "counted-page", 3, 16, &SnippetConfig::default())
                .expect("ranked observation");

            for page in [&count_only, &first, &second, &prefix, &past_end] {
                assert_eq!(page.total_count, 9, "exact Count must ignore k and offset");
                assert_eq!(
                    page.doc_count, 9,
                    "oracle document count must share the page searcher's generation"
                );
            }
            assert_eq!(ranked.total_count, 9);
            assert_eq!(
                ranked.doc_count, 9,
                "ranked oracle document count must ignore staged writer state"
            );
            assert!(
                count_only.hits.is_empty(),
                "limit zero must retain Count only"
            );
            assert!(past_end.hits.is_empty(), "past-end offset must be empty");
            assert_eq!(first.hits.len(), 3);
            assert_eq!(second.hits.len(), 3);
            assert_eq!(prefix.hits.len(), 6);

            for (page_rank, hit) in first.hits.iter().enumerate() {
                assert_eq!(hit.page_rank, page_rank);
                assert_eq!(hit.absolute_rank, page_rank);
            }
            for (page_rank, hit) in second.hits.iter().enumerate() {
                assert_eq!(hit.page_rank, page_rank);
                assert_eq!(hit.absolute_rank, page_rank + 3);
            }
            let combined = first
                .hits
                .iter()
                .chain(&second.hits)
                .map(|hit| (&hit.doc_id, hit.score_bits))
                .collect::<Vec<_>>();
            let prefix = prefix
                .hits
                .iter()
                .map(|hit| (&hit.doc_id, hit.score_bits))
                .collect::<Vec<_>>();
            assert_eq!(combined, prefix, "offset pages must compose exactly");
        });
    }

    #[test]
    fn tantivy_indexing_enforces_max_token_len_boundary() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let max = tantivy::tokenizer::MAX_TOKEN_LEN;
            let kept = "k".repeat(max);
            let dropped = "d".repeat(max + 1);
            idx.index_document(&cx, &IndexableDocument::new("kept", &kept))
                .await
                .expect("index boundary token");
            idx.index_document(&cx, &IndexableDocument::new("dropped", &dropped))
                .await
                .expect("index oversized token document");
            idx.commit(&cx).await.expect("commit");

            let searcher = idx.reader.searcher();
            let kept_query = TermQuery::new(
                Term::from_field_text(idx.fields.content, &kept),
                IndexRecordOption::WithFreqsAndPositions,
            );
            let dropped_query = TermQuery::new(
                Term::from_field_text(idx.fields.content, &dropped),
                IndexRecordOption::WithFreqsAndPositions,
            );
            assert_eq!(searcher.search(&kept_query, &Count).expect("search"), 1);
            assert_eq!(searcher.search(&dropped_query, &Count).expect("search"), 0);
        });
    }

    // ─── Delete tests ───────────────────────────────────────────────────

    #[test]
    fn delete_document_removes_from_index() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");
            assert_eq!(idx.doc_count().expect("document count"), 5);

            idx.delete_document(&cx, "doc-1").await.expect("delete");
            idx.commit(&cx).await.expect("commit after delete");

            let results = idx.search(&cx, "Rust systems", 10).await.expect("search");
            assert!(
                !results.iter().any(|r| r.doc_id == "doc-1"),
                "deleted document should not appear"
            );
        });
    }

    #[test]
    fn delete_document_publishes_to_public_lexical_readers_before_return() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let retained = IndexableDocument::new("retained", "delete visibility sentinel");
            let deleted = IndexableDocument::new("deleted", "delete visibility sentinel");
            LexicalWrite::index_documents(&idx, &cx, &[retained, deleted])
                .await
                .expect("index documents through the public write trait");
            LexicalWrite::commit(&idx, &cx)
                .await
                .expect("publish documents through the public write trait");

            assert_eq!(
                LexicalRead::doc_count(&idx).expect("count published documents"),
                2
            );

            idx.delete_document(&cx, "deleted")
                .await
                .expect("delete must publish before returning");

            let hits = LexicalRead::search(&idx, &cx, "delete visibility sentinel", 10)
                .await
                .expect("public lexical reader must see the committed deletion");
            assert_eq!(
                hits.iter()
                    .map(|hit| hit.doc_id.as_str())
                    .collect::<Vec<_>>(),
                vec!["retained"]
            );
            assert_eq!(
                LexicalRead::doc_count(&idx).expect("count refreshed readable generation"),
                1
            );
        });
    }

    // ─── Edge case tests ────────────────────────────────────────────────

    #[test]
    fn search_with_special_characters() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "Error code ERR-404: page not found");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "ERR-404", 10).await.expect("search");
            assert!(!results.is_empty(), "should find hyphenated term");
        });
    }

    #[test]
    fn case_insensitive_search() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "Rust Programming Language");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "rust", 10).await.expect("search lowercase");
            assert!(!results.is_empty());

            let results = idx.search(&cx, "RUST", 10).await.expect("search uppercase");
            assert!(!results.is_empty());
        });
    }

    #[test]
    fn empty_metadata_not_stored() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "no metadata here");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search(&cx, "metadata", 1).await.expect("search");
            assert_eq!(results.len(), 1);
            assert!(results[0].metadata.is_none());
        });
    }

    #[test]
    fn doc_count_accurate_after_operations() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            assert_eq!(idx.doc_count().expect("document count"), 0);

            let doc = IndexableDocument::new("doc-1", "first");
            idx.index_document(&cx, &doc).await.expect("index");
            assert_eq!(
                idx.doc_count().expect("pre-commit document count"),
                0,
                "the count must describe the current searcher, not staged writer state"
            );
            idx.commit(&cx).await.expect("commit");
            assert_eq!(idx.doc_count().expect("document count"), 1);

            let doc = IndexableDocument::new("doc-2", "second");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");
            assert_eq!(idx.doc_count().expect("document count"), 2);

            idx.delete_document(&cx, "doc-1").await.expect("delete");
            idx.commit(&cx).await.expect("commit delete");
            assert_eq!(idx.doc_count().expect("document count"), 1);
        });
    }

    // ─── Trait object safety ────────────────────────────────────────────

    #[test]
    fn tantivy_index_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<TantivyIndex>();
    }

    // ─── On-disk persistence tests ──────────────────────────────────────

    #[test]
    fn reopen_preserves_documents() {
        let dir = tempfile::tempdir().expect("tempdir");

        // Phase 1: Create and populate.
        {
            let idx = TantivyIndex::create(dir.path()).expect("create");
            asupersync::test_utils::run_test_with_cx(|cx| async move {
                let doc = IndexableDocument::new("doc-1", "persistent content");
                idx.index_document(&cx, &doc).await.expect("index");
                idx.commit(&cx).await.expect("commit");
            });
        }

        // Phase 2: Reopen and verify.
        {
            let idx = TantivyIndex::open(dir.path()).expect("open");
            asupersync::test_utils::run_test_with_cx(|cx| async move {
                let results = idx.search(&cx, "persistent", 10).await.expect("search");
                assert_eq!(results.len(), 1);
                assert_eq!(results[0].doc_id, "doc-1");
            });
        }
    }

    // ─── Query explanation tests (bd-3un.18) ─────────────────────────────

    #[test]
    fn classify_empty_query() {
        assert_eq!(classify_query(""), QueryExplanation::Empty);
        assert_eq!(classify_query("   "), QueryExplanation::Empty);
    }

    #[test]
    fn classify_simple_query() {
        assert_eq!(classify_query("rust"), QueryExplanation::Simple);
        assert_eq!(
            classify_query("  authentication  "),
            QueryExplanation::Simple
        );
    }

    #[test]
    fn classify_phrase_query() {
        assert_eq!(
            classify_query("\"error handling\""),
            QueryExplanation::Phrase
        );
        assert_eq!(classify_query("'single quotes'"), QueryExplanation::Phrase);
    }

    #[test]
    fn classify_boolean_query() {
        assert_eq!(classify_query("rust async"), QueryExplanation::Boolean);
        assert_eq!(
            classify_query("distributed consensus algorithm"),
            QueryExplanation::Boolean
        );
    }

    #[test]
    fn query_explanation_display() {
        assert_eq!(QueryExplanation::Empty.to_string(), "empty");
        assert_eq!(QueryExplanation::Simple.to_string(), "simple");
        assert_eq!(QueryExplanation::Phrase.to_string(), "phrase");
        assert_eq!(QueryExplanation::Boolean.to_string(), "boolean");
    }

    #[test]
    fn query_explanation_serde_roundtrip() {
        let json = serde_json::to_string(&QueryExplanation::Phrase).unwrap();
        let decoded: QueryExplanation = serde_json::from_str(&json).unwrap();
        assert_eq!(decoded, QueryExplanation::Phrase);
    }

    // ─── Snippet config tests ────────────────────────────────────────────

    #[test]
    fn snippet_config_default() {
        let config = SnippetConfig::default();
        assert_eq!(config.max_chars, DEFAULT_SNIPPET_MAX_CHARS);
        assert_eq!(config.highlight_prefix, "<b>");
        assert_eq!(config.highlight_postfix, "</b>");
    }

    #[test]
    fn snippet_unicode_window_uses_tantivy_byte_offsets() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            idx.index_document(&cx, &IndexableDocument::new("unicode", "éé alpha"))
                .await
                .expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig {
                max_chars: 6,
                ..SnippetConfig::default()
            };
            let results = idx
                .search_with_snippets(&cx, "éé", 1, &config)
                .expect("snippet search");
            assert_eq!(results.len(), 1);
            assert_eq!(results[0].snippet.as_deref(), Some("<b>éé</b>"));
        });
    }

    // ─── search_with_snippets tests (bd-3un.18) ─────────────────────────

    #[test]
    fn search_with_snippets_returns_results() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig::default();
            let results = idx
                .search_with_snippets(&cx, "Rust", 10, &config)
                .expect("search");

            assert!(!results.is_empty());
            assert_eq!(results[0].rank, 0);
            assert_eq!(results[0].query_type, QueryExplanation::Simple);
            assert!(results[0].bm25_score > 0.0);
        });
    }

    #[test]
    fn search_doc_ids_returns_ranked_identifiers() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx.search_doc_ids(&cx, "Rust", 10).expect("search");
            assert!(!results.is_empty());
            for (expected_rank, hit) in results.iter().enumerate() {
                assert_eq!(hit.rank, expected_rank, "rank should be sequential");
                assert!(!hit.doc_id.is_empty());
                assert!(hit.bm25_score.is_finite());
            }
        });
    }

    #[test]
    fn all_doc_ids_enumerates_only_live_committed_documents() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = [
                IndexableDocument::new("doc-c", "gamma"),
                IndexableDocument::new("doc-a", "alpha"),
                IndexableDocument::new("doc-b", "beta"),
            ];
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");
            idx.delete_document(&cx, "doc-b").await.expect("delete");
            idx.commit(&cx).await.expect("commit delete");

            assert_eq!(
                idx.all_doc_ids().expect("enumerate ids"),
                vec![DocId::from("doc-a"), DocId::from("doc-c")]
            );
            let exported = idx.all_documents().expect("export documents");
            assert_eq!(
                exported
                    .iter()
                    .map(|document| document.id.as_str())
                    .collect::<Vec<_>>(),
                vec!["doc-a", "doc-c"]
            );
            assert_eq!(exported[0].content, "alpha");
            assert_eq!(exported[1].content, "gamma");
        });
    }

    #[test]
    fn every_live_tantivy_search_surface_has_one_total_order_under_score_ties() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            idx.writer
                .lock(&cx)
                .await
                .expect("lock writer")
                .set_merge_policy(Box::new(tantivy::merge_policy::NoMergePolicy));

            const DOC_COUNT: usize = 120;
            const SEGMENT_SIZE: usize = 30;
            for segment_start in (0..DOC_COUNT).step_by(SEGMENT_SIZE) {
                let docs = (segment_start..segment_start + SEGMENT_SIZE)
                    .map(|ordinal| {
                        IndexableDocument::new(
                            format!("tie-{ordinal:03}"),
                            "alpha beta gamma delta shared exact score",
                        )
                        .with_title("alpha beta heading")
                        .with_metadata("ordinal", ordinal.to_string())
                    })
                    .collect::<Vec<_>>();
                idx.index_documents(&cx, &docs)
                    .await
                    .expect("index tie segment");
                idx.commit(&cx).await.expect("commit tie segment");
            }

            let query_shapes = [
                "alpha",
                "alpha beta",
                "alpha beta gamma",
                "\"alpha beta\"",
                "alpha AND beta",
                "title:alpha",
            ];
            for query in query_shapes {
                for limit in [0, 1, DOC_COUNT - 1, DOC_COUNT, DOC_COUNT + 1] {
                    assert_live_lexical_contract(&idx, &cx, query, limit, DOC_COUNT).await;
                }
            }
            assert_live_lexical_contract(&idx, &cx, "", 20, 0).await;
            assert_live_lexical_contract(&idx, &cx, "term-not-present", 20, 0).await;
        });
    }

    #[test]
    fn harvested_natural_language_query_keeps_count_off_the_public_candidate_path() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let documents = shared_full120_docs();
            for batch in documents.chunks(5) {
                idx.index_documents(&cx, batch)
                    .await
                    .expect("index Full120 campaign batch");
            }
            idx.commit(&cx).await.expect("commit Full120");

            const QUERY: &str = "how to sear a steak properly";
            const LIMIT: usize = 20;
            let full = idx.search(&cx, QUERY, LIMIT).await.expect("full search");
            reset_collector_invocations();
            let ids = idx
                .search_doc_ids(&cx, QUERY, LIMIT)
                .expect("count-free ID search");
            let candidates = idx
                .search_candidates(&cx, QUERY, LIMIT)
                .await
                .expect("fusion candidates")
                .into_parts()
                .0;
            assert_eq!(
                collector_invocations(),
                (0, 2),
                "both public candidate surfaces must construct TopDocs-only and never Count"
            );
            let counted = idx
                .search_doc_ids_counted(&cx, QUERY, LIMIT)
                .expect("counted benchmark control");
            assert_eq!(
                collector_invocations(),
                (1, 2),
                "only the explicit benchmark control may construct (TopDocs, Count)"
            );

            assert_eq!(full.len(), LIMIT);
            assert_eq!(ids.len(), full.len());
            assert_eq!(candidates.len(), full.len());
            assert_eq!(counted.len(), LIMIT);
            for (rank, ((expected, id_hit), candidate)) in
                full.iter().zip(&ids).zip(&candidates).enumerate()
            {
                let context = format!("harvested-14 rank={rank}");
                assert_eq!(id_hit.rank, rank, "{context}");
                assert_eq!(id_hit.doc_id, expected.doc_id, "{context}");
                assert_eq!(
                    id_hit.bm25_score.to_bits(),
                    expected.score.to_bits(),
                    "{context}"
                );
                assert_eq!(candidate.doc_id, expected.doc_id, "{context}");
                assert_eq!(
                    candidate.score.to_bits(),
                    expected.score.to_bits(),
                    "{context}"
                );
            }

            let parsed = idx.parse_query_lenient(QUERY);
            let counted_page =
                execute_query_with_offset(&idx.reader.searcher(), &*parsed, LIMIT, 0)
                    .expect("exact counted API");
            assert_eq!(
                counted_page.total_count, 110,
                "the pinned Full120 harvested-14 exact count drifted"
            );
        });
    }

    #[test]
    fn search_with_snippets_empty_query() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig::default();
            let results = idx
                .search_with_snippets(&cx, "", 10, &config)
                .expect("search");
            assert!(results.is_empty());
        });
    }

    #[test]
    fn search_with_snippets_has_highlighted_content() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new(
                "doc-1",
                "The Rust programming language is fast and memory-safe",
            );
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig::default();
            let results = idx
                .search_with_snippets(&cx, "Rust", 1, &config)
                .expect("search");

            assert_eq!(results.len(), 1);
            if let Some(snippet) = &results[0].snippet {
                assert!(
                    snippet.contains("<b>"),
                    "snippet should have highlight tags: {snippet}"
                );
            }
        });
    }

    #[test]
    fn search_with_snippets_custom_highlight_tags() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "Rust is awesome for systems programming");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig {
                max_chars: 200,
                highlight_prefix: "<em>".to_owned(),
                highlight_postfix: "</em>".to_owned(),
            };
            let results = idx
                .search_with_snippets(&cx, "Rust", 1, &config)
                .expect("search");

            assert_eq!(results.len(), 1);
            if let Some(snippet) = &results[0].snippet {
                assert!(
                    snippet.contains("<em>"),
                    "snippet should use custom highlight: {snippet}"
                );
                assert!(
                    !snippet.contains("<b>"),
                    "should NOT use default highlight: {snippet}"
                );
            }
        });
    }

    #[test]
    fn search_with_snippets_ranks_are_sequential() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig::default();
            let results = idx
                .search_with_snippets(&cx, "language", 10, &config)
                .expect("search");

            for (i, hit) in results.iter().enumerate() {
                assert_eq!(hit.rank, i, "rank should be sequential");
            }
        });
    }

    #[test]
    fn search_with_snippets_metadata_preserved() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "metadata test content")
                .with_metadata("key", "value");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig::default();
            let results = idx
                .search_with_snippets(&cx, "metadata", 1, &config)
                .expect("search");

            assert_eq!(results.len(), 1);
            let meta = results[0].metadata.as_ref().expect("metadata");
            assert_eq!(meta["key"], "value");
        });
    }

    #[test]
    fn search_with_snippets_phrase_query() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "error handling in Rust is explicit");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig::default();
            let results = idx
                .search_with_snippets(&cx, "\"error handling\"", 10, &config)
                .expect("search");

            assert_eq!(results.len(), 1);
            assert_eq!(results[0].query_type, QueryExplanation::Phrase);
        });
    }

    #[test]
    fn search_with_snippets_boolean_query() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let docs = sample_docs();
            idx.index_documents(&cx, &docs).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let config = SnippetConfig::default();
            let results = idx
                .search_with_snippets(&cx, "machine learning", 10, &config)
                .expect("search");

            assert!(!results.is_empty());
            assert_eq!(results[0].query_type, QueryExplanation::Boolean);
        });
    }

    // ─── Query truncation tests ──────────────────────────────────────────

    #[test]
    fn truncate_query_short_passthrough() {
        let q = "hello world";
        assert_eq!(TantivyIndex::truncate_query(q), q);
    }

    #[test]
    fn truncate_query_at_limit() {
        let q = "a".repeat(MAX_QUERY_LENGTH);
        assert_eq!(TantivyIndex::truncate_query(&q), q.as_str());
    }

    #[test]
    fn truncate_query_over_limit() {
        let q = "a".repeat(MAX_QUERY_LENGTH + 100);
        let truncated = TantivyIndex::truncate_query(&q);
        assert_eq!(truncated.len(), MAX_QUERY_LENGTH);
        assert_eq!(truncated.chars().count(), MAX_QUERY_LENGTH);
    }

    #[test]
    fn truncate_query_counts_multibyte_characters() {
        let over = "\u{00E9}".repeat(MAX_QUERY_LENGTH + 3);
        let truncated = TantivyIndex::truncate_query(&over);
        assert!(truncated.is_char_boundary(truncated.len()));
        assert_eq!(truncated.chars().count(), MAX_QUERY_LENGTH);
        assert_eq!(truncated.len(), MAX_QUERY_LENGTH * '\u{00E9}'.len_utf8());
    }

    #[test]
    fn truncate_query_preserves_multibyte_query_within_character_limit() {
        let query = "\u{00E9}".repeat(MAX_QUERY_LENGTH / 2 + 1);
        assert!(query.len() > MAX_QUERY_LENGTH);
        assert_eq!(TantivyIndex::truncate_query(&query), query);
    }

    #[test]
    fn overlong_query_still_searches() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "findable content");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            // Build a query with the search term followed by lots of padding.
            let mut long_query = "findable ".to_owned();
            long_query.push_str(&"padding ".repeat(2000));
            assert!(long_query.len() > MAX_QUERY_LENGTH);

            let results = idx
                .search(&cx, &long_query, 10)
                .await
                .expect("should not error");
            assert!(
                !results.is_empty(),
                "truncated query should still find docs"
            );
        });
    }

    // ─── LexicalHit serde test ───────────────────────────────────────────

    #[test]
    fn lexical_hit_serde_roundtrip() {
        let hit = LexicalHit {
            doc_id: "doc-42".into(),
            bm25_score: 2.75,
            rank: 0,
            snippet: Some("<b>Rust</b> is great".into()),
            query_type: QueryExplanation::Simple,
            metadata: Some(serde_json::json!({"lang": "en"})),
        };
        let json = serde_json::to_string(&hit).expect("serialize");
        let roundtripped: LexicalHit = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(roundtripped.doc_id, "doc-42");
        assert!((roundtripped.bm25_score - 2.75).abs() < f32::EPSILON);
        assert_eq!(roundtripped.rank, 0);
        assert_eq!(
            roundtripped.snippet.as_deref(),
            Some("<b>Rust</b> is great")
        );
        assert_eq!(roundtripped.query_type, QueryExplanation::Simple);
    }

    // ─── Special character robustness tests ──────────────────────────────

    #[test]
    fn search_with_special_chars_no_crash() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "some content");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            // These queries contain special characters that could trip up a parser.
            // In lenient mode, Tantivy should handle them gracefully.
            for query in &["@user", "#hashtag", "foo:bar", "a+b", "hello!"] {
                let result = idx.search(&cx, query, 10).await;
                assert!(result.is_ok(), "query '{query}' should not error");
            }
        });
    }

    #[test]
    fn search_no_results_returns_empty_not_error() {
        let idx = TantivyIndex::in_memory().expect("create");
        run_with_cx(|cx| async move {
            let doc = IndexableDocument::new("doc-1", "hello world");
            idx.index_document(&cx, &doc).await.expect("index");
            idx.commit(&cx).await.expect("commit");

            let results = idx
                .search(&cx, "nonexistentterm", 10)
                .await
                .expect("no error");
            assert!(results.is_empty());
        });
    }

    /// Tantivy candidates hydrate from the generation that scored them.
    ///
    /// The same contract Quill already proves, now that `TantivyIndex`
    /// overrides `search_candidates`/`hydrate_candidates` instead of falling
    /// back to the eager default (`bd-8nqz.1`). Scores come from generation
    /// N; a commit publishes N+1; the retained batch must still hydrate N's
    /// metadata while a fresh search observes N+1.
    #[test]
    fn tantivy_candidates_hydrate_from_the_scoring_generation() {
        use frankensearch_core::traits::LexicalRead;

        run_with_cx(|cx| async move {
            let dir = tempfile::tempdir().expect("tempdir");
            let idx = TantivyIndex::create(dir.path()).expect("create");

            let v1 =
                IndexableDocument::new("doc-a", "alpha pinned content").with_metadata("rev", "v1");
            LexicalWrite::index_document(&idx, &cx, &v1)
                .await
                .expect("index N");
            LexicalWrite::commit(&idx, &cx).await.expect("publish N");

            // Score on N. Candidates defer metadata and carry the searcher pin.
            let batch = LexicalRead::search_candidates(&idx, &cx, "pinned", 10)
                .await
                .expect("candidates on N");
            assert!(
                batch.is_deferred(),
                "Tantivy candidates must carry a searcher pin, not fall back to eager"
            );
            assert_eq!(batch.results().len(), 1);
            assert!(
                batch.results()[0].metadata.is_none(),
                "deferred candidates skip metadata until hydration"
            );

            // Publish N+1 with different metadata for the same document.
            let v2 =
                IndexableDocument::new("doc-a", "alpha pinned content").with_metadata("rev", "v2");
            LexicalWrite::index_document(&idx, &cx, &v2)
                .await
                .expect("upsert N+1");
            LexicalWrite::commit(&idx, &cx).await.expect("publish N+1");

            let rev_of = |result: &ScoredResult| -> Option<String> {
                result.metadata.as_ref().and_then(|metadata| {
                    metadata
                        .get("rev")
                        .and_then(|value| value.as_str())
                        .map(str::to_owned)
                })
            };

            // A fresh search observes N+1.
            let fresh = LexicalRead::search(&idx, &cx, "pinned", 10)
                .await
                .expect("fresh search");
            assert_eq!(rev_of(&fresh[0]).as_deref(), Some("v2"));

            // The retained batch hydrates from its PINNED generation N.
            let (mut winners, context) = batch.into_parts();
            LexicalRead::hydrate_candidates(&idx, &cx, context.as_ref(), &mut winners)
                .await
                .expect("pinned hydration");
            assert_eq!(
                rev_of(&winners[0]).as_deref(),
                Some("v1"),
                "hydration must read the scoring searcher, not the newest generation"
            );
        });
    }

    /// A foreign or missing context is refused rather than silently reading
    /// the current generation.
    #[test]
    fn tantivy_hydration_rejects_a_foreign_or_absent_context() {
        use frankensearch_core::traits::{LexicalHydrationContext, LexicalRead};

        run_with_cx(|cx| async move {
            let dir = tempfile::tempdir().expect("tempdir");
            let idx = TantivyIndex::create(dir.path()).expect("create");
            let doc = IndexableDocument::new("doc-a", "alpha").with_metadata("rev", "v1");
            LexicalWrite::index_document(&idx, &cx, &doc)
                .await
                .expect("index");
            LexicalWrite::commit(&idx, &cx).await.expect("commit");

            let mut winners = vec![ScoredResult {
                doc_id: DocId::from("doc-a"),
                score: 1.0,
                source: ScoreSource::Lexical,
                index: None,
                fast_score: None,
                quality_score: None,
                lexical_score: Some(1.0),
                rerank_score: None,
                explanation: None,
                metadata: None,
            }];

            let absent = LexicalRead::hydrate_candidates(&idx, &cx, None, &mut winners)
                .await
                .expect_err("deferred winners without their pin must not hydrate silently");
            assert!(matches!(
                absent,
                SearchError::SubsystemError {
                    subsystem: "tantivy.hydration",
                    ..
                }
            ));

            let foreign = LexicalHydrationContext::new("quill", Box::new(7_u64));
            let error = LexicalRead::hydrate_candidates(&idx, &cx, Some(&foreign), &mut winners)
                .await
                .expect_err("a foreign pin must be refused");
            match error {
                SearchError::SubsystemError { subsystem, source } => {
                    assert_eq!(subsystem, "tantivy.hydration");
                    assert!(
                        source.to_string().contains("quill"),
                        "the rejection must name the foreign backend"
                    );
                }
                other => panic!("expected a typed subsystem error, got {other:?}"),
            }
        });
    }
}

#[cfg(all(test, feature = "bench-internals"))]
mod benchmark_writer_mode_tests {
    use super::{
        BenchmarkMaterializedWidth, BenchmarkWidthUnobservableReason, BenchmarkWriterMode,
        TOKENIZER_NAME, TantivyIndex, positions_from_live_schema,
    };
    use frankensearch_core::SearchError;
    use frankensearch_core::traits::{LexicalRead, LexicalWrite};
    use frankensearch_core::types::IndexableDocument;

    /// Tantivy requires a per-writer floor, so an eight-thread pool needs at
    /// least `8 * 15_000_000` bytes. Ask for that plus headroom, or the widest
    /// case silently exercises a narrower pool than it claims.
    const HEAP: usize = 8 * 15_000_000 + 64 * 1024 * 1024;

    #[test]
    fn shipping_auto_uses_the_pinned_selection_path_and_reports_no_width() {
        let mut index = TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, true)
            .expect("shipping-auto writer");
        let attestation = index
            .take_benchmark_writer_attestation()
            .expect("successful benchmark writer mints one live attestation");
        let receipt = index
            .benchmark_writer_receipt()
            .cloned()
            .expect("shipping-auto stamps a receipt");

        assert_eq!(attestation.receipt(), &receipt);
        assert!(
            index.take_benchmark_writer_attestation().is_none(),
            "the live attestation is a one-shot capability"
        );
        assert_eq!(receipt.mode, BenchmarkWriterMode::ShippingAuto);
        assert_eq!(
            receipt.materialized_width,
            BenchmarkMaterializedWidth::Unobservable {
                reason: BenchmarkWidthUnobservableReason::EngineSelectedWidthNotExposed,
            }
        );
        // The unknown must stay unknown everywhere it is read.
        assert_eq!(receipt.materialized_width.authenticated(), None);
        assert_eq!(index.benchmark_materialized_writer_threads(), None);
        assert_eq!(receipt.writer_heap_bytes, HEAP);
        assert!(!receipt.writer_rearmed);
    }

    #[test]
    fn identical_fixed_constructors_mint_distinct_live_attestations() {
        let mut first = TantivyIndex::in_memory_with_benchmark_config(HEAP, 4, true)
            .expect("first fixed writer");
        let mut second = TantivyIndex::in_memory_with_benchmark_config(HEAP, 4, true)
            .expect("second fixed writer");
        let first_attestation = first
            .take_benchmark_writer_attestation()
            .expect("first live attestation");
        let second_attestation = second
            .take_benchmark_writer_attestation()
            .expect("second live attestation");

        assert_ne!(
            first_attestation.construction_id(),
            second_attestation.construction_id(),
            "identical benchmark requests still construct separate live writers"
        );
        assert_eq!(
            first_attestation.receipt(),
            first.benchmark_writer_receipt().expect("first receipt")
        );
        assert_eq!(
            second_attestation.receipt(),
            second.benchmark_writer_receipt().expect("second receipt")
        );
        assert_eq!(
            first_attestation.receipt(),
            second_attestation.receipt(),
            "the diagnostic receipt may agree for identical real constructors"
        );
        assert_eq!(
            first_attestation.receipt().mode,
            BenchmarkWriterMode::Fixed { threads: 4 }
        );
        assert_eq!(
            first_attestation.receipt().materialized_width,
            BenchmarkMaterializedWidth::Authenticated(4)
        );
    }

    #[test]
    fn fixed_width_is_authenticated_exactly() {
        for threads in [1usize, 3, 8] {
            let index = TantivyIndex::in_memory_with_benchmark_config(HEAP, threads, true)
                .expect("fixed writer");
            let receipt = index.benchmark_writer_receipt().expect("fixed receipt");

            assert_eq!(receipt.mode, BenchmarkWriterMode::Fixed { threads });
            assert_eq!(
                receipt.materialized_width,
                BenchmarkMaterializedWidth::Authenticated(threads)
            );
            assert_eq!(receipt.materialized_width.authenticated(), Some(threads));
            assert_eq!(index.benchmark_materialized_writer_threads(), Some(threads));
        }
    }

    #[test]
    fn invalid_width_and_insufficient_heap_fail_closed() {
        assert!(matches!(
            TantivyIndex::in_memory_with_benchmark_config(HEAP, 0, true),
            Err(SearchError::InvalidConfig { .. })
        ));
        // A heap below Tantivy's per-writer floor must surface its typed
        // construction error, never a silently downgraded pool.
        assert!(TantivyIndex::in_memory_with_benchmark_config(1, 4, true).is_err());
        assert!(TantivyIndex::in_memory_with_shipping_auto_writer(1, true).is_err());
    }

    #[test]
    fn shipping_and_fixed_receipts_are_distinguishable() {
        let auto = TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, true)
            .expect("shipping-auto writer");
        let fixed =
            TantivyIndex::in_memory_with_benchmark_config(HEAP, 4, true).expect("fixed writer");
        let auto = auto
            .benchmark_writer_receipt()
            .expect("auto receipt")
            .clone();
        let fixed = fixed.benchmark_writer_receipt().expect("fixed receipt");

        assert_ne!(
            &auto, fixed,
            "the two modes must not produce equal receipts"
        );
        assert_ne!(auto.mode, fixed.mode);
        assert_ne!(auto.materialized_width, fixed.materialized_width);
        // Identity that is genuinely shared must still match, or the receipt
        // would be distinguishing on incidental noise instead of on mode.
        assert_eq!(auto.schema_fields, fixed.schema_fields);
        assert_eq!(auto.tokenizer_name, fixed.tokenizer_name);
    }

    #[test]
    fn schema_and_oracle_identity_track_the_index_that_was_built() {
        let with_positions_index = TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, true)
            .expect("positions-on writer");
        let without_positions_index =
            TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, false)
                .expect("positions-off writer");
        let with_positions = with_positions_index
            .benchmark_writer_receipt()
            .expect("receipt")
            .clone();
        let without_positions = without_positions_index
            .benchmark_writer_receipt()
            .expect("receipt");

        assert!(with_positions.positions);
        assert!(!without_positions.positions);
        assert_ne!(
            &with_positions, without_positions,
            "a positions mutation must change the receipt"
        );
        assert_eq!(with_positions.tokenizer_name, TOKENIZER_NAME);
        // The receipt's positions value must be the live indexing option, not a
        // remembered argument, so read the schema back independently.
        assert_eq!(
            positions_from_live_schema(&with_positions_index.index.schema()),
            Some(true)
        );
        assert_eq!(
            positions_from_live_schema(&without_positions_index.index.schema()),
            Some(false)
        );
        // Pin the exact field set this crate's schema builds, so the receipt is
        // read from the live schema rather than reporting a plausible shape.
        // A field added, renamed, or dropped must fail here.
        assert_eq!(
            with_positions.schema_fields,
            vec![
                "id".to_owned(),
                "content".to_owned(),
                "title".to_owned(),
                "metadata_json".to_owned(),
                "ord".to_owned(),
            ],
            "schema identity must match the fields build_schema_with_positions creates"
        );
        assert_eq!(
            without_positions.schema_fields, with_positions.schema_fields,
            "positions is an index option, not a field, so the field set must not move"
        );
    }

    #[test]
    fn a_fresh_writer_never_claims_a_rearm() {
        for index in [
            TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, true).expect("auto"),
            TantivyIndex::in_memory_with_benchmark_config(HEAP, 2, true).expect("fixed"),
        ] {
            assert!(
                !index
                    .benchmark_writer_receipt()
                    .expect("receipt")
                    .writer_rearmed,
                "a freshly constructed writer must not report a rearm"
            );
        }
    }

    #[test]
    fn the_construction_receipt_flips_after_a_rearm() {
        let mut index =
            TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, true).expect("auto writer");
        let original_attestation = index
            .take_benchmark_writer_attestation()
            .expect("original live attestation");
        assert_eq!(
            index.benchmark_writer_receipt().expect("receipt").mode,
            BenchmarkWriterMode::ShippingAuto
        );

        let (mut rearmed, _join) = index
            .benchmark_join_workers_and_rearm(HEAP, 2)
            .expect("join and rearm");
        let rearmed_attestation = rearmed
            .take_benchmark_writer_attestation()
            .expect("replacement writer mints a fresh live attestation");
        let receipt = rearmed.benchmark_writer_receipt().expect("rearm receipt");

        // A rearm replaces the writer, so the construction receipt must stop
        // describing the original one: the mode moves to the fixed constructor
        // the rearm actually called, and the rearm flag is set.
        assert!(receipt.writer_rearmed);
        assert_eq!(receipt.mode, BenchmarkWriterMode::Fixed { threads: 2 });
        assert_eq!(
            receipt.materialized_width,
            BenchmarkMaterializedWidth::Authenticated(2)
        );
        assert_eq!(rearmed_attestation.receipt(), receipt);
        assert_ne!(
            original_attestation.construction_id(),
            rearmed_attestation.construction_id(),
            "rearming replaces the writer and must mint a new live identity"
        );
        // The receipt states the rearm's intent; this states the call it made.
        // Carrying the old writer's observation forward instead would leave a
        // rearmed index reporting Auto, which this rejects.
        assert_eq!(
            rearmed.observed_writer_call,
            super::WriterCall::Fixed(2),
            "the rearm must observe its own writer_with_num_threads call"
        );
    }

    #[test]
    fn the_receipt_seed_cannot_drift_from_the_constructor_branch() {
        // Discriminating observer: the two factories differ only in which
        // Tantivy constructor they reach, and the receipt is seeded inside that
        // branch. If the seed were passed in beside the call instead, these two
        // could report the same mode while calling different constructors.
        let factories: [(&str, fn() -> TantivyIndex, BenchmarkWriterMode); 2] = [
            (
                "Index::writer",
                || TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, true).expect("auto"),
                BenchmarkWriterMode::ShippingAuto,
            ),
            (
                "Index::writer_with_num_threads",
                || TantivyIndex::in_memory_with_benchmark_config(HEAP, 8, true).expect("fixed"),
                BenchmarkWriterMode::Fixed { threads: 8 },
            ),
        ];
        for (constructor, factory, expected_mode) in factories {
            let index = factory();
            let receipt = index.benchmark_writer_receipt().expect("receipt");
            assert_eq!(
                receipt.mode, expected_mode,
                "receipt mode must name the constructor that ran: {constructor}"
            );
            assert_eq!(
                receipt.writer_heap_bytes, HEAP,
                "heap must come from the same branch as the mode: {constructor}"
            );
            assert_eq!(
                receipt.materialized_width.authenticated(),
                match expected_mode {
                    BenchmarkWriterMode::ShippingAuto => None,
                    BenchmarkWriterMode::Fixed { threads } => Some(threads),
                },
                "width authentication must follow the branch: {constructor}"
            );
        }
    }

    /// Heap that is exactly one thread's floor.
    ///
    /// This is the label-independent discriminator. `writer_with_num_threads`
    /// rejects a width whose per-thread share falls under Tantivy's floor,
    /// while `Index::writer` *clamps* the width instead of failing. So at this
    /// budget the two constructors disagree observably: a fixed eight-wide
    /// construction must fail and a shipping-auto construction must succeed.
    const ONE_THREAD_FLOOR_HEAP: usize = 15_000_000;

    #[test]
    fn the_constructor_is_discriminated_by_behaviour_not_by_its_label() {
        // If ShippingAuto secretly called writer_with_num_threads(8, ..) this
        // would fail; if Fixed{8} secretly called Index::writer it would
        // succeed. Neither can be rescued by a matching label.
        let auto = TantivyIndex::in_memory_with_shipping_auto_writer(ONE_THREAD_FLOOR_HEAP, true)
            .expect("Index::writer clamps the width instead of rejecting this budget");
        assert_eq!(
            auto.benchmark_writer_receipt().expect("receipt").mode,
            BenchmarkWriterMode::ShippingAuto
        );

        assert!(
            TantivyIndex::in_memory_with_benchmark_config(ONE_THREAD_FLOOR_HEAP, 8, true).is_err(),
            "writer_with_num_threads must reject eight writers sharing one writer's floor"
        );
    }

    #[test]
    fn the_rearm_constructor_is_discriminated_the_same_way() {
        let index = TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, true)
            .expect("auto writer at a comfortable budget");
        // The rearm must reconstruct through writer_with_num_threads, so it
        // inherits that constructor's floor rejection. Succeeding here would
        // prove it had fallen back to Index::writer.
        assert!(
            index
                .benchmark_join_workers_and_rearm(ONE_THREAD_FLOOR_HEAP, 8)
                .is_err(),
            "rearm must reconstruct at a pinned width, not through the auto path"
        );
    }

    #[test]
    fn ordinary_constructors_claim_no_benchmark_receipt() {
        // Only an explicit benchmark plan may produce a receipt. An ordinary
        // index that happens to reach the same Tantivy call must not be able to
        // present itself as a screened candidate.
        let mut ordinary = TantivyIndex::in_memory().expect("ordinary in-memory index");
        assert!(ordinary.benchmark_writer_receipt().is_none());
        assert!(ordinary.benchmark_materialized_writer_threads().is_none());
        assert!(
            ordinary.take_benchmark_writer_attestation().is_none(),
            "ordinary construction must not mint a live benchmark capability"
        );

        // The pinned oracle only exists behind `tantivy-oracle`; this module is
        // gated on `bench-internals` alone, so its negative coverage has to be
        // conditional or `bench-internals` by itself stops compiling.
        #[cfg(feature = "tantivy-oracle")]
        {
            let mut oracle =
                TantivyIndex::in_memory_single_threaded_oracle().expect("single-threaded oracle");
            assert!(
                oracle.benchmark_writer_receipt().is_none(),
                "pinning a width is not the same as claiming a screening receipt"
            );
            assert!(
                oracle.benchmark_materialized_writer_threads().is_none(),
                "an unscreened oracle authenticates no width to a screening consumer"
            );
            assert!(
                oracle.take_benchmark_writer_attestation().is_none(),
                "an ordinary pinned oracle must not mint a live benchmark capability"
            );
        }
    }

    #[cfg(feature = "tantivy-oracle")]
    #[test]
    fn the_ordinary_pinned_oracle_invokes_the_fixed_constructor() {
        use super::WriterCall;

        // Asserting "no receipt" here proves nothing: reverting this oracle to
        // WriterPlan::Shipping keeps the receipt absent while silently moving
        // the writer onto Tantivy's auto selection, which is exactly the
        // regression this test exists to catch. So observe the call itself,
        // recorded by the helper that performed it, on this instance — not a
        // global counter that parallel tests would race.
        let oracle =
            TantivyIndex::in_memory_single_threaded_oracle().expect("single-threaded oracle");

        assert_eq!(
            oracle.observed_writer_call,
            WriterCall::Fixed(1),
            "the oracle must invoke writer_with_num_threads(1, ..), not the auto path"
        );
        assert!(
            oracle.benchmark_writer_receipt().is_none(),
            "invoking the fixed constructor still claims no screening identity"
        );
    }

    #[test]
    fn the_observed_call_tracks_the_constructor_each_plan_reaches() {
        use super::WriterCall;

        // The same observer over the benchmark plans, so a plan that reached
        // the wrong Tantivy entry point cannot hide behind a matching label.
        let auto =
            TantivyIndex::in_memory_with_shipping_auto_writer(HEAP, true).expect("auto writer");
        assert_eq!(auto.observed_writer_call, WriterCall::Auto);

        let fixed =
            TantivyIndex::in_memory_with_benchmark_config(HEAP, 4, true).expect("fixed writer");
        assert_eq!(fixed.observed_writer_call, WriterCall::Fixed(4));

        let ordinary = TantivyIndex::in_memory().expect("ordinary in-memory index");
        assert_eq!(ordinary.observed_writer_call, WriterCall::Auto);
    }

    #[test]
    fn a_reopened_index_rejects_a_disagreeing_positions_claim() {
        let directory = tempfile::tempdir().expect("temporary index directory");
        let path = directory.path().join("oracle");
        TantivyIndex::create_with_benchmark_config(&path, HEAP, 2, true)
            .expect("create with positions");

        // Reopening while claiming the opposite positions setting is an
        // assertion about bytes that already exist, and must fail closed rather
        // than writing a false value into every downstream receipt.
        assert!(matches!(
            TantivyIndex::open_with_benchmark_config(&path, HEAP, 2, false),
            Err(SearchError::InvalidConfig { .. })
        ));

        let reopened = TantivyIndex::open_with_benchmark_config(&path, HEAP, 2, true)
            .expect("reopen with the true positions setting");
        assert!(
            reopened
                .benchmark_writer_receipt()
                .expect("receipt")
                .positions,
            "the reopened receipt must carry the live schema's positions option"
        );
    }

    #[test]
    fn a_reopened_positions_off_index_rejects_the_mirrored_claim() {
        // Mirror of the case above: the rejection must be symmetric, or a
        // positions-off index could be reopened while claiming positions-on and
        // carry that false claim into every downstream receipt.
        let directory = tempfile::tempdir().expect("temporary index directory");
        let path = directory.path().join("oracle");
        TantivyIndex::create_with_benchmark_config(&path, HEAP, 2, false)
            .expect("create without positions");

        assert!(matches!(
            TantivyIndex::open_with_benchmark_config(&path, HEAP, 2, true),
            Err(SearchError::InvalidConfig { .. })
        ));

        let reopened = TantivyIndex::open_with_benchmark_config(&path, HEAP, 2, false)
            .expect("reopen with the true positions setting");
        assert!(
            !reopened
                .benchmark_writer_receipt()
                .expect("receipt")
                .positions,
            "the reopened receipt must carry the live schema's positions option"
        );
    }

    #[test]
    fn qg4_directory_sync_requires_fresh_no_merge_preparation() {
        let directory = tempfile::tempdir().expect("temporary index directory");
        let path = directory.path().join("qg4");
        asupersync::test_utils::run_test_with_cx(|cx| async move {
            let index = TantivyIndex::create_with_benchmark_config(&path, HEAP, 1, true)
                .expect("create QG-4 index");

            assert!(matches!(
                index.benchmark_arm_qg4_directory_sync(),
                Err(SearchError::InvalidConfig { value, .. }) if value == "not_prepared"
            ));

            index
                .index_document(&cx, &IndexableDocument::new("warm", "warm document"))
                .await
                .expect("stage warm document");
            assert!(matches!(
                index.benchmark_prepare_qg4_no_merge_directory_sync(&cx).await,
                Err(SearchError::InvalidConfig { value, .. }) if value == "documents_already_indexed"
            ));
        });
    }

    #[test]
    fn qg4_directory_sync_receipt_binds_real_sync_opstamp_and_reopen() {
        let directory = tempfile::tempdir().expect("temporary index directory");
        let path = directory.path().join("qg4");
        asupersync::test_utils::run_test_with_cx(|cx| async move {
            let index = TantivyIndex::create_with_benchmark_config(&path, HEAP, 1, true)
                .expect("create QG-4 index");
            index
                .benchmark_prepare_qg4_no_merge_directory_sync(&cx)
                .await
                .expect("prepare no-merge QG-4 fixture");

            index
                .index_document(&cx, &IndexableDocument::new("warm", "warm document"))
                .await
                .expect("stage warm document");
            index.commit(&cx).await.expect("commit warm document");

            index
                .index_document(&cx, &IndexableDocument::new("staged", "staged document"))
                .await
                .expect("stage probe document");
            let mut arm = index
                .benchmark_arm_qg4_directory_sync()
                .expect("arm QG-4 directory observation");
            index
                .benchmark_commit_qg4_directory_sync(&cx, &mut arm)
                .await
                .expect("commit staged QG-4 document");
            let receipt = arm.finish().expect("one real directory sync");
            assert_eq!(receipt.root, path);
            assert_ne!(receipt.commit_opstamp, 0);
            assert_ne!(receipt.session_nonce, 0);
            assert_eq!(receipt.observed_sync_count, 1);

            drop(index);
            let reopened = TantivyIndex::open_with_benchmark_config(&path, HEAP, 1, true)
                .expect("fresh reopen");
            assert_eq!(reopened.doc_count().expect("reopened count"), 2);
            let staged_hits = reopened
                .search_doc_ids(&cx, "id:staged", 2)
                .expect("explicit staged-id query");
            assert_eq!(
                staged_hits.len(),
                1,
                "fresh reopen must retain exactly the staged ID"
            );
            assert_eq!(staged_hits[0].doc_id.as_str(), "staged");
        });
    }

    #[test]
    fn qg4_directory_sync_rejects_a_second_real_armed_sync() {
        let directory = tempfile::tempdir().expect("temporary index directory");
        let path = directory.path().join("qg4");
        asupersync::test_utils::run_test_with_cx(|cx| async move {
            let index = TantivyIndex::create_with_benchmark_config(&path, HEAP, 1, true)
                .expect("create QG-4 index");
            index
                .benchmark_prepare_qg4_no_merge_directory_sync(&cx)
                .await
                .expect("prepare no-merge QG-4 fixture");
            index
                .index_document(&cx, &IndexableDocument::new("staged", "staged document"))
                .await
                .expect("stage probe document");

            let mut arm = index
                .benchmark_arm_qg4_directory_sync()
                .expect("arm QG-4 directory observation");
            index
                .benchmark_test_second_armed_directory_sync()
                .expect("first real wrapped sync");
            index
                .benchmark_commit_qg4_directory_sync(&cx, &mut arm)
                .await
                .expect("commit staged QG-4 document");
            assert!(matches!(
                arm.finish(),
                Err(SearchError::InvalidConfig { value, .. }) if value == "multiple_syncs"
            ));
        });
    }
}

/// Default-feature coverage for the writer-call observation.
///
/// Without this the observation is written on every build but only read behind
/// `bench-internals`, so a default `--all-targets` run would carry a field that
/// is never read. The fix is a real reader, not an allow: the ordinary
/// in-memory constructor genuinely must reach `Index::writer`, and that is
/// worth asserting on its own.
#[cfg(test)]
mod writer_call_observation_tests {
    use super::{TantivyIndex, WriterCall};

    #[test]
    fn the_ordinary_in_memory_constructor_invokes_the_auto_writer() {
        let index = TantivyIndex::in_memory().expect("ordinary in-memory index");
        assert_eq!(
            index.observed_writer_call,
            WriterCall::Auto,
            "the ordinary constructor must reach Index::writer, not a pinned width"
        );
    }
}