infino 0.1.10

A fast retrieval engine that stores data on object storage and runs SQL, full-text search, and vector search over it from a single system — search-on-Parquet.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Infino Authors

//! FTS blob builder. Multi-column FTS index assembly.
//!
//! `FtsBuilder` accumulates posting records across all FTS-indexed
//! columns and on `finish_to<W>` emits the on-disk FTS blob:
//!
//! ```text
//!   header (48 bytes)
//!   FST term dictionary  + CRC32C
//!   postings region      + CRC32C
//!   doc-lengths directory   + CRC32C
//!   per-column doc-lengths arrays  (each + its own CRC32C)
//! ```
//!
//! See `docs/architecture/superfile.md` for the full byte-level spec.
//!
//! ## Build architecture
//!
//! Two-mode accumulator, threshold-based, identical in shape to
//! `VectorBuilder`:
//!
//! - **In-RAM mode**: each column holds a `FxHashMap<term, Vec<(doc,
//!   tf)>>` until total accumulated bytes cross
//!   `spill_threshold_bytes` (default 256 MiB). Small builds never
//!   touch the disk during `add_doc`.
//! - **Spill mode**: once the threshold is crossed, that column's
//!   terms are interned into a per-column `term_to_id`/`id_to_term`
//!   pair, the in-memory map is drained into per-column hash-
//!   partitioned spill files holding **fixed-size 12-byte
//!   `(term_id_le, doc_id_le, tf_le)` triples**, and from then on
//!   `add_doc` writes one triple per posting straight to the spill
//!   files via buffered file IO. Same shape as vector's spill: no
//!   per-record framing, no variable-length payload, no per-record
//!   allocation on read.
//!
//! `finish_to<W: Write>` correspondingly has two paths:
//!
//! - **In-RAM finish**: no column spilled. Per-column maps are
//!   drained, sorted, encoded into a posting-region scratch file,
//!   and the FST is built in RAM (small).
//! - **Spilled finish**: at least one column has spilled. The
//!   spilled column's `id_to_term` builds a lex-rank lookup
//!   (`term_id → rank in lex order`, one `Vec<u32>` per column,
//!   bounded by vocab so small even at 10M docs). Partition files
//!   are read as fixed-size triples, sorted by
//!   `(lex_rank[term_id], doc_id)` (pdqsort over `[(u32, u32,
//!   u32)]` — pure u32 compares, no `&[u8]` chasing), then
//!   k-way-merged into global lex order. The FST is built
//!   *streaming* via [`StreamingDictBuilder`] writing to a scratch
//!   file, using `id_to_term[term_id]` to recover the term bytes
//!   per emission. Final blob assembly is `header → FST scratch →
//!   posting scratch → doc-lengths`, all streamed through `W`.
//!
//! Mirror of vector: vector spills its input corpus as raw f32
//! bytes past 256 MiB and streams its centroid+code layout to
//! scratch; FTS spills its posting accumulator as fixed 12-byte
//! triples past 256 MiB and streams its FST + posting region to
//! scratch. Both bound peak resident memory by a formula that does
//! not include `n_docs`, and both use fixed-size, no-framing record
//! formats so the spill IO is allocator-free on the read side.
//!
//! ## Builder lifecycle
//!
//! 1. `FtsBuilder::new(tokenizer)` — empty builder.
//! 2. `register_column(name, false)` per FTS column, in declaration order.
//! 3. `add_doc(column_id, local_doc_id, text)` per `(doc, column)` pair.
//!    Caller passes monotonically-increasing `local_doc_id`s.
//! 4. `finish()` (returns `Vec<u8>`) or `finish_to(impl Write)`
//!    (streams the blob progressively to any sink).

use std::{
    cmp::Ordering,
    collections::BinaryHeap,
    fs,
    fs::File,
    hash::{BuildHasher, Hash},
    io::{self, BufReader, BufWriter, Error, ErrorKind, Read, Seek, SeekFrom, Write},
    mem,
    path::{Path, PathBuf},
    sync::Arc,
    time::{Duration, Instant},
    vec::IntoIter,
};

use bumpalo::Bump;
use hashbrown::hash_map::{HashMap as HbHashMap, RawEntryMut};
use memmap2::Mmap;
use rustc_hash::{FxBuildHasher, FxHashMap};

use crate::superfile::{
    BuildError,
    format::{
        self, FST_SEPARATOR,
        checksum::{crc32c, crc32c_append},
    },
    fts::{
        bm25,
        dict::{DictBuilder, StreamingDictBuilder},
        fst_value::{FstValue, INLINE_TF_MAX},
        positions::{encode_run, read_varint, skip_run},
        posting::{BLOCK_LEN, Block, EncodedBlock, encode_block},
        tokenize::{AsciiLowerTokenizer, Tokenizer},
    },
};

/// Per-column term interner table.
///
/// Keys are `&'static str` slices that **actually borrow from the
/// per-column `term_arena: bumpalo::Bump`** stored alongside the
/// map in the [`ColumnPostings::Spilled`] variant. The `'static`
/// lifetime tag is a lie maintained by `unsafe` `std::mem::
/// transmute` at insertion (see [`intern_term_id_arena`]) and
/// kept sound by two structural invariants:
///
/// 1. The arena outlives the map. The `Spilled` variant declares
///    `term_arena` *after* `term_to_id` and `id_to_term` so Rust
///    drops it last (struct fields drop in declaration order, so
///    the last-declared field is the last-dropped). The
///    `finish_to` per-column block that destructures `Spilled`
///    likewise puts `term_arena` last in the pattern and adds an
///    explicit `drop(term_arena)` after the last use of
///    `id_to_term` for the same reason.
/// 2. No method on the map's keys does a deref during the map's
///    own `Drop`. `&str` has no `Drop` impl, so dropping the map
///    just deallocates the bucket table without touching the
///    key bytes. The arena can therefore safely outlast the
///    map's body without the map ever needing arena bytes
///    during its own teardown.
///
/// Switching from `Box<str>` keys to arena `&str` keys:
///
///   * removes one `Box<str>` heap allocation per intern miss
///     (was: one for the map key + one cloned for `id_to_term`;
///     now: one bump-arena copy reused by both);
///   * packs all term bytes densely in the bump arena instead
///     of scattering them across the global heap, which keeps
///     the byte-compare fast path inside `raw_entry_mut` cache-
///     hot on the per-token spill-arm hot loop (the bench
///     vocab is ~10K terms × ~5-10 byte average = ~75 KiB
///     total, comfortably L2-resident as one contiguous arena
///     instead of ~10K separate heap allocations chasing
///     pointers through unrelated allocator buckets).
type TermIdMap = HbHashMap<&'static str, u32, FxBuildHasher>;

/// Reusable per-document term-frequency table for the in-RAM build path.
///
/// Keys borrow from [`FtsBuilder::bump`] with the same lifetime-extension
/// discipline as [`TermIdMap`]. The table is drained after every document
/// and cleared before the arena is reset, so only its bucket allocation
/// persists across calls.
type DocTfMap = HbHashMap<&'static str, u32, FxBuildHasher>;

/// Per-doc positional chain-head map — same key lifetime rules as
/// [`DocTfMap`] (bump-arena keys, cleared before every arena reset).
type DocPosHeadMap = HbHashMap<&'static str, u32, FxBuildHasher>;

/// Chain terminator for the per-doc position chains
/// (`FtsBuilder::doc_pos_chain`): no previous occurrence.
const CHAIN_END: u32 = u32::MAX;

#[derive(Default)]
struct FinishProfile {
    enabled: bool,
    encode_calls: u64,
    encode_df1: u64,
    encode_pfor: u64,
    encode_total: Duration,
    encode_block_build: Duration,
    encode_meta_write: Duration,
    encode_skip_write: Duration,
    encode_block_write: Duration,
    fst_insert: Duration,
    // Per-column phase totals (summed across columns; printed in the
    // [fts-finish] summary line at the end of finish_to).
    partition_flush: Duration,
    lex_rank_build: Duration,
    partition_sort: Duration,
    mmap_open: Duration,
    scratch_cleanup: Duration,
    // Whole-finish phase totals (printed once at end of finish_to).
    fst_close: Duration,
    postings_close: Duration,
    doc_lengths_emit: Duration,
    blob_copy: Duration,
}

impl FinishProfile {
    fn from_config() -> Self {
        Self {
            enabled: crate::config::global().diagnostics.fts_profile,
            ..Self::default()
        }
    }
}

/// Per-(column, term) metadata header — 20 bytes, written immediately
/// before the term's skip table + posting blocks in the postings region.
/// `term_metadata_offset` (referenced from the FST value) points at the
/// start of this struct.
///
/// Layout:
///   off  0 ..  4 : df (u32) — bounded by n_docs per superfile
///   off  4 .. 12 : postings_offset (u64) — equals the term's metadata_offset;
///                  self-describing. u64 supports superfiles past 4 GiB
///                  (e.g. the 16 GB target).
///   off 12 .. 16 : postings_length (u32) — single term's bytes, well under
///                  4 G even at high df (≤ ~1 MB for the most common term in
///                  a 16 GB superfile).
///   off 16 .. 20 : num_blocks (u32)
///
/// `df`, `postings_length`, and `num_blocks` stay u32; only the absolute
/// offset into the postings region needs the full u64 range.
pub(crate) const TERM_META_SIZE: usize = 20;

/// Extended per-term metadata header for terms of a **positional**
/// column: the 20-byte layout plus `positions_offset` (u64, absolute
/// within the positions region) and `positions_length` (u32). The
/// column's positions flag selects the stride — the two layouts never
/// mix within one column.
pub(crate) const TERM_META_POSITIONAL_SIZE: usize = 32;

/// Skip-table entry size in bytes.
pub(crate) const SKIP_ENTRY_SIZE: usize = 16;

/// Doc-lengths directory entry size in bytes (per column).
///
/// Layout:
///   off  0 ..  4 : column_id (u32)
///   off  4 .. 12 : doc_lengths_offset (u64) — absolute offset of this column's
///                  doc-lengths array in the FTS blob. u64 supports superfiles
///                  past 4 GiB.
///   off 12 .. 16 : avgdl_x1000 (u32) — avgdl × 1000, as an integer
///
/// Only the absolute offset needs u64; column_id and avgdl_x1000 stay
/// u32 (bounded by column count and doc length respectively).
pub(crate) const DOC_LENGTHS_ENTRY_SIZE: usize = 16;

/// Default per-column in-RAM accumulator budget before a column
/// flushes to spill files. Mirrors `VectorBuilder::spill_threshold_bytes`
/// (also 256 MiB by default). Builds whose every column stays below
/// this never touch the disk during `add_doc`.
///
/// Overridable per-builder via `FtsBuilder::set_spill_threshold_bytes(b)`.
pub const DEFAULT_SPILL_THRESHOLD_BYTES: usize = 256 * 1024 * 1024;

/// Default hash-partition count for the spill-backed postings accumulator.
///
/// In spill mode each `(term, doc_id, tf)` record is written to one
/// partition during `add_doc`; `finish_to` sorts and k-way-merges
/// partitions in global lex order. Higher values shrink the expected
/// per-partition size at the cost of more file handles.
///
/// Overridable per-builder via `FtsBuilder::set_spill_partitions(n)`.
pub const DEFAULT_SPILL_PARTITIONS: usize = 128;

/// Default in-memory budget per partition during the finish-time
/// sort pass. Partitions whose on-disk size exceeds this value are
/// sorted via external merge (chunked sort + k-way merge over
/// sorted spill files) rather than being fully materialised in RAM.
///
/// Overridable per-builder via `FtsBuilder::set_max_partition_bytes(b)`.
pub const DEFAULT_MAX_PARTITION_BYTES: u64 = 256 * 1024 * 1024;

/// Per-partition write buffer. 64 KiB matches the vector builder's
/// bucket writer budget and amortizes syscall cost without pinning
/// meaningful RAM.
const PARTITION_BUF_SIZE: usize = 64 * 1024;

/// Approximate per-record byte overhead in the in-RAM posting
/// accumulator. Used to drive the spill threshold; intentionally
/// rough — the threshold is a soft budget, not a hard cap.
///
/// - `~24 B`: per new term: FxHashMap entry header + `Vec<(u32,u32)>`
///   header + `Box<str>` header + small-alloc rounding.
/// - `+ term.len()`: term bytes.
/// - `+ 8 B`: per added posting: `(doc_id: u32, tf: u32)`.
const ACCUM_NEW_TERM_FIXED_BYTES: usize = 24;
const ACCUM_POSTING_BYTES: usize = 8;

/// Partition size (in triples) below which the lex-rank sort uses
/// `sort_unstable_by` instead of the counting/radix variant: under
/// this count the histogram allocation outweighs the algorithmic
/// savings.
const RADIX_SORT_MIN_TRIPLES: usize = 256;

/// Upper bound on the initial in-RAM chunk capacity (in triples)
/// during external merge sort. Caps the up-front `Vec` reservation
/// (~12 MiB of triples) when `max_partition_bytes` is large.
const EXTERNAL_MERGE_CHUNK_CAP_TRIPLES: usize = 1024 * 1024;

/// Number of triples buffered before each `write_all` when streaming
/// a sorted partition to disk. Amortizes the syscall cost (~48 KiB
/// per flush).
const SORT_OUTPUT_BATCH_TRIPLES: usize = 4096;

/// Per-column build-time state (scalar accounting only).
struct ColumnState {
    name: String,
    /// One u32 per doc (token count for this column), push order
    /// matches local_doc_id order.
    doc_lengths: Vec<u32>,
    /// Total token count across every doc in this column. Used for
    /// `avgdl = total_tokens / n_docs`.
    total_tokens: u64,
    /// Record token positions for this column (phrase support). Set
    /// at registration from `FtsConfig::positions`; selects the
    /// positional capture path in `add_doc` and the extended
    /// per-term layout at emit.
    positions: bool,
}

/// Per-column posting accumulator. Starts in `InRam` mode; transitions
/// to `Spilled` exactly once when this column's accumulated bytes
/// cross the builder's `spill_threshold_bytes`.
enum ColumnPostings {
    /// In-RAM term → posting list map. Small builds stay here forever.
    InRam {
        terms: FxHashMap<Box<str>, Vec<(u32, u32)>>,
        /// Per-term position runs for a **positional column**: the
        /// concatenated [`positions`](crate::superfile::fts::positions)
        /// varint runs, one run per `(doc, tf)` pair in `terms`, in the
        /// same doc order — pair `i`'s run is the `i`-th run in the
        /// buffer, delimited by its `tf`. Never populated for
        /// positionless columns (zero cost off).
        pos_runs: FxHashMap<Box<str>, Vec<u8>>,
        /// Estimated bytes held by `terms` (+ `pos_runs`) — used to
        /// drive the spill threshold check. Approximate (see
        /// `ACCUM_*_BYTES`).
        bytes: usize,
    },
    /// Hash-partitioned spill files plus the per-column term
    /// interner. Records on disk are fixed-size 12-byte
    /// `(term_id_le, doc_id_le, tf_le)` triples — same shape as
    /// vector's raw-f32 spill, no per-record framing.
    ///
    /// `term_to_id` assigns a fresh `u32` ID to each distinct term
    /// the first time it's seen (during the threshold flush, then
    /// during subsequent `add_doc` calls). `id_to_term` is the
    /// reverse map used at `finish_to` time to recover the term
    /// bytes for FST emission. Both are bounded by the column's
    /// vocabulary, which is typically O(10^4 - 10^6) even on 10M-
    /// doc corpora — millions of bytes, not gigabytes.
    Spilled {
        partitions: SpillStore,
        term_to_id: TermIdMap,
        /// Per-id reverse lookup used by `finish_to` to recover term
        /// bytes for FST emit. Entries are `&'static str` slices
        /// borrowing from `term_arena` (see [`TermIdMap`] doc for
        /// the lifetime-extension invariant — same arena, same
        /// drop-order rules).
        id_to_term: Vec<&'static str>,
        /// Per-doc tf accumulator, indexed by `term_id`. Replaces the
        /// previous `FxHashMap<u32, u32>` scratch: term_ids are dense
        /// `0..vocab_size` (vocab ~10K on the bench Zipfian corpus, ≤
        /// few M on 10M-doc corpora), so a dense `Vec<u32>` keyed on
        /// `term_id` is a single array store per token (~5ns) vs a
        /// hashmap probe + entry update (~25-30ns). On the 1M-doc
        /// spill bench that's ~150M token-hits, so the per-call delta
        /// is the dominant `add_doc` cost saving.
        ///
        /// Memory: 4 bytes × vocab. 40 KiB at 10K vocab; a few MiB
        /// even at multi-M vocab — well inside the `O(max_partition_
        /// bytes)` budget. The Vec grows monotonically as `intern_
        /// term_id` mints new IDs; only ever read at the indices
        /// listed in `updated_terms`, so stale entries past the
        /// current `add_doc`'s set are ignored.
        dense_doc_tf: Vec<u32>,
        /// Per-doc position-chain heads, indexed by `term_id` like
        /// `dense_doc_tf` (`CHAIN_END` = no occurrence this doc).
        /// Allocated (and maintained) only for positional columns;
        /// stays empty otherwise.
        dense_doc_poshead: Vec<u32>,
        /// Set of `term_id`s that were written in the current
        /// `add_doc` call. Drained at the end of each call to emit
        /// triples and zero out `dense_doc_tf` slots — bounded by
        /// the per-doc unique-term count (≤ doc length), so a tiny
        /// `Vec<u32>` reused across calls.
        updated_terms: Vec<u32>,
        /// Per-column bump arena owning the term bytes. Backing
        /// store for the `&'static str` keys in `term_to_id` and
        /// entries in `id_to_term` (see [`TermIdMap`] doc).
        ///
        /// **Declared LAST in this variant so it drops LAST.**
        /// Rust drops struct fields in declaration order; the map
        /// + reverse vec drop first, both of which leave their
        ///   `&str` keys / entries bitwise-deallocated without
        ///   dereferencing, and only then does the arena's
        ///   `Drop` free the term bytes.
        term_arena: Bump,
    },
}

impl ColumnPostings {
    fn new() -> Self {
        Self::InRam {
            terms: FxHashMap::default(),
            pos_runs: FxHashMap::default(),
            bytes: 0,
        }
    }
    fn is_spilled(&self) -> bool {
        matches!(self, Self::Spilled { .. })
    }
}

/// Per-partition batch buffer used in front of `BufWriter` on the
/// hot `add_doc` spill path. Sized so it holds 341 fixed-12-byte
/// triples (≈ 4 KiB). The flush path is one `Vec::extend_from_slice
/// (&[u8; 12])` per posting plus one `BufWriter::write_all` per
/// full batch, vs the previous "one `BufWriter::write_all([u8; 12])`
/// per posting". On the 1M-doc bench this is ~440K BufWriter
/// branches instead of ~150M.
const SPILL_BATCH_TRIPLES: usize = 341;

struct SpillPartition<const N: usize> {
    path: PathBuf,
    writer: Option<BufWriter<File>>,
    /// In-memory batch buffer flushed into `writer` when full.
    /// `add_doc` appends triples here in the hot path; `finish_to`'s
    /// flush-stage drains any partial buffer once per partition before
    /// the merge starts.
    ///
    /// Stored as `Vec<Triple>` rather than `Vec<u8>` so the hot-path
    /// `push_triple_batched` is a single `Vec::push` (one len-bump +
    /// 12-byte store) instead of `extend_from_slice` of three
    /// per-field `copy_from_slice` writes. On the 1M-doc spill bench
    /// that's ~135M call-sites in the hot loop; the per-call delta
    /// adds up.
    ///
    /// On flush the buffer is cast to `&[u8]` via `bytemuck::cast_slice`
    /// (LE hosts) — zero copy. BE hosts pay a per-triple byte-swap
    /// path. Capacity reserved to `SPILL_BATCH_TRIPLES` up front so
    /// the steady-state push is branch-free w.r.t. capacity.
    batch: Vec<[u32; N]>,
}

/// Fixed on-disk record size in the spill files: 4 bytes `term_id`
/// + 4 bytes `doc_id` + 4 bytes `tf`, all little-endian.
///
/// This matches vector's "raw f32 bytes" spill strategy in shape:
/// fixed-size records, no framing, no variable-length payload.
/// `read_triples` reads N×12 bytes in one syscall-amortised batch
/// and reinterprets as `&[[u32; 3]]` via `bytemuck` — zero per-
/// record allocation, no UTF-8 validation, no `Box<str>` round-
/// trips.
/// Sortable + heap-mergeable posting triple. Matches the on-disk
/// layout (`[term_id_le, doc_id_le, tf_le]`) exactly so a partition
/// file's bytes can be reinterpreted as `&[Triple]` without copying
/// on little-endian hosts.
/// Lane count of the plain (positionless) spill record.
const PLAIN_RECORD_LANES: usize = 3;

/// Lane count of the positional spill record:
/// `[term_id, doc_id, tf, pos_off_lo, pos_off_hi]`. The last two
/// lanes carry the little-endian halves of the u64 byte offset of
/// this posting's position run in the partition's positions blob.
const POSITIONAL_RECORD_LANES: usize = 5;

/// Pack a positions-blob byte offset into the positional record's
/// two trailing lanes.
#[inline(always)]
fn pos_off_lanes(off: u64) -> (u32, u32) {
    (off as u32, (off >> 32) as u32)
}

/// Recover the positions-blob byte offset from a positional record.
#[inline(always)]
fn record_pos_off(rec: &[u32; POSITIONAL_RECORD_LANES]) -> u64 {
    (rec[3] as u64) | ((rec[4] as u64) << 32)
}

/// Per-partition positions blob for a positional column's spill: the
/// delta-varint runs of every posting routed to this partition, in
/// arrival order, addressed by the byte offsets riding in the
/// partition's 5-lane records. Written during `add_doc` (and the
/// in-RAM→spill transition), mmap'd read-only at merge time.
struct PartitionPositions {
    path: PathBuf,
    writer: Option<BufWriter<File>>,
    /// Bytes written so far — the next run's offset.
    len: u64,
}

/// A spilled column's partition set. A positionless column spills
/// plain 3-lane records; a positional column spills 5-lane records
/// plus one positions blob per partition (parallel vectors).
enum SpillStore {
    Plain(Vec<SpillPartition<PLAIN_RECORD_LANES>>),
    Positional {
        partitions: Vec<SpillPartition<POSITIONAL_RECORD_LANES>>,
        blobs: Vec<PartitionPositions>,
    },
}

impl SpillStore {
    fn n_partitions(&self) -> usize {
        match self {
            SpillStore::Plain(p) => p.len(),
            SpillStore::Positional { partitions, .. } => partitions.len(),
        }
    }
}

#[inline(always)]
fn triple_term_id<const N: usize>(t: &[u32; N]) -> u32 {
    t[0]
}
#[inline(always)]
fn triple_doc_id<const N: usize>(t: &[u32; N]) -> u32 {
    t[1]
}
#[inline(always)]
fn triple_tf<const N: usize>(t: &[u32; N]) -> u32 {
    t[2]
}

/// Write one triple as little-endian bytes via a single 12-byte
/// `write_all`. Replaces the old four-call
/// `write_posting_record` — function-call overhead is ~4× lower
/// on `BufWriter` and the syscall amortisation through the 64-KiB
/// buffer is unchanged. Reserved for callers without a per-
/// partition batch buffer (the `flush_in_ram_to_partitions`
/// streaming path uses the buffered `push_triple_batched` path
/// instead — see below).
/// On big-endian hosts, the bulk `bytemuck::cast_slice` write
/// path in `write_triples_sorted` is replaced with a per-triple
/// scalar write to preserve the little-endian on-disk format.
/// On little-endian hosts (x86_64, aarch64) the bulk path is
/// the only one compiled, so this function isn't built at all.
#[cfg(not(target_endian = "little"))]
#[inline(always)]
fn write_record<W: Write, const N: usize>(w: &mut W, rec: &[u32; N]) -> Result<(), BuildError> {
    let mut buf = [0u8; MAX_RECORD_BYTES];
    for (lane, v) in rec.iter().enumerate() {
        buf[lane * 4..lane * 4 + 4].copy_from_slice(&v.to_le_bytes());
    }
    w.write_all(&buf[..mem::size_of::<[u32; N]>()])?;
    Ok(())
}

/// Append one fixed-12-byte triple to a `SpillPartition`'s in-
/// memory batch buffer, flushing the batch to the partition's
/// `BufWriter` only when it reaches `SPILL_BATCH_BYTES` (4 KiB).
///
/// This is the hot path on `add_doc` spill: ~150M calls at 1M
/// docs / 1500 tokens/doc. Each call is one `extend_from_slice`
/// of 12 bytes onto a `Vec<u8>` (the Vec's capacity is reserved
/// up-front, so the extend is a pure memcpy + len bump — no
/// branch on capacity); every 341st call also pays one
/// `BufWriter::write_all` + buffer clear. Replaces the old
/// "one `BufWriter::write_all([u8; 12])` per posting" pattern
/// which paid the `BufWriter`'s "does this fit in the inline
/// buffer?" branch on every single posting.
#[inline(always)]
fn push_record_batched<const N: usize>(
    partition: &mut SpillPartition<N>,
    rec: [u32; N],
) -> Result<(), BuildError> {
    partition.batch.push(rec);
    if partition.batch.len() >= SPILL_BATCH_TRIPLES {
        flush_partition_batch(partition)?;
    }
    Ok(())
}

/// Drain any pending bytes in a partition's batch buffer into its
/// `BufWriter`. Called from the hot path when the batch fills and
/// from `finish_to`'s flush stage so partial buffers reach disk
/// before the merge starts.
#[inline]
fn flush_partition_batch<const N: usize>(
    partition: &mut SpillPartition<N>,
) -> Result<(), BuildError> {
    if partition.batch.is_empty() {
        return Ok(());
    }
    let writer = partition
        .writer
        .as_mut()
        .expect("partition writer is open before finish");
    // LE host: zero-copy cast from `&[Triple]` to `&[u8]`. BE host:
    // per-triple swap path keeps the on-disk file little-endian so
    // the LE fast read path stays valid cross-arch.
    #[cfg(target_endian = "little")]
    {
        writer.write_all(bytemuck::cast_slice::<[u32; N], u8>(&partition.batch))?;
    }
    #[cfg(not(target_endian = "little"))]
    {
        for t in &partition.batch {
            write_record(writer, t)?;
        }
    }
    partition.batch.clear();
    Ok(())
}

/// Read every triple in `path` into a `Vec<Triple>`. The file is
/// laid out as a contiguous run of 12-byte LE triples, so on a
/// little-endian host the read is a single batched `read_to_end`
/// followed by a `bytemuck` reinterpretation (zero per-record
/// allocation, zero UTF-8 validation, no `Box<str>` chasing).
///
/// On a big-endian host the same bytes are read but each triple
/// is byte-swapped on the way in — kept behind a `cfg` so x86_64
/// and arm64 hit the fast cast path.
fn read_partition_records<const N: usize>(path: &Path) -> Result<Vec<[u32; N]>, BuildError> {
    let mut bytes = Vec::new();
    let mut f = File::open(path)?;
    f.read_to_end(&mut bytes)?;
    if bytes.is_empty() {
        return Ok(Vec::new());
    }
    let rec_bytes = mem::size_of::<[u32; N]>();
    if bytes.len() % rec_bytes != 0 {
        return Err(BuildError::Io(Error::new(
            ErrorKind::InvalidData,
            format!(
                "spill partition {path:?} length {} not a multiple of {}",
                bytes.len(),
                rec_bytes
            ),
        )));
    }
    #[cfg(target_endian = "little")]
    {
        // Zero-copy bytes → triples cast on LE hosts. `bytemuck`
        // gates this on `Pod` alignment; `Vec<u8>::read_to_end`
        // returns a `Vec` whose buffer is aligned at least to
        // `align_of::<usize>()` (8 bytes on x86_64), so the cast
        // to `[u32; 3]` (alignment 4) is sound.
        let records: &[[u32; N]] = bytemuck::try_cast_slice(&bytes).map_err(|_| {
            BuildError::Io(Error::new(
                ErrorKind::InvalidData,
                "bytemuck: spill bytes failed alignment for the record slice",
            ))
        })?;
        Ok(records.to_vec())
    }
    #[cfg(not(target_endian = "little"))]
    {
        let n = bytes.len() / rec_bytes;
        let mut out = Vec::with_capacity(n);
        for i in 0..n {
            let off = i * rec_bytes;
            let mut rec = [0u32; N];
            for (lane, slot) in rec.iter_mut().enumerate() {
                let at = off + lane * 4;
                *slot = u32::from_le_bytes(
                    bytes[at..at + 4]
                        .try_into()
                        .expect("invariant: 4-byte record lane"),
                );
            }
            out.push(rec);
        }
        Ok(out)
    }
}

/// Build the two lex-order permutations between `term_id` and
/// lex rank over `id_to_term`:
///
/// * `lex_rank[term_id] = rank` (forward map, used for sort keys
///   in the per-partition sort).
/// * `term_id_in_lex_order[rank] = term_id` (inverse map; the
///   sorted permutation itself, used by the finish-time merge to
///   walk term_ids in global lex order without any heap
///   arbitration).
///
/// Both come from the same `sort_unstable_by` pass over `[0..n)`,
/// so producing both is essentially free. Bounded by the column's
/// vocabulary; tiny even at 10M docs.
fn build_lex_rank(id_to_term: &[&str]) -> (Vec<u32>, Vec<u32>) {
    let n = id_to_term.len();
    let mut by_lex: Vec<u32> = (0..n as u32).collect();
    by_lex.sort_unstable_by(|&a, &b| {
        id_to_term[a as usize]
            .as_bytes()
            .cmp(id_to_term[b as usize].as_bytes())
    });
    let mut rank = vec![0u32; n];
    for (r, id) in by_lex.iter().enumerate() {
        rank[*id as usize] = r as u32;
    }
    (rank, by_lex)
}

#[inline(always)]
fn compute_hash<Q: Hash + ?Sized, S: BuildHasher>(hash_builder: &S, key: &Q) -> u64 {
    hash_builder.hash_one(key)
}

/// Intern `term` in the spill-mode column vocabulary and return its
/// stable `term_id`.
///
/// This is the hot spill `add_doc` lookup. Use hashbrown's raw entry
/// API so miss handling reuses the hash computed for lookup instead
/// of doing `get(term)` (probe once) followed by `insert(boxed, id)`
/// (rehash + probe again). Hit behaviour remains one borrowed lookup
/// with no allocation; misses copy the term bytes into the per-column
/// `term_arena: bumpalo::Bump` (one bump-pointer advance + memcpy, no
/// heap allocator round-trip) and store the resulting `&str` slice in
/// both the map and `id_to_term` (a reference copy, no second heap
/// alloc — replaces the prior `Box<str>` + `boxed.clone()` pattern
/// which paid two heap allocations per miss).
///
/// The on-hit cost benefit is the more important change at scale:
/// every intern hit's byte-compare inside `raw_entry_mut` previously
/// dereferenced an arbitrary `Box<str>` whose backing bytes sat
/// wherever the global allocator placed it (typically scattered
/// across cache lines, often L2-cold for vocabularies >~1 KB worth
/// of total key bytes). Arena-backed keys live densely in a single
/// contiguous `bumpalo::Bump` so the byte-compare hits L1/L2 the
/// vast majority of the time, regardless of vocab size.
///
/// Returns `(term_id, is_new)`. `is_new == true` iff this call minted
/// a brand-new id (`term_to_id` previously had no entry for `term`).
/// Callers that keep a per-id parallel array (e.g. `dense_doc_tf` on
/// the spill path) use this to gate the grow check off the hot path:
/// after the InRam→Spilled transition pre-grows the parallel array
/// to `id_to_term.len()`, the array only needs to be extended when a
/// fresh id is minted, which is once per novel term per column —
/// not once per token.
///
/// SAFETY (invariants enforced by callers and the `Spilled` variant
/// struct layout, see [`TermIdMap`] doc): the `'static` lifetime tag
/// on the keys is a lie — the real lifetime is that of `arena`. The
/// transmute below is sound iff (a) `arena` outlives both
/// `term_to_id` and `id_to_term`, and (b) no key dereference happens
/// after `arena`'s `Drop` runs. Both hold by construction: `arena`
/// is declared *after* the map and reverse-vec in `Spilled` so it
/// drops *last*, and the `Drop` impls for `HbHashMap<&'static str,
/// u32, _>` and `Vec<&'static str>` never dereference their
/// `&str` keys/entries (no `Drop` to run on a reference).
#[inline(always)]
fn intern_term_id(
    term_to_id: &mut TermIdMap,
    id_to_term: &mut Vec<&'static str>,
    arena: &Bump,
    term: &str,
) -> (u32, bool) {
    let hash = compute_hash(term_to_id.hasher(), term);
    match term_to_id
        .raw_entry_mut()
        .from_hash(hash, |existing| *existing == term)
    {
        RawEntryMut::Occupied(entry) => (*entry.get(), false),
        RawEntryMut::Vacant(entry) => {
            let id = id_to_term.len() as u32;
            // Bump-arena copy: one pointer advance + memcpy of the
            // term bytes, returning a `&str` whose lifetime is tied
            // to `&arena`'s borrow scope.
            let arena_str: &str = arena.alloc_str(term);
            // SAFETY: see function-level doc. The `'static` tag is
            // a lie; the real lifetime is `arena`'s, which the
            // `Spilled` variant guarantees outlives the map +
            // id_to_term via field drop order.
            let static_str: &'static str = unsafe { std::mem::transmute(arena_str) };
            id_to_term.push(static_str);
            entry.insert_hashed_nocheck(hash, static_str, id);
            (id, true)
        }
    }
}

/// Min-heap entry for the k-way merge over sorted partition chunks.
/// Sort key is a packed `u64 = (lex_rank as u64) << 32 | doc_id as
/// u64` — natural u64 ordering matches `(lex_rank, doc_id)` lex
/// order, so the heap comparator is a single u64 compare per pop.
/// Ordering is inverted (heap returns the *smallest* sort key
/// first) by implementing `Ord` reversed; `BinaryHeap` is a max-
/// heap.
struct MergeEntry<const N: usize> {
    /// `(lex_rank as u64) << 32 | doc_id as u64`.
    sort_key: u64,
    /// The full record — term_id/doc_id/tf lanes plus, on positional
    /// columns, the positions-blob offset lanes.
    rec: [u32; N],
    reader_idx: usize,
}

impl<const N: usize> PartialEq for MergeEntry<N> {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}
impl<const N: usize> Eq for MergeEntry<N> {}
impl<const N: usize> PartialOrd for MergeEntry<N> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}
impl<const N: usize> Ord for MergeEntry<N> {
    fn cmp(&self, other: &Self) -> Ordering {
        // Reverse so the largest "smallest" wins on pop — gives
        // BinaryHeap min-heap behaviour over (lex_rank, doc_id).
        other
            .sort_key
            .cmp(&self.sort_key)
            .then(other.reader_idx.cmp(&self.reader_idx))
    }
}

#[inline(always)]
fn pack_sort_key(lex_rank: u32, doc_id: u32) -> u64 {
    ((lex_rank as u64) << 32) | (doc_id as u64)
}

/// Iterator producing sorted triples (by `(lex_rank, doc_id)`) for
/// one partition.
///
/// `InMemory` is the small-partition path: the whole partition fits
/// in `max_partition_bytes` of RAM, so it's read once, sorted in
/// place, and drained.
///
/// `Merge` is the over-budget path: the partition is streamed in
/// chunks of `max_partition_bytes`, each chunk sorted in RAM and
/// spilled to a sorted-chunk side file under the scratch directory,
/// and then k-way-merged via a `BinaryHeap` of cursors so the
/// finish-time sort never holds more than one chunk plus one
/// record per chunk file at a time.
enum PartitionIter<const N: usize> {
    InMemory(IntoIter<[u32; N]>),
    Merge {
        readers: Vec<BufReader<File>>,
        heap: BinaryHeap<MergeEntry<N>>,
        /// Sorted-chunk files; kept alive so their inodes don't
        /// get reaped before iteration finishes.
        _chunk_paths: Vec<PathBuf>,
    },
}

impl<const N: usize> PartitionIter<N> {
    /// Pull the next sorted triple from this partition, looking up
    /// the sort key via `lex_rank` when refilling a merge cursor
    /// (so the heap stays minimal — only sort_key + tf + term_id
    /// + reader_idx).
    fn next_with(&mut self, lex_rank: &[u32]) -> Option<Result<[u32; N], BuildError>> {
        match self {
            PartitionIter::InMemory(it) => it.next().map(Ok),
            PartitionIter::Merge { readers, heap, .. } => {
                let MergeEntry {
                    rec, reader_idx, ..
                } = heap.pop()?;
                match read_one_record::<_, N>(&mut readers[reader_idx]) {
                    Ok(Some(next_t)) => {
                        let next_id = triple_term_id(&next_t);
                        let next_doc = triple_doc_id(&next_t);
                        let key = pack_sort_key(lex_rank[next_id as usize], next_doc);
                        heap.push(MergeEntry {
                            sort_key: key,
                            rec: next_t,
                            reader_idx,
                        });
                    }
                    Ok(None) => { /* chunk drained */ }
                    Err(e) => return Some(Err(e)),
                }
                Some(Ok(rec))
            }
        }
    }
}

/// Read a single 12-byte triple from a sorted-chunk file. Returns
/// `Ok(None)` on clean EOF.
fn read_one_record<R: Read, const N: usize>(r: &mut R) -> Result<Option<[u32; N]>, BuildError> {
    let mut buf = [0u8; MAX_RECORD_BYTES];
    let rec_bytes = mem::size_of::<[u32; N]>();
    match r.read_exact(&mut buf[..rec_bytes]) {
        Ok(()) => {}
        Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(None),
        Err(e) => return Err(BuildError::Io(e)),
    }
    let mut rec = [0u32; N];
    for (lane, slot) in rec.iter_mut().enumerate() {
        let at = lane * 4;
        *slot = u32::from_le_bytes(buf[at..at + 4].try_into().expect("slice len 4"));
    }
    Ok(Some(rec))
}

/// Stack-buffer bound for [`read_one_record`]: the widest spill
/// record (the positional 5-lane form).
const MAX_RECORD_BYTES: usize = mem::size_of::<[u32; 5]>();

/// Write a slice of triples to a sorted-chunk file. Single
/// `write_all` per chunk on LE hosts via `bytemuck` byte-cast.
fn write_records_sorted<const N: usize>(
    triples: &[[u32; N]],
    path: &Path,
) -> Result<(), BuildError> {
    let mut w = BufWriter::with_capacity(PARTITION_BUF_SIZE, File::create(path)?);
    #[cfg(target_endian = "little")]
    {
        let bytes: &[u8] = bytemuck::cast_slice(triples);
        w.write_all(bytes)?;
    }
    #[cfg(not(target_endian = "little"))]
    {
        for t in triples {
            write_record(&mut w, t)?;
        }
    }
    w.flush()?;
    Ok(())
}

fn spill_sorted_chunk<const N: usize>(
    chunk: &mut Vec<[u32; N]>,
    scratch_dir: &Path,
    partition_label: &str,
    chunk_idx: usize,
    lex_rank: &[u32],
    out_paths: &mut Vec<PathBuf>,
) -> Result<(), BuildError> {
    radix_sort_records_by_lex_rank(chunk, lex_rank);
    let path = scratch_dir.join(format!("{partition_label}_sorted{chunk_idx}.bin"));
    write_records_sorted(chunk, &path)?;
    chunk.clear();
    #[cfg(test)]
    finish_debug::record_chunk_path(&path);
    out_paths.push(path);
    Ok(())
}

/// Test-only observer for the external-merge chunk-file path.
///
/// Used by `external_merge_path_matches_in_memory_path_byte_for_
/// byte` to gate that the over-budget partition branch in
/// `open_partition_sorted` actually runs (and therefore that the
/// reviewer's "is the external merge exercised?" question is
/// answered by a positive test, not just blob-equality). Lives in
/// `#[cfg(test)]` so production binaries pay zero runtime cost.
#[cfg(test)]
mod finish_debug {
    use std::{
        cell::RefCell,
        path::{Path, PathBuf},
    };

    thread_local! {
        // Thread-local so concurrent `cargo test` workers do not
        // cross-pollute each other's observed chunk lists. Tests
        // that drive the external-merge path build + finish on
        // their own worker thread, so this stays isolated.
        static OBSERVED_CHUNKS: RefCell<Vec<PathBuf>> = const { RefCell::new(Vec::new()) };
    }

    /// Clear the observed-chunks log. Tests call this before the
    /// build whose external-merge activity they want to inspect.
    pub fn reset() {
        OBSERVED_CHUNKS.with(|c| c.borrow_mut().clear());
    }

    /// Called by `spill_sorted_chunk` for every sorted-chunk file
    /// written during external-merge.
    pub fn record_chunk_path(path: &Path) {
        OBSERVED_CHUNKS.with(|c| c.borrow_mut().push(path.to_path_buf()));
    }

    /// Snapshot of the observed-chunk-path list.
    pub fn observed() -> Vec<PathBuf> {
        OBSERVED_CHUNKS.with(|c| c.borrow().clone())
    }
}

/// Sort `triples` in place by `(lex_rank[term_id], doc_id)` using a
/// single-pass O(n) stable counting sort over `lex_rank`.
///
/// **Why a counting sort suffices** (and beats every comparison /
/// LSB-radix variant we tried):
///
/// 1. The sort key is *bounded*. `lex_rank[term_id]` is in
///    `0..vocab_size`. The bench Zipfian column has ~10K vocab; even
///    a 10M-doc supertable column tops out around a few million —
///    the counts table fits comfortably in L2 either way.
/// 2. The secondary key is *free*. Within a partition file, all
///    triples for a fixed `term_id` are appended in strictly
///    increasing `doc_id` order (`add_doc` is called with monotonic
///    `local_doc_id` per `column_id`, and each call emits one
///    triple per unique term in iteration order over
///    `updated_terms`, with all triples for that doc emitted
///    contiguously). So a *stable* sort on `lex_rank[term_id]`
///    leaves the within-rank order as the original `doc_id` order
///    — exactly the `(lex_rank, doc_id)` order the finish-time
///    lex-order partition traversal needs.
/// 3. Counting sort is **one pass to histogram + one pass to
///    scatter**. No `O(log n)` compare chain (pdqsort), no 5–8
///    LSB-byte passes (radix), no comparator chasing `lex_rank`
///    twice per call. Two reads of every triple and one write.
///
/// **Memory shape**: `counts: Vec<u32>` of length
/// `vocab_size + 1` (~40 KiB at 10K vocab), plus the `out: Vec
/// <Triple>` of the same length as `triples` — the same size as the
/// radix variant's parallel-array workspace, just a single
/// allocation instead of three.
///
/// Falls back to `sort_unstable_by` for tiny inputs where the counts
/// allocation outweighs the algorithmic savings.
fn radix_sort_records_by_lex_rank<const N: usize>(triples: &mut Vec<[u32; N]>, lex_rank: &[u32]) {
    let n = triples.len();
    if n < RADIX_SORT_MIN_TRIPLES {
        triples.sort_unstable_by(|a, b| {
            lex_rank[triple_term_id(a) as usize]
                .cmp(&lex_rank[triple_term_id(b) as usize])
                .then(triple_doc_id(a).cmp(&triple_doc_id(b)))
        });
        return;
    }

    let vocab_size = lex_rank.len();
    // Histogram + prefix-sum table. `+1` so the final entry holds
    // `n` after prefix-sum, which simplifies the bounds check below.
    let mut offsets: Vec<u32> = vec![0u32; vocab_size + 1];

    // Pass 1: count triples per `lex_rank`. The hot inner step is
    // `lex_rank[term_id as usize]` — at `target-cpu=x86-64-v3` LLVM
    // lowers the strided load to an AVX2 `vpgatherdd` (8 ranks per
    // instruction). The histogram `offsets[rank] += 1` has a self-
    // dependency that prevents auto-vectorisation, but the loop
    // body is short enough that out-of-order issue absorbs the
    // latency.
    //
    // SAFETY (every `get_unchecked` in this function): term ids are
    // dense in `[0, vocab_size)` and `lex_rank` has `vocab_size`
    // entries, so `t[0] < lex_rank.len()`. `rank < vocab_size` indexes
    // `offsets` (length `vocab_size + 1`); the prefix sum keeps every
    // scatter `dst < n` (`out.len()`), and each `offsets[rank]` is
    // bumped at most its histogram count, so all accesses are in bounds.
    for t in triples.iter() {
        let rank = unsafe { *lex_rank.get_unchecked(t[0] as usize) } as usize;
        offsets[rank] = offsets[rank].wrapping_add(1);
    }

    // Pass 2 (cheap): convert counts into starting-offset table by
    // exclusive prefix sum. Runs over `vocab_size + 1` entries
    // (~10K on the bench) — well below the partition sort cost.
    let mut sum: u32 = 0;
    for c in offsets.iter_mut() {
        let tmp = *c;
        *c = sum;
        sum = sum.wrapping_add(tmp);
    }
    debug_assert_eq!(sum as usize, n, "histogram total != triple count");

    // Pass 3: scatter into `out`. Each triple lands at
    // `offsets[rank]`, then we bump that slot so the next triple
    // for the same rank lands immediately after. Because we walk
    // `triples` in arrival order and arrival order is `(doc_id,
    // term_id_within_doc)`, the within-rank order in `out` is the
    // partition's `doc_id` order — i.e. `(lex_rank, doc_id)`.
    let mut out: Vec<[u32; N]> = vec![[0u32; N]; n];
    for t in triples.iter() {
        let rank = unsafe { *lex_rank.get_unchecked(t[0] as usize) } as usize;
        let dst = unsafe { *offsets.get_unchecked(rank) } as usize;
        unsafe {
            *out.get_unchecked_mut(dst) = *t;
            *offsets.get_unchecked_mut(rank) = (dst as u32).wrapping_add(1);
        }
    }

    *triples = out;
}

/// Open a partition as a sorted-triple iterator. Picks the in-
/// memory path when the on-disk partition is at or below
/// `max_partition_bytes` and the external-merge path when it
/// isn't.
fn open_partition_sorted<const N: usize>(
    partition_path: &Path,
    max_partition_bytes: u64,
    scratch_dir: &Path,
    partition_label: &str,
    lex_rank: &[u32],
) -> Result<PartitionIter<N>, BuildError> {
    let len = fs::metadata(partition_path)?.len();
    if len <= max_partition_bytes {
        let mut triples = read_partition_records::<N>(partition_path)?;
        radix_sort_records_by_lex_rank(&mut triples, lex_rank);
        return Ok(PartitionIter::InMemory(triples.into_iter()));
    }

    // External merge: stream the partition in
    // `max_partition_bytes`-sized triple chunks, sort each chunk
    // in RAM, write sorted-chunk spill, then k-way merge. The
    // resident peak during this path is one chunk's triples plus
    // one triple per chunk file in the heap.
    let chunk_triples = (max_partition_bytes as usize) / mem::size_of::<[u32; N]>();
    let mut sorted_chunk_paths: Vec<PathBuf> = Vec::new();
    let mut r = BufReader::with_capacity(PARTITION_BUF_SIZE, File::open(partition_path)?);
    let mut chunk: Vec<[u32; N]> =
        Vec::with_capacity(chunk_triples.min(EXTERNAL_MERGE_CHUNK_CAP_TRIPLES));
    let mut chunk_idx: usize = 0;
    while let Some(t) = read_one_record::<_, N>(&mut r)? {
        chunk.push(t);
        if chunk.len() >= chunk_triples {
            spill_sorted_chunk(
                &mut chunk,
                scratch_dir,
                partition_label,
                chunk_idx,
                lex_rank,
                &mut sorted_chunk_paths,
            )?;
            chunk_idx += 1;
        }
    }
    if !chunk.is_empty() {
        spill_sorted_chunk(
            &mut chunk,
            scratch_dir,
            partition_label,
            chunk_idx,
            lex_rank,
            &mut sorted_chunk_paths,
        )?;
    }

    let mut readers: Vec<BufReader<File>> = Vec::with_capacity(sorted_chunk_paths.len());
    for p in &sorted_chunk_paths {
        readers.push(BufReader::with_capacity(PARTITION_BUF_SIZE, File::open(p)?));
    }
    let mut heap: BinaryHeap<MergeEntry<N>> = BinaryHeap::with_capacity(readers.len());
    for (idx, reader) in readers.iter_mut().enumerate() {
        if let Some(t) = read_one_record::<_, N>(reader)? {
            let term_id = triple_term_id(&t);
            let doc_id = triple_doc_id(&t);
            heap.push(MergeEntry {
                sort_key: pack_sort_key(lex_rank[term_id as usize], doc_id),
                rec: t,
                reader_idx: idx,
            });
        }
    }
    Ok(PartitionIter::Merge {
        readers,
        heap,
        _chunk_paths: sorted_chunk_paths,
    })
}

pub struct FtsBuilder {
    /// Tokenizer applied to columns registered via
    /// [`Self::register_column`] (the default). Per-column overrides go
    /// through [`Self::register_column_with_tokenizer`].
    default_tokenizer: Arc<dyn Tokenizer>,
    /// Tokenizer for each registered column, indexed by column_id — the
    /// analyzer that column's text is tokenized with at index time.
    /// Grown in lockstep with `columns`.
    column_tokenizers: Vec<Arc<dyn Tokenizer>>,
    columns: Vec<ColumnState>,
    /// Per-column posting accumulator. Each entry starts in
    /// `ColumnPostings::InRam` and transitions to `Spilled` exactly
    /// once when its accumulated bytes cross `spill_threshold_bytes`.
    /// Mirror of `VectorBuilder`'s `pre_spill_buffer` + `spill`.
    postings: Vec<ColumnPostings>,
    /// Scratch directory that owns all posting + FST spill files.
    /// Lazily populated — small builds (every column stays in RAM)
    /// never write here. Dropped after `finish_to` copies its
    /// contents into the output writer.
    scratch_dir: tempfile::TempDir,
    /// Per-column in-RAM accumulator budget. When a column's `InRam`
    /// state's `bytes` would cross this on an `add_doc`, that column
    /// is flushed to spill files and transitions to `Spilled` for the
    /// rest of the build. Default: `DEFAULT_SPILL_THRESHOLD_BYTES`.
    spill_threshold_bytes: usize,
    /// Number of hash partitions used in spill mode. Must be ≥ 1.
    /// Default: `DEFAULT_SPILL_PARTITIONS`.
    spill_partitions: usize,
    /// Per-partition in-RAM sort budget at finish time. Partitions
    /// exceeding this size on disk are sorted via external merge.
    /// Default: `DEFAULT_MAX_PARTITION_BYTES`.
    max_partition_bytes: u64,
    /// Tracks the number of distinct local_doc_ids ever seen by add_doc.
    /// Used as `n_docs` for the FTS blob header.
    n_docs: u32,
    /// Per-document term-frequency table for the in-RAM path. Draining
    /// keeps its bucket allocation, avoiding a fresh allocation and
    /// repeated growth for every document.
    ///
    /// Declared before `bump` so it drops first. Its transient `&str`
    /// keys borrow from that arena under the lifetime invariant described
    /// on [`DocTfMap`].
    doc_tf: DocTfMap,
    /// Per-doc chain heads for the positional capture path: term →
    /// index of its LAST occurrence in `doc_pos_chain`. Shares its
    /// `&'static str` keys with `doc_tf` (same bump arena, same
    /// lifetime invariant), so it is likewise declared before `bump`
    /// and cleared before the arena resets. Untouched for
    /// positionless columns.
    doc_pos_head: DocPosHeadMap,
    /// Per-doc occurrence chain: `(position, prev_index)` per token,
    /// `CHAIN_END` terminating each term's chain. Cleared per doc;
    /// capacity persists.
    doc_pos_chain: Vec<(u32, u32)>,
    /// Scratch for one term's positions while draining a doc (chain
    /// walk emits them descending; reversed here before encoding).
    pos_scratch: Vec<u32>,
    /// Scratch for one (term, doc) encoded position run on the
    /// spilled positional drain path (the in-RAM path encodes
    /// straight into the accumulator's per-term buffer instead).
    run_scratch: Vec<u8>,
    /// Per-shard bump arena reused across every `add_doc` call.
    /// Holds the transient `&str` keys of the per-doc tf hashmap.
    /// Reset at the top of each `add_doc` so the leftover bytes are
    /// invalidated before the next allocation; `Bump::reset` keeps
    /// the largest chunk so subsequent docs allocate in-place
    /// without going back to the system allocator.
    ///
    /// Only the in-RAM arm of `add_doc` consumes this — the spill
    /// arm interns tokens straight into the column's `term_to_id`
    /// and dedupes via a dense `Vec<u32>` (kept inside `ColumnPostings
    /// ::Spilled`) keyed by `term_id` instead.
    bump: Bump,
}

impl FtsBuilder {
    /// Construct a builder with the default scratch directory
    /// (under `$TMPDIR` via `tempfile::tempdir()`) and the default
    /// 256 MiB spill threshold. Mirror of `VectorBuilder::new`.
    ///
    /// Panics if creating the scratch tempdir fails — same policy
    /// as `VectorBuilder::new` for the same reason (no realistic
    /// recovery at construction time, preserves existing public
    /// API). Operators running large builds should prefer
    /// [`Self::with_scratch`] pointing at an instance-store NVMe
    /// partition.
    pub fn new(tokenizer: Arc<dyn Tokenizer>) -> Self {
        let scratch_dir = tempfile::tempdir().expect("create FtsBuilder scratch tempdir");
        Self::from_parts(tokenizer, scratch_dir)
    }

    /// Construct a builder with `scratch` as the scratch root. The
    /// directory must already exist and be writable. Used for
    /// benchmarks + production deployments that want to pin scratch
    /// to instance-store NVMe (`/mnt/nvme0/infino-build`, etc.)
    /// instead of the default `$TMPDIR` (which on EC2 is typically
    /// EBS-backed `/tmp`).
    ///
    /// Mirror of `VectorBuilder::with_scratch`, same return type
    /// (`Result<Self, BuildError>`).
    pub fn with_scratch(
        tokenizer: Arc<dyn Tokenizer>,
        scratch: PathBuf,
    ) -> Result<Self, BuildError> {
        let scratch_dir = tempfile::Builder::new()
            .prefix("infino-fts-")
            .tempdir_in(&scratch)?;
        Ok(Self::from_parts(tokenizer, scratch_dir))
    }

    fn from_parts(tokenizer: Arc<dyn Tokenizer>, scratch_dir: tempfile::TempDir) -> Self {
        Self {
            default_tokenizer: tokenizer,
            column_tokenizers: Vec::new(),
            columns: Vec::new(),
            postings: Vec::new(),
            scratch_dir,
            spill_threshold_bytes: DEFAULT_SPILL_THRESHOLD_BYTES,
            spill_partitions: DEFAULT_SPILL_PARTITIONS,
            max_partition_bytes: DEFAULT_MAX_PARTITION_BYTES,
            n_docs: 0,
            doc_tf: DocTfMap::with_hasher(FxBuildHasher),
            doc_pos_head: DocPosHeadMap::with_hasher(FxBuildHasher),
            doc_pos_chain: Vec::new(),
            pos_scratch: Vec::new(),
            run_scratch: Vec::new(),
            bump: Bump::new(),
        }
    }

    /// Override the per-column in-RAM accumulator budget. Once a
    /// column's accumulated posting bytes cross this threshold, that
    /// column flushes its in-memory map to spill files and runs the
    /// remainder of the build in spill mode.
    ///
    /// Mirror of `VectorBuilder::set_spill_threshold_bytes`, same
    /// `&mut self` setter shape. Threshold is read live at
    /// `add_doc` time, so changes after `register_column` *do*
    /// apply — unlike vector, which snapshots into each
    /// `ColumnState` at registration time.
    pub fn set_spill_threshold_bytes(&mut self, threshold: usize) {
        assert!(
            threshold > 0,
            "FtsBuilder: spill_threshold_bytes must be > 0"
        );
        self.spill_threshold_bytes = threshold;
    }

    /// Override the hash-partition count used when a column spills.
    /// Must be called *before* the first `register_column` — today
    /// partition files are created lazily on first spill, so a
    /// post-registration call would also work, but we require the
    /// pre-registration call for forward-compat with eager-create
    /// modes.
    pub fn set_spill_partitions(&mut self, n: usize) -> Result<(), BuildError> {
        if !self.columns.is_empty() {
            return Err(BuildError::Io(Error::new(
                ErrorKind::InvalidInput,
                "FtsBuilder::set_spill_partitions must be called before any register_column",
            )));
        }
        if n == 0 {
            return Err(BuildError::Io(Error::new(
                ErrorKind::InvalidInput,
                "FtsBuilder: spill_partitions must be ≥ 1",
            )));
        }
        // Partition selection is `term_id & (n - 1)` on the hot
        // spill path; that's only correct (uniform partitioning)
        // when `n` is a power of two. Reject non-PO2 values so the
        // hot path stays branch-free instead of falling back to
        // modulo.
        if !n.is_power_of_two() {
            return Err(BuildError::Io(Error::new(
                ErrorKind::InvalidInput,
                format!("FtsBuilder: spill_partitions must be a power of two; got {n}"),
            )));
        }
        self.spill_partitions = n;
        Ok(())
    }

    /// Override the per-partition in-RAM sort budget. Partitions
    /// whose on-disk size exceeds this value are sorted via external
    /// merge at finish time. Safe to call at any point before
    /// `finish`.
    pub fn set_max_partition_bytes(&mut self, bytes: u64) {
        assert!(bytes > 0, "FtsBuilder: max_partition_bytes must be > 0");
        self.max_partition_bytes = bytes;
    }

    /// Register an FTS column up-front, tokenized with the builder's
    /// default tokenizer. Returns its `column_id` (its index in
    /// declaration order).
    pub fn register_column(&mut self, name: String, positions: bool) -> Result<u32, BuildError> {
        let tokenizer = Arc::clone(&self.default_tokenizer);
        self.register_column_with_tokenizer(name, positions, tokenizer)
    }

    /// Register an FTS column tokenized with an explicit `tokenizer`,
    /// overriding the builder default. Returns its `column_id`. Lets
    /// each column carry its own analyzer (per-field analysis).
    pub fn register_column_with_tokenizer(
        &mut self,
        name: String,
        positions: bool,
        tokenizer: Arc<dyn Tokenizer>,
    ) -> Result<u32, BuildError> {
        if name.as_bytes().contains(&FST_SEPARATOR) {
            return Err(BuildError::ReservedSeparatorInColumnName(name));
        }
        if name.starts_with(format::RESERVED_PREFIX) {
            return Err(BuildError::ReservedPrefixInColumnName(name));
        }
        if self.columns.iter().any(|c| c.name == name) {
            return Err(BuildError::DuplicateColumnName(name));
        }
        let column_id = self.columns.len() as u32;
        self.columns.push(ColumnState {
            name,
            doc_lengths: Vec::new(),
            total_tokens: 0,
            positions,
        });
        self.postings.push(ColumnPostings::new());
        self.column_tokenizers.push(tokenizer);
        Ok(column_id)
    }

    /// Open spill partition files for a column and return them.
    /// Called the first time a column's in-RAM accumulator crosses
    /// `spill_threshold_bytes`.
    fn open_partitions_for_column<const N: usize>(
        scratch_dir: &Path,
        column_id: u32,
        n_partitions: usize,
    ) -> Result<Vec<SpillPartition<N>>, BuildError> {
        let mut partitions = Vec::with_capacity(n_partitions);
        for partition in 0..n_partitions {
            let path = scratch_dir.join(format!("fts_col{column_id}_part{partition}.bin"));
            let file = File::create(&path)?;
            partitions.push(SpillPartition {
                path,
                writer: Some(BufWriter::with_capacity(PARTITION_BUF_SIZE, file)),
                batch: Vec::with_capacity(SPILL_BATCH_TRIPLES),
            });
        }
        Ok(partitions)
    }

    /// Open one positions blob per spill partition for a positional
    /// column. Sibling of
    /// [`open_partitions_for_column`](Self::open_partitions_for_column);
    /// the blob at index `p` carries the position runs of every record
    /// routed to partition `p`.
    fn open_position_blobs_for_column(
        scratch_dir: &Path,
        column_id: u32,
        n_partitions: usize,
    ) -> Result<Vec<PartitionPositions>, BuildError> {
        let mut blobs = Vec::with_capacity(n_partitions);
        for partition in 0..n_partitions {
            let path = scratch_dir.join(format!("fts_col{column_id}_part{partition}.pos.bin"));
            let file = File::create(&path)?;
            blobs.push(PartitionPositions {
                path,
                writer: Some(BufWriter::with_capacity(PARTITION_BUF_SIZE, file)),
                len: 0,
            });
        }
        Ok(blobs)
    }

    /// Positional twin of
    /// [`flush_in_ram_to_partitions`](Self::flush_in_ram_to_partitions):
    /// drains the term → postings map *and* the parallel term →
    /// position-runs map. Each `(doc, tf)` pair's run — delimited by
    /// its `tf` varints within the term's concatenated buffer — is
    /// appended to the partition's positions blob, and the record
    /// carries the run's byte offset in its trailing lanes.
    #[allow(clippy::too_many_arguments)]
    fn flush_in_ram_to_positional_partitions(
        terms: FxHashMap<Box<str>, Vec<(u32, u32)>>,
        mut pos_runs: FxHashMap<Box<str>, Vec<u8>>,
        partitions: &mut [SpillPartition<POSITIONAL_RECORD_LANES>],
        blobs: &mut [PartitionPositions],
        term_to_id: &mut TermIdMap,
        id_to_term: &mut Vec<&'static str>,
        arena: &Bump,
    ) -> Result<(), BuildError> {
        let n_part = partitions.len();
        debug_assert_eq!(n_part, blobs.len(), "one blob per partition");
        debug_assert!(
            n_part.is_power_of_two(),
            "spill_partitions must be a power of 2; got {n_part}"
        );
        let mask = n_part - 1;
        for (term, postings) in terms {
            let (term_id, _is_new) = intern_term_id(term_to_id, id_to_term, arena, &term);
            let p = (term_id as usize) & mask;
            let runs = pos_runs
                .remove(&term)
                .expect("positional term accumulated a position run");
            let blob = &mut blobs[p];
            let writer = blob
                .writer
                .as_mut()
                .expect("positions blob writer is open before finish");
            let mut at: usize = 0;
            for (doc_id, tf) in postings {
                let run_start = at;
                skip_run(&runs, &mut at, tf).expect("builder-encoded runs are well-formed");
                writer.write_all(&runs[run_start..at])?;
                let pos_off = blob.len;
                blob.len += (at - run_start) as u64;
                let (lo, hi) = pos_off_lanes(pos_off);
                push_record_batched(&mut partitions[p], [term_id, doc_id, tf, lo, hi])?;
            }
            debug_assert_eq!(at, runs.len(), "runs must cover exactly the pairs");
        }
        Ok(())
    }

    /// Drain an in-RAM term → postings map into spill partitions,
    /// assigning a fresh `term_id` per term as it's first seen.
    /// Used once per column at the moment that column crosses the
    /// spill threshold. After this returns, the map is empty
    /// (already dropped by the caller) and all records live in the
    /// partition files as fixed-size 12-byte triples.
    ///
    /// `term_to_id` + `id_to_term` are populated with this
    /// column's vocabulary; subsequent `add_doc` calls reuse them
    /// to intern any new terms they see.
    fn flush_in_ram_to_partitions(
        terms: FxHashMap<Box<str>, Vec<(u32, u32)>>,
        partitions: &mut [SpillPartition<PLAIN_RECORD_LANES>],
        term_to_id: &mut TermIdMap,
        id_to_term: &mut Vec<&'static str>,
        arena: &Bump,
    ) -> Result<(), BuildError> {
        let n_part = partitions.len();
        debug_assert!(
            n_part.is_power_of_two(),
            "spill_partitions must be a power of 2; got {n_part}"
        );
        let mask = n_part - 1;
        for (term, postings) in terms {
            // Drain-time intern: every drained term is by construction
            // a fresh id (term_to_id was empty when the transition
            // started). The `is_new` flag is unused here; the dense-
            // array sizing is handled by the caller pre-growing
            // `dense_doc_tf` to `id_to_term.len()` after this returns.
            let (term_id, _is_new) = intern_term_id(term_to_id, id_to_term, arena, &term);
            let p = (term_id as usize) & mask;
            for (doc_id, tf) in postings {
                push_record_batched(&mut partitions[p], [term_id, doc_id, tf])?;
            }
        }
        Ok(())
    }

    /// Index `text` for `(column_id, local_doc_id)`.
    ///
    /// Caller must call this once per (doc, registered FTS column) pair,
    /// with monotonically increasing `local_doc_id` per column. Multiple
    /// occurrences of the same term in `text` increment the term-frequency
    /// for that doc.
    pub fn add_doc(
        &mut self,
        column_id: u32,
        local_doc_id: u32,
        text: &str,
    ) -> Result<(), BuildError> {
        let col_idx = column_id as usize;
        if col_idx >= self.columns.len() {
            return Err(BuildError::FtsColumnTypeInvalid {
                column: format!("(unregistered column_id {column_id})"),
                actual: "n/a".to_string(),
            });
        }

        // The contract is that `local_doc_id` increments by 1 per
        // (per-column) call, starting at 0. `finish()` indexes
        // `col.doc_lengths[doc_id]` with a doc_id from the posting list,
        // so the doc_lengths vec must be in sync with the local_doc_id
        // axis. Catch contract violations early in debug builds;
        // release skips the check.
        debug_assert!(
            local_doc_id as usize == self.columns[col_idx].doc_lengths.len(),
            "FtsBuilder::add_doc: local_doc_id ({local_doc_id}) must equal \
             this column's next index ({}); doc_ids must be consecutive \
             from 0 within a column",
            self.columns[col_idx].doc_lengths.len(),
        );

        // Dispatch by variant. Re-destructured inside each helper
        // so the helper can field-split-borrow `self.postings`,
        // `self.columns`, and (for in-RAM) `self.bump` without
        // routing through an enum field reference held across the
        // call.
        if self.postings[col_idx].is_spilled() {
            self.add_doc_spilled(col_idx, local_doc_id, text)
        } else {
            self.add_doc_inram(col_idx, local_doc_id, text)
        }
    }

    /// Spilled-mode hot path. Per-token cost: intern lookup + dense-
    /// array tf bump; per-doc cost: drain `updated_terms` into the
    /// partition writers as 12-byte triples. Invariant maintained:
    /// `dense_doc_tf.len() == id_to_term.len()` and
    /// `dense_doc_tf[tid] != 0 iff tid in updated_terms`. See the
    /// inline `SAFETY` comments for the bounds-check elisions.
    #[inline(always)]
    fn add_doc_spilled(
        &mut self,
        col_idx: usize,
        local_doc_id: u32,
        text: &str,
    ) -> Result<(), BuildError> {
        // Downcast once per call so the tokenize_each_inline fast
        // path is reachable. See the original `add_doc` for the
        // ~150M dyn-dispatch savings this buys on the 1M-doc bench.
        let tokenizer = &self.column_tokenizers[col_idx];
        let ascii_tok = tokenizer
            .as_ref()
            .as_any()
            .downcast_ref::<AsciiLowerTokenizer>();
        let mut tokens_in_doc: u64 = 0;

        let positional = self.columns[col_idx].positions;
        let col_post = &mut self.postings[col_idx];
        let (
            store,
            term_to_id,
            id_to_term,
            dense_doc_tf,
            dense_doc_poshead,
            updated_terms,
            term_arena,
        ) = match col_post {
            ColumnPostings::Spilled {
                partitions,
                term_to_id,
                id_to_term,
                dense_doc_tf,
                dense_doc_poshead,
                updated_terms,
                term_arena,
            } => (
                partitions,
                term_to_id,
                id_to_term,
                dense_doc_tf,
                dense_doc_poshead,
                updated_terms,
                term_arena,
            ),
            ColumnPostings::InRam { .. } => {
                unreachable!("add_doc_spilled called on InRam column")
            }
        };

        let n_part = store.n_partitions();
        debug_assert!(
            n_part.is_power_of_two(),
            "spill_partitions must be a power of 2"
        );
        let mask = n_part - 1;

        updated_terms.clear();
        let mut pos_overflow = false;
        if !positional {
            let mut on_token = |tok: &str| {
                tokens_in_doc += 1;
                let (term_id, is_new) = intern_term_id(term_to_id, id_to_term, term_arena, tok);
                let idx = term_id as usize;
                if is_new {
                    debug_assert_eq!(idx, dense_doc_tf.len());
                    dense_doc_tf.push(0);
                }
                // SAFETY: lockstep invariant between `dense_doc_tf`
                // and `id_to_term` (see type-level docs above) holds
                // here: `intern_term_id` returns `term_id <
                // id_to_term.len()` and we just `push(0)` on `is_new`
                // so `idx < dense_doc_tf.len()`.
                let slot = unsafe { dense_doc_tf.get_unchecked_mut(idx) };
                if *slot == 0 {
                    updated_terms.push(term_id);
                }
                *slot += 1;
            };
            if let Some(ascii) = ascii_tok {
                ascii.tokenize_each_inline(text, &mut on_token);
            } else {
                tokenizer.tokenize_each(text, &mut on_token);
            }
        } else {
            // Positional twin of the scan: same interning + dense-tf
            // bump, plus each occurrence links its position into the
            // per-doc chain (the same chain the in-RAM path uses),
            // headed per term in `dense_doc_poshead`.
            self.doc_pos_chain.clear();
            let doc_pos_chain = &mut self.doc_pos_chain;
            // `record` interns the token, bumps its tf, and links its
            // `position` into the per-doc chain. `position` is the
            // gap-inclusive ordinal — a token the tokenizer drops still
            // advances it, so a phrase never treats the tokens on either
            // side of a dropped word as adjacent. The doc length
            // (`tokens_in_doc`) counts only *emitted* tokens, bumped by
            // the caller below, so it stays identical to the
            // positionless build; the two coincide only when nothing is
            // dropped.
            let mut record = |tok: &str, position: u64| {
                let (term_id, is_new) = intern_term_id(term_to_id, id_to_term, term_arena, tok);
                let idx = term_id as usize;
                if is_new {
                    debug_assert_eq!(idx, dense_doc_tf.len());
                    dense_doc_tf.push(0);
                    dense_doc_poshead.push(CHAIN_END);
                }
                // SAFETY: same lockstep invariant as the positionless
                // closure; `dense_doc_poshead` is pushed in the same
                // `is_new` branch so it shares the bound.
                let slot = unsafe { dense_doc_tf.get_unchecked_mut(idx) };
                if *slot == 0 {
                    updated_terms.push(term_id);
                }
                *slot += 1;
                if position > u32::MAX as u64 {
                    // Positions are u32 ordinals; checked after the
                    // scan and surfaced as a hard build error.
                    pos_overflow = true;
                    return;
                }
                let chain_idx = doc_pos_chain.len() as u32;
                let head = unsafe { dense_doc_poshead.get_unchecked_mut(idx) };
                doc_pos_chain.push((position as u32, *head));
                *head = chain_idx;
            };
            if let Some(ascii) = ascii_tok {
                // Gap-aware: a dropped (non-ASCII) run advances the
                // position ordinal but emits no token.
                ascii.tokenize_each_inline_positioned(text, |tok, position| {
                    record(tok, position);
                    tokens_in_doc += 1;
                });
            } else {
                // A custom tokenizer can't report dropped tokens through
                // the current trait, so positions are plain emission
                // ordinals; a tokenizer that silently drops tokens will
                // not leave phrase gaps (see the `Tokenizer` trait docs).
                tokenizer.tokenize_each(text, &mut |tok| {
                    record(tok, tokens_in_doc);
                    tokens_in_doc += 1;
                });
            }
        }
        if pos_overflow {
            return Err(BuildError::PositionOverflow {
                column: self.columns[col_idx].name.clone(),
            });
        }

        // `self.columns[col_idx]` is a disjoint field from
        // `self.postings[col_idx]`, so split-borrow legal.
        let col = &mut self.columns[col_idx];
        let dl_clamped: u32 = tokens_in_doc.min(u32::MAX as u64) as u32;
        col.doc_lengths.push(dl_clamped);
        col.total_tokens = col.total_tokens.saturating_add(tokens_in_doc);
        let docs_now = local_doc_id.saturating_add(1);
        if docs_now > self.n_docs {
            self.n_docs = docs_now;
        }

        // Per-doc drain: emit one fixed-size record per touched term,
        // then zero the dense slot to restore the `dense_doc_tf[tid]
        // != 0 iff in updated_terms` invariant. The positional store
        // additionally walks the term's chain, appends its run to the
        // partition's positions blob, and rides the run's byte offset
        // in the record's trailing lanes.
        //
        // SAFETY: `p = term_id & mask` where `mask = n_partitions - 1`
        // (power-of-two enforced), so `p` indexes the partition vec;
        // the dense-slot index `idx` was already validated above.
        match store {
            SpillStore::Plain(partitions) => {
                for &term_id in updated_terms.iter() {
                    let idx = term_id as usize;
                    let slot = unsafe { dense_doc_tf.get_unchecked_mut(idx) };
                    let tf = *slot;
                    *slot = 0;
                    let p = (term_id as usize) & mask;
                    let partition = unsafe { partitions.get_unchecked_mut(p) };
                    push_record_batched(partition, [term_id, local_doc_id, tf])?;
                }
            }
            SpillStore::Positional { partitions, blobs } => {
                let doc_pos_chain = &self.doc_pos_chain;
                let pos_scratch = &mut self.pos_scratch;
                let run_buf = &mut self.run_scratch;
                for &term_id in updated_terms.iter() {
                    let idx = term_id as usize;
                    let slot = unsafe { dense_doc_tf.get_unchecked_mut(idx) };
                    let tf = *slot;
                    *slot = 0;
                    let head_slot = unsafe { dense_doc_poshead.get_unchecked_mut(idx) };
                    let head = *head_slot;
                    *head_slot = CHAIN_END;
                    pos_scratch.clear();
                    let mut at = head;
                    while at != CHAIN_END {
                        let (pos, prev) = doc_pos_chain[at as usize];
                        pos_scratch.push(pos);
                        at = prev;
                    }
                    pos_scratch.reverse();
                    debug_assert_eq!(pos_scratch.len() as u32, tf, "chain length must equal tf");
                    run_buf.clear();
                    encode_run(run_buf, pos_scratch);
                    let p = (term_id as usize) & mask;
                    let blob = &mut blobs[p];
                    let pos_off = blob.len;
                    blob.writer
                        .as_mut()
                        .expect("positions blob writer is open before finish")
                        .write_all(run_buf)?;
                    blob.len += run_buf.len() as u64;
                    let (lo, hi) = pos_off_lanes(pos_off);
                    let partition = unsafe { partitions.get_unchecked_mut(p) };
                    push_record_batched(partition, [term_id, local_doc_id, tf, lo, hi])?;
                }
            }
        }

        Ok(())
    }

    /// In-RAM hot path. Stages tokens into a per-doc `tf_per_term`
    /// hashbrown map (`&str` keys backed by `self.bump`), then
    /// drains into the column's `terms: HashMap<Box<str>, …>`
    /// posting accumulator. On a Zipfian corpus ~80-95% of tokens
    /// are repeats within the same doc, so the bump-arena-keyed
    /// raw-entry probe pays off vs a `Box<str>`-keyed map.
    ///
    /// After the drain, if the column's accumulated bytes cross
    /// `self.spill_threshold_bytes`, transitions it to
    /// `ColumnPostings::Spilled` (one-shot — every subsequent
    /// `add_doc` for this column routes through
    /// [`Self::add_doc_spilled`]).
    #[inline(always)]
    fn add_doc_inram(
        &mut self,
        col_idx: usize,
        local_doc_id: u32,
        text: &str,
    ) -> Result<(), BuildError> {
        let tokenizer = &self.column_tokenizers[col_idx];
        let ascii_tok = tokenizer
            .as_ref()
            .as_any()
            .downcast_ref::<AsciiLowerTokenizer>();
        let mut tokens_in_doc: u64 = 0;
        let positional = self.columns[col_idx].positions;

        // Clear borrowed keys before resetting their backing arena.
        // Both containers retain their allocations for the next doc.
        self.doc_tf.clear();
        self.bump.reset();
        let bump = &self.bump;

        // Per-doc dedup map. `hashbrown::raw_entry_mut` probes
        // with the *borrowed* `&str` token from the tokenizer's
        // input slice and only pays the `bump.alloc_str` copy on
        // the miss path. Hit-path cost: hash + load + increment.
        let tf_per_term = &mut self.doc_tf;
        if !positional {
            let mut on_token = |tok: &str| {
                tokens_in_doc += 1;
                let hash = compute_hash(tf_per_term.hasher(), tok);
                match tf_per_term
                    .raw_entry_mut()
                    .from_hash(hash, |existing| *existing == tok)
                {
                    RawEntryMut::Occupied(mut e) => {
                        *e.get_mut() += 1;
                    }
                    RawEntryMut::Vacant(e) => {
                        // Miss path: copy borrowed token bytes into
                        // the bump arena so the key outlives the
                        // tokenizer's input lifetime, then widen the
                        // bump ref to `'static` tied to the scratch
                        // table's lifetime.
                        let bumped: &str = bump.alloc_str(tok);
                        // SAFETY: the `'static` tag is a lie — the real
                        // lifetime is `self.bump`. The table is drained below,
                        // cleared before the arena is reset on the next call,
                        // and declared before `bump` so it also drops first if
                        // unwinding leaves entries behind.
                        let extended: &'static str = unsafe { std::mem::transmute(bumped) };
                        e.insert_hashed_nocheck(hash, extended, 1);
                    }
                }
            };
            if let Some(ascii) = ascii_tok {
                ascii.tokenize_each_inline(text, &mut on_token);
            } else {
                tokenizer.tokenize_each(text, &mut on_token);
            }
        } else {
            // Positional variant of the scan: same tf accumulation,
            // plus each occurrence links its token position into a
            // per-doc chained list headed per term. Chained (not
            // sorted): O(1) per token, and the drain below walks each
            // term's chain once. A separate closure so the
            // positionless hot path above stays byte-identical.
            self.doc_pos_head.clear();
            self.doc_pos_chain.clear();
            let doc_pos_head = &mut self.doc_pos_head;
            let doc_pos_chain = &mut self.doc_pos_chain;
            let mut pos_overflow = false;
            // `record` accumulates tf and links each occurrence's
            // `position` into the per-doc chain. `position` is the
            // gap-inclusive ordinal (a dropped token still advances it,
            // so phrase adjacency isn't faked across a dropped word);
            // the doc length (`tokens_in_doc`) counts only emitted
            // tokens, bumped by the caller below — identical to the
            // positionless build.
            let mut record = |tok: &str, position: u64| {
                let hash = compute_hash(tf_per_term.hasher(), tok);
                let key: &'static str = match tf_per_term
                    .raw_entry_mut()
                    .from_hash(hash, |existing| *existing == tok)
                {
                    RawEntryMut::Occupied(mut e) => {
                        *e.get_mut() += 1;
                        e.key()
                    }
                    RawEntryMut::Vacant(e) => {
                        let bumped: &str = bump.alloc_str(tok);
                        // SAFETY: same lifetime argument as the
                        // positionless closure above — the map (and
                        // the chain-head map, which shares its keys)
                        // is drained/cleared before the arena resets.
                        let extended: &'static str = unsafe { std::mem::transmute(bumped) };
                        e.insert_hashed_nocheck(hash, extended, 1);
                        extended
                    }
                };
                if position > u32::MAX as u64 {
                    // Positions are u32 ordinals; a doc this long is
                    // a hard build error (checked after the scan).
                    pos_overflow = true;
                    return;
                }
                let idx = doc_pos_chain.len() as u32;
                let prev = doc_pos_head.insert(key, idx).unwrap_or(CHAIN_END);
                doc_pos_chain.push((position as u32, prev));
            };
            if let Some(ascii) = ascii_tok {
                // Gap-aware: a dropped (non-ASCII) run advances the
                // position ordinal but emits no token.
                ascii.tokenize_each_inline_positioned(text, |tok, position| {
                    record(tok, position);
                    tokens_in_doc += 1;
                });
            } else {
                // A custom tokenizer can't report dropped tokens through
                // the current trait, so positions are plain emission
                // ordinals (see the `Tokenizer` trait docs).
                tokenizer.tokenize_each(text, &mut |tok| {
                    record(tok, tokens_in_doc);
                    tokens_in_doc += 1;
                });
            }
            if pos_overflow {
                return Err(BuildError::PositionOverflow {
                    column: self.columns[col_idx].name.clone(),
                });
            }
        }

        let col = &mut self.columns[col_idx];
        let dl_clamped: u32 = tokens_in_doc.min(u32::MAX as u64) as u32;
        col.doc_lengths.push(dl_clamped);
        col.total_tokens = col.total_tokens.saturating_add(tokens_in_doc);
        let docs_now = local_doc_id.saturating_add(1);
        if docs_now > self.n_docs {
            self.n_docs = docs_now;
        }

        let column_id = col_idx as u32;
        let col_post = &mut self.postings[col_idx];
        let (terms, pos_runs, bytes) = match col_post {
            ColumnPostings::InRam {
                terms,
                pos_runs,
                bytes,
            } => (terms, pos_runs, bytes),
            ColumnPostings::Spilled { .. } => {
                unreachable!("add_doc_inram called on Spilled column")
            }
        };
        // Lookup with `get_mut(&str)` first — borrowed probe
        // against a `Box<str>` key, no allocation on hits. Only
        // the miss path constructs a `Box::<str>::from(term)` for
        // insertion. Bytes accounting folds into the same loop.
        let doc_pos_head = &self.doc_pos_head;
        let doc_pos_chain = &self.doc_pos_chain;
        let pos_scratch = &mut self.pos_scratch;
        let mut new_bytes: usize = 0;
        for (term, tf) in tf_per_term.drain() {
            let term_len = term.len();
            match terms.get_mut(term) {
                Some(acc) => {
                    acc.push((local_doc_id, tf));
                    new_bytes = new_bytes.saturating_add(ACCUM_POSTING_BYTES);
                }
                None => {
                    terms.insert(Box::<str>::from(term), vec![(local_doc_id, tf)]);
                    new_bytes = new_bytes.saturating_add(
                        ACCUM_NEW_TERM_FIXED_BYTES + term_len + ACCUM_POSTING_BYTES,
                    );
                }
            }
            if positional {
                // Walk this term's per-doc chain (positions come out
                // descending — the chain heads at the LAST occurrence),
                // reverse to ascending, and append the delta-varint run
                // to the term's run buffer. Pair order and run order
                // stay aligned because both append once per (term, doc)
                // in this same loop.
                let head = doc_pos_head.get(term).copied().unwrap_or(CHAIN_END);
                debug_assert_ne!(head, CHAIN_END, "tf term missing from position chain");
                pos_scratch.clear();
                let mut at = head;
                while at != CHAIN_END {
                    let (p, prev) = doc_pos_chain[at as usize];
                    pos_scratch.push(p);
                    at = prev;
                }
                pos_scratch.reverse();
                debug_assert_eq!(pos_scratch.len() as u32, tf, "chain length must equal tf");
                match pos_runs.get_mut(term) {
                    Some(run) => {
                        let before = run.len();
                        encode_run(run, pos_scratch);
                        new_bytes = new_bytes.saturating_add(run.len() - before);
                    }
                    None => {
                        let mut run = Vec::new();
                        encode_run(&mut run, pos_scratch);
                        new_bytes = new_bytes
                            .saturating_add(ACCUM_NEW_TERM_FIXED_BYTES + term_len + run.len());
                        pos_runs.insert(Box::<str>::from(term), run);
                    }
                }
            }
        }
        let new_total = bytes.saturating_add(new_bytes);

        if new_total > self.spill_threshold_bytes {
            // Crossed the threshold. Drain the in-RAM map into a
            // fresh set of spill files for this column, build the
            // interner from the drained vocab, transition to
            // `Spilled` so subsequent `add_doc` calls route to
            // `add_doc_spilled`.
            let drained = mem::take(terms);
            let drained_pos_runs = mem::take(pos_runs);
            let term_arena = Bump::new();
            let mut term_to_id: TermIdMap = TermIdMap::default();
            // Pre-size to the exact post-flush vocab.
            let mut id_to_term: Vec<&'static str> = Vec::with_capacity(drained.len());
            let store = match positional {
                false => {
                    let mut partitions = Self::open_partitions_for_column(
                        self.scratch_dir.path(),
                        column_id,
                        self.spill_partitions,
                    )?;
                    Self::flush_in_ram_to_partitions(
                        drained,
                        &mut partitions,
                        &mut term_to_id,
                        &mut id_to_term,
                        &term_arena,
                    )?;
                    SpillStore::Plain(partitions)
                }
                true => {
                    let mut partitions = Self::open_partitions_for_column(
                        self.scratch_dir.path(),
                        column_id,
                        self.spill_partitions,
                    )?;
                    let mut blobs = Self::open_position_blobs_for_column(
                        self.scratch_dir.path(),
                        column_id,
                        self.spill_partitions,
                    )?;
                    Self::flush_in_ram_to_positional_partitions(
                        drained,
                        drained_pos_runs,
                        &mut partitions,
                        &mut blobs,
                        &mut term_to_id,
                        &mut id_to_term,
                        &term_arena,
                    )?;
                    SpillStore::Positional { partitions, blobs }
                }
            };
            let dense_doc_tf = vec![0u32; id_to_term.len()];
            let dense_doc_poshead = match positional {
                true => vec![CHAIN_END; id_to_term.len()],
                false => Vec::new(),
            };
            let updated_terms: Vec<u32> = Vec::new();
            *col_post = ColumnPostings::Spilled {
                partitions: store,
                term_to_id,
                id_to_term,
                dense_doc_tf,
                dense_doc_poshead,
                updated_terms,
                // Declared last in the variant so it drops last;
                // see `TermIdMap` doc for the lifetime invariant.
                term_arena,
            };
        } else {
            *bytes = new_total;
        }

        Ok(())
    }

    /// Finalise and emit the FTS blob bytes. Consumes the builder.
    ///
    /// Returns `BuildError::Io` for scratch IO failures that can
    /// occur on the spill path (partition write/read, streaming-FST
    /// scratch file, posting region scratch file). Mirror of
    /// `VectorBuilder::finish`, which has the same return type for
    /// the same reason.
    pub fn finish(self) -> Result<Vec<u8>, BuildError> {
        let mut blob = Vec::new();
        self.finish_to(&mut blob)?;
        Ok(blob)
    }

    /// Streaming variant: write the final FTS blob progressively to `w`.
    ///
    /// Two finish paths, picked automatically by inspecting whether
    /// any column has spilled:
    ///
    /// - **In-RAM finish** (no column spilled): per-column term maps
    ///   are sorted and drained term-by-term, encoded postings flow
    ///   to a posting-region scratch file, and the FST is built in
    ///   RAM via `DictBuilder`. Small-build path; mirrors the
    ///   in-RAM `VectorBuilder` finish.
    ///
    /// - **Spilled finish** (any column spilled): every column's
    ///   posting source — in-RAM map (for columns that stayed below
    ///   threshold) or partition files (for spilled columns) — is
    ///   normalised into a sorted record stream, then column-by-
    ///   column those streams feed a *streaming* FST builder writing
    ///   to a scratch file. The FST never lives entirely in RAM.
    ///   Mirrors the spilled `VectorBuilder` finish.
    ///
    /// Final blob assembly is byte-identical between the two paths
    /// (regression-gated by
    /// `build_above_threshold_spills_and_matches_in_ram_byte_for_byte`).
    pub fn finish_to<W: Write>(self, w: W) -> Result<(), BuildError> {
        // Dispatch to the path that matches the builder's current
        // state. The two paths share `assemble_and_write_blob` as
        // their tail, so the output blob is byte-identical for
        // builds that *could* be served by either (regression-
        // gated by `build_above_threshold_spills_and_matches_in_
        // ram_byte_for_byte`).
        if self.postings.iter().any(|c| c.is_spilled()) {
            self.finish_to_spilled(w)
        } else {
            self.finish_to_inram(w)
        }
    }

    /// In-RAM finish path: every column's accumulated `terms` map
    /// stayed under `spill_threshold_bytes`, so the FST is built in
    /// one shot via [`DictBuilder`] (no scratch FST file), no
    /// partition flush runs, and the per-column emit loop only ever
    /// sees the `InRam` variant.
    ///
    /// This is the production rayon-sharded path for builds whose
    /// per-shard data fits below the spill threshold — the case the
    /// 1M-doc Zipfian bench measures.
    fn finish_to_inram<W: Write>(self, mut w: W) -> Result<(), BuildError> {
        let FtsBuilder {
            default_tokenizer: _,
            column_tokenizers: _,
            columns,
            postings,
            scratch_dir,
            spill_threshold_bytes: _,
            spill_partitions: _,
            max_partition_bytes: _,
            n_docs,
            doc_tf,
            doc_pos_head,
            doc_pos_chain: _,
            pos_scratch: _,
            run_scratch: _,
            bump,
        } = self;
        drop(doc_tf);
        drop(doc_pos_head);
        drop(bump);

        let n_columns = columns.len() as u32;
        let mut n_terms_total_usize: usize = 0;

        // Build the per-column work list, sorted by lex name. Drained
        // by value below so each column's in-RAM map is dropped the
        // instant its terms have been emitted. Mirror of vector's
        // `columns.into_iter().enumerate()` pattern.
        let mut work: Vec<(usize, ColumnState, ColumnPostings)> = columns
            .into_iter()
            .zip(postings)
            .enumerate()
            .map(|(orig_idx, (state, posting_state))| (orig_idx, state, posting_state))
            .collect();
        work.sort_unstable_by(|a, b| a.1.name.cmp(&b.1.name));

        let mut avgdl_per_col: Vec<f32> = vec![0.0; n_columns as usize];
        for (orig_idx, state, _) in &work {
            let n = state.doc_lengths.len() as u64;
            avgdl_per_col[*orig_idx] = if n == 0 {
                0.0
            } else {
                (state.total_tokens as f32) / (n as f32)
            };
        }
        let scratch_path = scratch_dir.path().to_path_buf();
        // Posting body scratch file. Encoded posting blocks for every
        // (column, term) flow here in lex order, then get streamed
        // through to `w` at assembly time.
        let postings_path = scratch_path.join("infino_fts_postings.bin");
        let mut postings_writer = BufWriter::new(File::create(&postings_path)?);
        let mut postings_len: u64 = 0;
        let mut postings_crc_acc: u32 = 0;
        // Every blob carries a positions region (empty when no column
        // records positions) — new code always writes the v2 layout.
        let mut positions_sink = PositionsSink::create(&scratch_path)?;
        let mut key_buf: Vec<u8> = Vec::with_capacity(64);
        let mut term_scratch = TermScratch::default();
        let mut finish_profile = FinishProfile::from_config();

        // The in-RAM path's FST sink: collect (key, value) into a
        // `DictBuilder` and serialise once at assembly time. No
        // scratch file, no streaming.
        let mut fst_inram = DictBuilder::new();

        let mut doc_lengths_by_orig_col: Vec<Option<Vec<u32>>> =
            (0..n_columns as usize).map(|_| None).collect();

        for (orig_col_idx, col_state, posting_state) in work.drain(..) {
            let ColumnState {
                name: col_name,
                doc_lengths: col_doc_lengths_owned,
                total_tokens: _,
                positions: col_positions,
            } = col_state;
            let col_name_bytes = col_name.as_bytes();
            let avgdl = avgdl_per_col[orig_col_idx];
            let col_doc_lengths: &[u32] = &col_doc_lengths_owned;

            // In-RAM path invariant: dispatcher checked
            // `!any_spilled`, so every column is `InRam`.
            let (terms, mut pos_runs) = match posting_state {
                ColumnPostings::InRam {
                    terms,
                    pos_runs,
                    bytes: _,
                } => (terms, pos_runs),
                ColumnPostings::Spilled { .. } => unreachable!(
                    "finish_to_inram dispatched on !any_spilled; \
                     Spilled column cannot appear here"
                ),
            };

            // Sort term keys; per-term doc lists are already in
            // insertion order (monotonically increasing local_doc_id
            // per the `add_doc` contract), so no per-list sort
            // needed. pdqsort: dictionary entries for one in-RAM
            // column can run into millions; stability is unnecessary
            // because keys are unique.
            type InRamEntries = Vec<(Box<str>, Vec<(u32, u32)>)>;
            let mut entries: InRamEntries = terms.into_iter().collect();
            entries.sort_unstable_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
            for (term, postings) in entries {
                // A positional column hands the term's runs (removed
                // by value so the map shrinks as it drains) plus the
                // shared region sink to the encoder.
                let term_runs: Vec<u8> = match col_positions {
                    true => pos_runs
                        .remove(&term)
                        .expect("positional term accumulated a position run"),
                    false => Vec::new(),
                };
                let term_positions = match col_positions {
                    true => Some((&mut positions_sink, term_runs.as_slice())),
                    false => None,
                };
                encode_and_emit_term(
                    &term,
                    &postings,
                    col_name_bytes,
                    col_doc_lengths,
                    avgdl,
                    n_docs,
                    &mut key_buf,
                    &mut postings_writer,
                    &mut postings_crc_acc,
                    &mut postings_len,
                    Some(&mut fst_inram),
                    None,
                    term_positions,
                    &mut finish_profile,
                    &mut term_scratch,
                )?;
                n_terms_total_usize += 1;
            }

            doc_lengths_by_orig_col[orig_col_idx] = Some(col_doc_lengths_owned);
        }

        assemble_and_write_blob(
            BlobAssemblyInputs {
                postings_writer,
                postings_path,
                postings_crc_acc,
                postings_len,
                positions_sink,
                fst_sink: FstSinkFinish::InRam(fst_inram),
                n_columns,
                n_docs,
                n_terms_total_usize,
                avgdl_per_col,
                doc_lengths_by_orig_col,
                scratch_dir,
                finish_profile,
            },
            &mut w,
        )
    }

    /// Spilled finish path: at least one column transitioned to
    /// `Spilled` during `add_doc`. Uses a streaming `MapBuilder`
    /// (FST bytes go to a scratch file as we go, never resident in
    /// RAM in full), drains every spilled column's per-partition
    /// batch buffers + closes their `BufWriter`s before the merge
    /// reads them, and the per-column emit loop handles both
    /// variants (a spilled build can still have InRam columns whose
    /// accumulator stayed under threshold).
    fn finish_to_spilled<W: Write>(self, mut w: W) -> Result<(), BuildError> {
        let FtsBuilder {
            default_tokenizer: _,
            column_tokenizers: _,
            columns,
            postings,
            scratch_dir,
            spill_threshold_bytes: _,
            spill_partitions: _,
            max_partition_bytes,
            n_docs,
            doc_tf,
            doc_pos_head,
            doc_pos_chain: _,
            pos_scratch: _,
            run_scratch: _,
            bump,
        } = self;
        drop(doc_tf);
        drop(doc_pos_head);
        drop(bump);

        let n_columns = columns.len() as u32;
        let mut n_terms_total_usize: usize = 0;

        let mut work: Vec<(usize, ColumnState, ColumnPostings)> = columns
            .into_iter()
            .zip(postings)
            .enumerate()
            .map(|(orig_idx, (state, posting_state))| (orig_idx, state, posting_state))
            .collect();
        work.sort_unstable_by(|a, b| a.1.name.cmp(&b.1.name));

        let mut avgdl_per_col: Vec<f32> = vec![0.0; n_columns as usize];
        for (orig_idx, state, _) in &work {
            let n = state.doc_lengths.len() as u64;
            avgdl_per_col[*orig_idx] = if n == 0 {
                0.0
            } else {
                (state.total_tokens as f32) / (n as f32)
            };
        }

        let scratch_path = scratch_dir.path().to_path_buf();
        let postings_path = scratch_path.join("infino_fts_postings.bin");
        let mut postings_writer = BufWriter::new(File::create(&postings_path)?);
        let mut postings_len: u64 = 0;
        let mut postings_crc_acc: u32 = 0;
        // Every blob carries a positions region (empty when no column
        // records positions) — new code always writes the v2 layout.
        let mut positions_sink = PositionsSink::create(&scratch_path)?;
        let mut key_buf: Vec<u8> = Vec::with_capacity(64);
        let mut term_scratch = TermScratch::default();
        let mut finish_profile = FinishProfile::from_config();

        // Streaming FST: bytes flow to a scratch file as we insert
        // sorted keys, so the FST never lives in RAM in full.
        // Assembly reopens the file, CRCs it, and copies it into the
        // output writer.
        let fst_streaming_path = scratch_path.join("infino_fts_dict.bin");
        let mut fst_streaming = {
            let fst_file = File::create(&fst_streaming_path)?;
            let bw = BufWriter::new(fst_file);
            StreamingDictBuilder::new(bw).map_err(map_fst_err)?
        };

        // Drain every spilled column's per-partition batch buffer
        // into the partition's `BufWriter`, then flush + close it
        // so the merge phase reads a complete file. InRam columns
        // in this work list are no-ops.
        let partition_flush_start = finish_profile.enabled.then(Instant::now);
        for (_, _, cp) in &mut work {
            if let ColumnPostings::Spilled { partitions, .. } = cp {
                match partitions {
                    SpillStore::Plain(parts) => {
                        for partition in parts {
                            flush_partition_batch(partition)?;
                            if let Some(mut writer) = partition.writer.take() {
                                writer.flush()?;
                            }
                        }
                    }
                    SpillStore::Positional { partitions, blobs } => {
                        for partition in partitions.iter_mut() {
                            flush_partition_batch(partition)?;
                            if let Some(mut writer) = partition.writer.take() {
                                writer.flush()?;
                            }
                        }
                        for blob in blobs.iter_mut() {
                            if let Some(mut writer) = blob.writer.take() {
                                writer.flush()?;
                            }
                        }
                    }
                }
            }
        }
        if let Some(t) = partition_flush_start {
            finish_profile.partition_flush += t.elapsed();
        }

        let mut doc_lengths_by_orig_col: Vec<Option<Vec<u32>>> =
            (0..n_columns as usize).map(|_| None).collect();

        // Drain in lex order, consuming each entry by value so the
        // ColumnPostings (partition writers, in-RAM map) is dropped
        // before we touch the next column.
        for (orig_col_idx, col_state, posting_state) in work.drain(..) {
            let ColumnState {
                name: col_name,
                doc_lengths: col_doc_lengths_owned,
                total_tokens: _,
                positions: col_positions,
            } = col_state;
            let col_name_bytes = col_name.as_bytes();
            let avgdl = avgdl_per_col[orig_col_idx];
            let col_doc_lengths: &[u32] = &col_doc_lengths_owned;

            match posting_state {
                ColumnPostings::InRam {
                    terms,
                    pos_runs: mut col_pos_runs,
                    bytes: _,
                } => {
                    // Sort term keys; per-term doc lists are already
                    // in insertion order which is monotonically
                    // increasing local_doc_id per the add_doc
                    // contract — no per-list sort needed.
                    type InRamEntries = Vec<(Box<str>, Vec<(u32, u32)>)>;
                    let mut entries: InRamEntries = terms.into_iter().collect();
                    // pdqsort: posting-table dictionary entries for
                    // one in-RAM column can run into millions of
                    // terms; stability is unnecessary because keys
                    // are unique.
                    entries.sort_unstable_by(|a, b| a.0.as_bytes().cmp(b.0.as_bytes()));
                    for (term, postings) in entries {
                        // Positional columns never spill (their
                        // accumulator is pinned in RAM), so a spilled
                        // build's positional terms all pass through
                        // this arm with their runs.
                        let term_runs: Vec<u8> = match col_positions {
                            true => col_pos_runs
                                .remove(&term)
                                .expect("positional term accumulated a position run"),
                            false => Vec::new(),
                        };
                        let term_positions = match col_positions {
                            true => Some((&mut positions_sink, term_runs.as_slice())),
                            false => None,
                        };
                        encode_and_emit_term(
                            &term,
                            &postings,
                            col_name_bytes,
                            col_doc_lengths,
                            avgdl,
                            n_docs,
                            &mut key_buf,
                            &mut postings_writer,
                            &mut postings_crc_acc,
                            &mut postings_len,
                            None,
                            Some(&mut fst_streaming),
                            term_positions,
                            &mut finish_profile,
                            &mut term_scratch,
                        )?;
                        n_terms_total_usize += 1;
                    }
                }
                ColumnPostings::Spilled {
                    partitions,
                    term_to_id,
                    id_to_term,
                    dense_doc_tf: _,
                    dense_doc_poshead: _,
                    updated_terms: _,
                    term_arena,
                } => {
                    // Term interner is finished being written to;
                    // drop the forward map (`term_to_id`) immediately
                    // — the rest of the spilled finish only needs
                    // the reverse map (`id_to_term`) for FST emit and
                    // the lex-rank table built from it.
                    //
                    // Lifetime sanity: `term_to_id` and `id_to_term`
                    // hold `&'static str` keys/entries that actually
                    // borrow from `term_arena`. We must keep
                    // `term_arena` alive until the **last
                    // dereference** of those keys/entries, which is
                    // the FST emit loop's `id_to_term[term_id]`
                    // index below. End-of-scope `Drop` order does
                    // not matter for soundness — neither `&str` nor
                    // its container's `Drop` impls dereference the
                    // borrowed bytes — but any **use** of `id_to_
                    // term[i].as_bytes()` must occur before
                    // `term_arena` goes out of scope. Both this
                    // arm's body and the helper functions it calls
                    // observe that.
                    drop(term_to_id);
                    let lex_rank_start = finish_profile.enabled.then(Instant::now);
                    let (lex_rank, term_id_in_lex_order) = build_lex_rank(&id_to_term);
                    if let Some(t) = lex_rank_start {
                        finish_profile.lex_rank_build += t.elapsed();
                    }

                    // Pre-sort every partition to a sorted-triple
                    // file under scratch. Sorting partition-at-a-
                    // time bounds the in-RAM sort working set to
                    // `max_partition_bytes` (one partition at a
                    // time), then the k-way merge across the
                    // resulting sorted files runs with
                    // O(n_partitions) cursors each holding one
                    // triple + a small read buffer.
                    let sort_start = finish_profile.enabled.then(Instant::now);
                    let mut sorted_files: Vec<PathBuf> =
                        Vec::with_capacity(partitions.n_partitions());
                    let partition_paths: Vec<PathBuf> = match &partitions {
                        SpillStore::Plain(parts) => parts.iter().map(|p| p.path.clone()).collect(),
                        SpillStore::Positional {
                            partitions: parts, ..
                        } => parts.iter().map(|p| p.path.clone()).collect(),
                    };
                    for (partition_idx, partition_path) in partition_paths.iter().enumerate() {
                        let sorted_path = scratch_path.join(format!(
                            "fts_col{orig_col_idx}_part{partition_idx}.sorted.bin"
                        ));
                        match &partitions {
                            SpillStore::Plain(_) => sort_partition_to_file::<PLAIN_RECORD_LANES>(
                                partition_path,
                                &sorted_path,
                                max_partition_bytes,
                                &scratch_path,
                                &format!("c{orig_col_idx}_p{partition_idx}"),
                                &lex_rank,
                            )?,
                            SpillStore::Positional { .. } => {
                                sort_partition_to_file::<POSITIONAL_RECORD_LANES>(
                                    partition_path,
                                    &sorted_path,
                                    max_partition_bytes,
                                    &scratch_path,
                                    &format!("c{orig_col_idx}_p{partition_idx}"),
                                    &lex_rank,
                                )?
                            }
                        }
                        sorted_files.push(sorted_path);
                    }
                    if let Some(t) = sort_start {
                        finish_profile.partition_sort += t.elapsed();
                    }

                    // Lex-order partition traversal. Replaces the
                    // earlier `BinaryHeap`-based k-way merge: since
                    // partition assignment is `partition =
                    // term_id & (n_part - 1)` (enforced
                    // power-of-two in `set_spill_partitions`),
                    // every posting for a given `term_id` lives
                    // in exactly one partition. Within that
                    // partition, the sort-partition phase has
                    // already arranged triples in
                    // `(lex_rank[term_id], doc_id)` order, so all
                    // triples for one `term_id` are contiguous
                    // there and they emerge in `doc_id` order
                    // when scanned forward.
                    //
                    // The merge therefore reduces to: walk
                    // `term_id_in_lex_order` (the
                    // sort-once-globally permutation we already
                    // produced above) and, for each `term_id`,
                    // drain the contiguous matching run from
                    // `sorted_slices[term_id & mask]` starting at
                    // that partition's cursor. Cost is O(n_postings
                    // + n_terms) sequential mmap reads + one u32
                    // compare per posting, versus the heap path's
                    // O(n_postings · log n_part) compares + heap
                    // pushes/pops.
                    //
                    // We still mmap each sorted partition file
                    // (zero-copy `&[Triple]` over page-cache-hot
                    // bytes), so the per-posting access is pointer
                    // arithmetic against contiguous memory.
                    let merge_profile_start = Instant::now();
                    let encode_calls_before = finish_profile.encode_calls;
                    let encode_df1_before = finish_profile.encode_df1;
                    let encode_pfor_before = finish_profile.encode_pfor;
                    let encode_total_before = finish_profile.encode_total;
                    let encode_block_build_before = finish_profile.encode_block_build;
                    let encode_meta_write_before = finish_profile.encode_meta_write;
                    let encode_skip_write_before = finish_profile.encode_skip_write;
                    let encode_block_write_before = finish_profile.encode_block_write;
                    let fst_insert_before = finish_profile.fst_insert;
                    let n_emitted = match &partitions {
                        SpillStore::Plain(_) => merge_sorted_spill::<PLAIN_RECORD_LANES, _>(
                            &sorted_files,
                            None,
                            &term_id_in_lex_order,
                            &id_to_term,
                            col_name_bytes,
                            col_doc_lengths,
                            avgdl,
                            n_docs,
                            &mut key_buf,
                            &mut postings_writer,
                            &mut postings_crc_acc,
                            &mut postings_len,
                            &mut fst_streaming,
                            &mut positions_sink,
                            &mut finish_profile,
                            &mut term_scratch,
                        )?,
                        SpillStore::Positional { blobs, .. } => {
                            // mmap each partition's positions blob so
                            // run assembly is pointer arithmetic; an
                            // empty blob maps to an empty slice.
                            let mut blob_mmaps: Vec<Option<Mmap>> = Vec::with_capacity(blobs.len());
                            for blob in blobs {
                                let f = File::open(&blob.path)?;
                                // SAFETY: the blob scratch file is owned
                                // by this builder's `scratch_dir`; its
                                // writer was flushed + closed in the
                                // partition-flush stage and nothing
                                // mutates it for the Mmap's lifetime.
                                let mmap = match blob.len {
                                    0 => None,
                                    _ => Some(unsafe { Mmap::map(&f)? }),
                                };
                                blob_mmaps.push(mmap);
                            }
                            merge_sorted_spill::<POSITIONAL_RECORD_LANES, _>(
                                &sorted_files,
                                Some(&blob_mmaps),
                                &term_id_in_lex_order,
                                &id_to_term,
                                col_name_bytes,
                                col_doc_lengths,
                                avgdl,
                                n_docs,
                                &mut key_buf,
                                &mut postings_writer,
                                &mut postings_crc_acc,
                                &mut postings_len,
                                &mut fst_streaming,
                                &mut positions_sink,
                                &mut finish_profile,
                                &mut term_scratch,
                            )?
                        }
                    };
                    n_terms_total_usize += n_emitted;
                    if finish_profile.enabled {
                        let merge_total = merge_profile_start.elapsed();
                        let encode_total = finish_profile.encode_total - encode_total_before;
                        let non_encode = merge_total.saturating_sub(encode_total);
                        eprintln!(
                            "[fts-profile] col='{}' merge_total={:.3}s non_encode_merge={:.3}s encode_total={:.3}s calls={} df1={} pfor={} block_build={:.3}s meta_write={:.3}s skip_write={:.3}s block_write={:.3}s fst_insert={:.3}s",
                            col_name,
                            merge_total.as_secs_f64(),
                            non_encode.as_secs_f64(),
                            encode_total.as_secs_f64(),
                            finish_profile.encode_calls - encode_calls_before,
                            finish_profile.encode_df1 - encode_df1_before,
                            finish_profile.encode_pfor - encode_pfor_before,
                            (finish_profile.encode_block_build - encode_block_build_before)
                                .as_secs_f64(),
                            (finish_profile.encode_meta_write - encode_meta_write_before)
                                .as_secs_f64(),
                            (finish_profile.encode_skip_write - encode_skip_write_before)
                                .as_secs_f64(),
                            (finish_profile.encode_block_write - encode_block_write_before)
                                .as_secs_f64(),
                            (finish_profile.fst_insert - fst_insert_before).as_secs_f64(),
                        );
                    }

                    // Sorted-partition scratch files are scoped to
                    // this column and only consumed by the k-way
                    // merge above. Drop the mmap views first
                    // (releases the page-cache references), then
                    // remove the files so the next spilled column
                    // doesn't see their disk residency. (Original
                    // partition files are owned by `partitions`
                    // and dropped at the next iteration boundary.)
                    let cleanup_start = finish_profile.enabled.then(Instant::now);
                    for p in &sorted_files {
                        let _ = fs::remove_file(p);
                    }
                    // The raw spill partition files are also no
                    // longer needed once the merge finishes — the
                    // tempdir cleanup will reap them at scope exit
                    // but doing it here keeps peak resident bytes
                    // on disk bounded to one column.
                    drop(partitions);
                    // Explicit drop sequence: `id_to_term` first
                    // (its `&'static str` entries borrow from
                    // `term_arena`; we've finished the last read
                    // at the FST emit loop above), then
                    // `term_arena` itself releases the term-byte
                    // backing store. Soundness does not strictly
                    // require this order (neither `Vec<&str>::
                    // drop` nor `Bump::drop` interacts with the
                    // other), but spelling it out leaves the
                    // intent unambiguous to future readers.
                    drop(id_to_term);
                    drop(term_arena);
                    drop(lex_rank);
                    if let Some(t) = cleanup_start {
                        finish_profile.scratch_cleanup += t.elapsed();
                    }
                }
            }

            // Hand this column's doc-lengths off for the
            // final-assembly pass. `posting_state` (with its
            // partition writers if any) and `col_name` are dropped
            // here at scope exit before the next iteration starts,
            // bounding peak per-column resident state to one column.
            // Mirror of vector's `columns.into_iter().enumerate()`
            // lifetime in `VectorBuilder::finish_to`.
            doc_lengths_by_orig_col[orig_col_idx] = Some(col_doc_lengths_owned);
        }

        assemble_and_write_blob(
            BlobAssemblyInputs {
                postings_writer,
                postings_path,
                postings_crc_acc,
                postings_len,
                positions_sink,
                fst_sink: FstSinkFinish::Streaming {
                    builder: fst_streaming,
                    path: fst_streaming_path,
                },
                n_columns,
                n_docs,
                n_terms_total_usize,
                avgdl_per_col,
                doc_lengths_by_orig_col,
                scratch_dir,
                finish_profile,
            },
            &mut w,
        )
    }
}

/// Inputs threaded into [`assemble_and_write_blob`]. Bundled into a
/// struct rather than a 12-arg call so the two finish paths can read
/// like "build everything, then assemble" instead of routing through
/// a long positional argument list. All fields are consumed by
/// assembly.
/// Streaming sink for the positions region, mirroring the postings
/// scratch-file quartet (writer, path, running CRC, running length).
/// Created by a finish path iff any registered column is positional;
/// its running `len` doubles as the next term's `positions_offset`
/// (offsets in term metadata are relative to the region start).
struct PositionsSink {
    writer: BufWriter<File>,
    path: PathBuf,
    crc_acc: u32,
    len: u64,
}

impl PositionsSink {
    fn create(scratch_path: &Path) -> Result<Self, BuildError> {
        let path = scratch_path.join("infino_fts_positions.bin");
        Ok(Self {
            writer: BufWriter::new(File::create(&path)?),
            path,
            crc_acc: 0,
            len: 0,
        })
    }

    fn write(&mut self, bytes: &[u8]) -> Result<(), BuildError> {
        write_counted(&mut self.writer, &mut self.crc_acc, &mut self.len, bytes)
    }
}

struct BlobAssemblyInputs {
    /// Open scratch writer holding every encoded posting block in
    /// lex order. Assembly closes it (CRC trailer + flush) before
    /// streaming the file's contents into the output.
    postings_writer: BufWriter<File>,
    /// On-disk path of the posting body. Reopened for the streaming
    /// copy into the output writer.
    postings_path: PathBuf,
    /// Running CRC32C over every byte written to `postings_writer`.
    /// Assembly appends the little-endian trailer.
    postings_crc_acc: u32,
    /// Bytes written so far to `postings_writer` (excluding trailer).
    /// Assembly grows this by 4 when it appends the CRC.
    postings_len: u64,
    /// Positions region sink. Always present: new code always writes
    /// the v2 layout, with the region (possibly just its CRC-of-empty
    /// trailer) between the postings and the doc-lengths directory.
    /// v1 remains a read-only legacy format.
    positions_sink: PositionsSink,
    /// Whichever FST sink was used during the per-column emit loop
    /// (exactly one of the two variants).
    fst_sink: FstSinkFinish,
    n_columns: u32,
    n_docs: u32,
    /// Pre-cast checked downstream against `u32::MAX`.
    n_terms_total_usize: usize,
    /// Per-original-column avgdl (declaration order, not lex order).
    avgdl_per_col: Vec<f32>,
    /// Per-original-column doc-lengths, moved out of `work` by each
    /// emit-loop iteration.
    doc_lengths_by_orig_col: Vec<Option<Vec<u32>>>,
    /// Scratch dir owning every spill file. Dropped after the
    /// streamed regions (FST + postings) have been copied into `w`.
    scratch_dir: tempfile::TempDir,
    /// Profile accumulator — final block of `[fts-finish]` timings
    /// is emitted at the bottom of assembly.
    finish_profile: FinishProfile,
}

/// FST emission sink picked by the active finish path.
enum FstSinkFinish {
    /// In-RAM build: hand the populated `DictBuilder` to assembly,
    /// which calls `finish()` to produce the FST bytes in one shot.
    InRam(DictBuilder),
    /// Spilled build: hand the open `StreamingDictBuilder` (and the
    /// scratch path it's been writing to) to assembly, which finishes
    /// the builder, computes the file's CRC by streaming, and copies
    /// the file into the output.
    Streaming {
        builder: StreamingDictBuilder<BufWriter<File>>,
        path: PathBuf,
    },
}

/// Common tail of every finish path: close the posting body, finalise
/// the FST, build the doc-lengths directory + arrays, and write
/// `[header | fst | postings | dir | arrays]` to `w`. Lifted out of
/// `FtsBuilder::finish_to` so the in-RAM and spilled paths share one
/// regression target instead of two — every byte the reader observes
/// passes through here.
fn assemble_and_write_blob<W: Write>(
    inputs: BlobAssemblyInputs,
    w: &mut W,
) -> Result<(), BuildError> {
    let BlobAssemblyInputs {
        mut postings_writer,
        postings_path,
        postings_crc_acc,
        mut postings_len,
        positions_sink,
        fst_sink,
        n_columns,
        n_docs,
        n_terms_total_usize,
        avgdl_per_col,
        mut doc_lengths_by_orig_col,
        scratch_dir,
        mut finish_profile,
    } = inputs;

    debug_assert!(
        n_terms_total_usize <= u32::MAX as usize,
        "term count overflows u32"
    );
    let n_terms_total = n_terms_total_usize as u32;

    // Close the posting body file (CRC trailer + flush).
    let postings_close_start = finish_profile.enabled.then(Instant::now);
    let postings_crc = postings_crc_acc;
    let postings_crc_le = postings_crc.to_le_bytes();
    postings_writer.write_all(&postings_crc_le)?;
    postings_writer.flush()?;
    drop(postings_writer);
    postings_len += postings_crc_le.len() as u64;
    if let Some(t) = postings_close_start {
        finish_profile.postings_close += t.elapsed();
    }

    // Close the positions region file the same way (CRC trailer +
    // flush). A build with no positional column (or whose positional
    // terms all inlined) leaves a body of zero bytes — the region is
    // then just the 4-byte CRC-of-empty, the same legal shape an
    // empty postings region takes.
    let positions_region = {
        let mut sink = positions_sink;
        let crc_le = sink.crc_acc.to_le_bytes();
        sink.writer.write_all(&crc_le)?;
        sink.writer.flush()?;
        drop(sink.writer);
        (sink.path, sink.len + crc_le.len() as u64)
    };

    // Finalise the FST. Either path produces "FST bytes followed
    // by 4 trailing CRC bytes"; the source differs.
    enum FstSource {
        InRam(Vec<u8>),
        Streamed { path: PathBuf, len: u64, crc: u32 },
    }
    let fst_close_start = finish_profile.enabled.then(Instant::now);
    let fst_source = match fst_sink {
        FstSinkFinish::InRam(db) => {
            let mut bytes = db.finish();
            let crc = crc32c(&bytes);
            bytes.extend_from_slice(&crc.to_le_bytes());
            FstSource::InRam(bytes)
        }
        FstSinkFinish::Streaming {
            builder,
            path: fst_streaming_path,
        } => {
            let mut bw = builder.finish().map_err(map_fst_err)?;
            bw.flush()?;
            // Close the write side of the FST scratch file. The
            // returned `File` is `File::create`-opened (write-only),
            // so we must reopen for reading to compute the CRC and
            // later stream into `w`.
            let write_file = bw
                .into_inner()
                .map_err(|e| BuildError::Io(e.into_error()))?;
            drop(write_file);

            // Stream the FST scratch file with bounded memory to
            // compute its CRC.
            let mut read_file = File::open(&fst_streaming_path)?;
            let fst_body_len = read_file.metadata()?.len();
            read_file.seek(SeekFrom::Start(0))?;
            let mut reader = BufReader::with_capacity(PARTITION_BUF_SIZE, read_file);
            let mut crc: u32 = 0;
            let mut buf = vec![0u8; PARTITION_BUF_SIZE];
            loop {
                let n = match reader.read(&mut buf) {
                    Ok(0) => break,
                    Ok(n) => n,
                    Err(e) if e.kind() == ErrorKind::Interrupted => continue,
                    Err(e) => return Err(BuildError::Io(e)),
                };
                crc = crc32c_append(crc, &buf[..n]);
            }
            drop(reader);
            FstSource::Streamed {
                path: fst_streaming_path,
                len: fst_body_len + 4, /* trailing CRC */
                crc,
            }
        }
    };
    if let Some(t) = fst_close_start {
        finish_profile.fst_close += t.elapsed();
    }

    // Compute final-blob offsets now that both region lengths are known.
    let dl_emit_start = finish_profile.enabled.then(Instant::now);
    let fst_total_len: u64 = match &fst_source {
        FstSource::InRam(bytes) => bytes.len() as u64,
        FstSource::Streamed { len, .. } => *len,
    };
    let header_size: u64 = format::fts::HEADER_SIZE_V2 as u64;
    let fst_offset: u64 = header_size;
    let postings_offset: u64 = fst_offset + fst_total_len;
    // The positions region sits between the postings and the
    // doc-lengths directory (keeping the lazy-open doc-lengths tail
    // fetch small); absent, the directory follows postings directly.
    let positions_offset: u64 = postings_offset + postings_len;
    let doc_lengths_table_offset: u64 = positions_offset + positions_region.1;
    let mut doc_lengths_array_offset: u64 =
        doc_lengths_table_offset + (n_columns as u64) * (DOC_LENGTHS_ENTRY_SIZE as u64) + 4 /* dir CRC */;

    let mut dir_buf: Vec<u8> = Vec::with_capacity(n_columns as usize * DOC_LENGTHS_ENTRY_SIZE);
    let mut arrays_buf: Vec<u8> = Vec::new();
    for i in 0..n_columns as usize {
        let avgdl_x1000 = (avgdl_per_col[i] * format::fts::AVGDL_FIXED_POINT_SCALE)
            .max(0.0)
            .min(u32::MAX as f32) as u32;
        dir_buf.extend_from_slice(&(i as u32).to_le_bytes());
        dir_buf.extend_from_slice(&doc_lengths_array_offset.to_le_bytes());
        dir_buf.extend_from_slice(&avgdl_x1000.to_le_bytes());

        let col_dls = doc_lengths_by_orig_col[i]
            .take()
            .expect("doc_lengths recorded for every registered column");
        let array_start = arrays_buf.len();
        // x86_64 is little-endian and the format spec is
        // little-endian u32 — so a raw byte-cast over the
        // `Vec<u32>` slice is the wire encoding. `bytemuck`
        // gates this on `Pod` so a non-LE host would fail
        // compilation rather than silently emit wrong bytes;
        // the SIMD memcpy that `extend_from_slice` lowers to
        // is materially faster than the per-u32 `to_le_bytes`
        // + push loop, especially at the 10M-doc / column
        // scale where this writes 40 MB per column.
        #[cfg(target_endian = "little")]
        arrays_buf.extend_from_slice(bytemuck::cast_slice::<u32, u8>(&col_dls));
        #[cfg(not(target_endian = "little"))]
        for &dl in &col_dls {
            arrays_buf.extend_from_slice(&dl.to_le_bytes());
        }
        let array_bytes = &arrays_buf[array_start..];
        let array_crc = crc32c(array_bytes);
        arrays_buf.extend_from_slice(&array_crc.to_le_bytes());
        doc_lengths_array_offset += (col_dls.len() as u64) * 4 + 4;
    }
    let dir_crc = crc32c(&dir_buf);
    dir_buf.extend_from_slice(&dir_crc.to_le_bytes());
    if let Some(t) = dl_emit_start {
        finish_profile.doc_lengths_emit += t.elapsed();
    }

    // Final assembly. Bytes flow scratch → small streaming buffer
    // → `w`, never re-materialising the full blob in RAM.
    let blob_copy_start = finish_profile.enabled.then(Instant::now);
    let mut header = Vec::with_capacity(header_size as usize);
    header.extend_from_slice(format::fts::MAGIC); // 8
    header.extend_from_slice(&format::fts::VERSION_V2.to_le_bytes()); // 4
    header.extend_from_slice(&n_columns.to_le_bytes()); // 4
    header.extend_from_slice(&n_docs.to_le_bytes()); // 4
    header.extend_from_slice(&n_terms_total.to_le_bytes()); // 4
    header.extend_from_slice(&fst_offset.to_le_bytes()); // 8
    header.extend_from_slice(&postings_offset.to_le_bytes()); // 8
    header.extend_from_slice(&doc_lengths_table_offset.to_le_bytes()); // 8
    header.extend_from_slice(&positions_offset.to_le_bytes()); // 8
    debug_assert_eq!(header.len(), header_size as usize, "header size mismatch");

    w.write_all(&header)?;
    match fst_source {
        FstSource::InRam(bytes) => w.write_all(&bytes)?,
        FstSource::Streamed { path, crc, .. } => {
            let mut reader = BufReader::with_capacity(PARTITION_BUF_SIZE, File::open(&path)?);
            io::copy(&mut reader, w)?;
            w.write_all(&crc.to_le_bytes())?;
        }
    }
    let mut postings_reader =
        BufReader::with_capacity(PARTITION_BUF_SIZE, File::open(&postings_path)?);
    io::copy(&mut postings_reader, w)?;
    drop(postings_reader);
    {
        let mut positions_reader =
            BufReader::with_capacity(PARTITION_BUF_SIZE, File::open(&positions_region.0)?);
        io::copy(&mut positions_reader, w)?;
    }

    // Drop the scratch tempdir as soon as the streamed source
    // files (FST + posting body) have been copied into `w`. The
    // remaining writes (`dir_buf`, `arrays_buf`) are
    // already-resident `Vec<u8>` and don't touch the disk.
    // Mirror of vector's `drop(scratch_dir);` at the bottom of
    // `VectorBuilder::finish_to`.
    drop(scratch_dir);

    w.write_all(&dir_buf)?;
    w.write_all(&arrays_buf)?;
    if let Some(t) = blob_copy_start {
        finish_profile.blob_copy += t.elapsed();
    }

    if finish_profile.enabled {
        eprintln!(
            "[fts-finish] partition_flush={:.3}s lex_rank={:.3}s partition_sort={:.3}s mmap_open={:.3}s scratch_cleanup={:.3}s postings_close={:.3}s fst_close={:.3}s doc_lengths_emit={:.3}s blob_copy={:.3}s",
            finish_profile.partition_flush.as_secs_f64(),
            finish_profile.lex_rank_build.as_secs_f64(),
            finish_profile.partition_sort.as_secs_f64(),
            finish_profile.mmap_open.as_secs_f64(),
            finish_profile.scratch_cleanup.as_secs_f64(),
            finish_profile.postings_close.as_secs_f64(),
            finish_profile.fst_close.as_secs_f64(),
            finish_profile.doc_lengths_emit.as_secs_f64(),
            finish_profile.blob_copy.as_secs_f64(),
        );
    }

    Ok(())
}

#[inline]
fn map_fst_err(e: fst::Error) -> BuildError {
    BuildError::Io(Error::new(ErrorKind::InvalidData, e))
}

/// Reusable per-term scratch buffers threaded through
/// `encode_and_emit_term`. One instance is created at the top of
/// `finish_to` and re-used across every term encoded in the column,
/// turning ~3M+ per-term `Vec::new` allocations on the 1M-doc
/// forced-spill bench into ~5 reused allocations (one per buffer,
/// once per column). The Block's `doc_ids` / `tfs` Vecs are
/// `mem::take`'d into a Block, encoded, then swapped back via
/// `mem::take` so the underlying buffer is reused for the next
/// chunk (same allocation, just `Vec::clear` between iterations).
#[derive(Default)]
struct TermScratch {
    /// Per-block doc_id column passed to `encode_block`. Re-used by
    /// taking it into a Block, encoding, and taking it back. Capacity
    /// stabilises at `BLOCK_LEN` after the first dense term.
    doc_ids: Vec<u32>,
    /// Per-block tf column, same lifecycle as `doc_ids`.
    tfs: Vec<u32>,
    /// Per-block BM25 upper bound for the skip table — the **exact**
    /// maximum per-doc contribution over the block's docs (not the looser
    /// `score(max_tf, min_dl)`, whose best-case tf and best-case dl need
    /// not co-occur in one doc). A tighter bound lets the reader's
    /// block-skip fire more often.
    block_ub_per_block: Vec<f32>,
    /// Per-term list of encoded blocks held across the meta + skip-
    /// table + block-bytes emit stages.
    encoded_blocks: Vec<EncodedBlock>,
    /// Per-term contiguous byte buffer holding meta + skip table +
    /// concatenated block bytes; written to `postings_writer` as one
    /// `write_counted` call.
    term_buf: Vec<u8>,
    /// Per-term positions-block offsets (one per PFOR block, byte
    /// offset of the block's first run within the term's positions
    /// bytes) for positional columns. Reused like the other buffers.
    pos_block_offsets: Vec<u32>,
}

/// Merge one spilled column's sorted partition files and emit every
/// term. Shared by the plain and positional stores: the lex-order
/// walk, contiguous-run drain, and emit sequence are identical; a
/// positional store (`blob_mmaps = Some`) additionally recovers each
/// posting's position run from its partition's blob — sliced at the
/// offset riding in the record's trailing lanes, delimited by the
/// posting's `tf` — and hands the term's assembled runs to the
/// encoder. Returns the number of terms emitted.
#[allow(clippy::too_many_arguments)]
fn merge_sorted_spill<const N: usize, W: Write>(
    sorted_files: &[PathBuf],
    blob_mmaps: Option<&[Option<Mmap>]>,
    term_id_in_lex_order: &[u32],
    id_to_term: &[&'static str],
    col_name_bytes: &[u8],
    col_doc_lengths: &[u32],
    avgdl: f32,
    n_docs: u32,
    key_buf: &mut Vec<u8>,
    postings_writer: &mut W,
    postings_crc_acc: &mut u32,
    postings_len: &mut u64,
    fst_streaming: &mut StreamingDictBuilder<BufWriter<File>>,
    positions_sink: &mut PositionsSink,
    finish_profile: &mut FinishProfile,
    term_scratch: &mut TermScratch,
) -> Result<usize, BuildError> {
    let mmap_start = finish_profile.enabled.then(Instant::now);
    let mut mmaps: Vec<Mmap> = Vec::with_capacity(sorted_files.len());
    for p in sorted_files {
        let f = File::open(p)?;
        // SAFETY: the sorted-partition scratch file is owned by this
        // builder's `scratch_dir`; no other process truncates or
        // appends to it for the lifetime of the `Mmap`.
        let mmap = unsafe { Mmap::map(&f)? };
        mmaps.push(mmap);
    }
    if let Some(t) = mmap_start {
        finish_profile.mmap_open += t.elapsed();
    }
    let sorted_slices: Vec<&[[u32; N]]> = mmaps
        .iter()
        .map(|m| {
            if m.is_empty() {
                &[][..]
            } else {
                bytemuck::cast_slice::<u8, [u32; N]>(&m[..])
            }
        })
        .collect();
    let blob_slices: Vec<&[u8]> = match blob_mmaps {
        Some(ms) => ms
            .iter()
            .map(|m| m.as_ref().map_or(&[][..], |m| &m[..]))
            .collect(),
        None => Vec::new(),
    };
    let mask = (sorted_slices.len() - 1) as u32;
    // Per-partition next-index into its sorted slice. Walked forward
    // only — each posting is read exactly once.
    let mut cursors: Vec<usize> = vec![0usize; sorted_slices.len()];

    // Per-term buffers, reused across all terms in this column so we
    // pay one growth schedule instead of one per term.
    let mut group: Vec<(u32, u32)> = Vec::new();
    let mut group_pos: Vec<u64> = Vec::new();
    let mut term_run: Vec<u8> = Vec::new();
    let mut n_emitted = 0usize;
    for &term_id in term_id_in_lex_order {
        let p = (term_id & mask) as usize;
        let slice = sorted_slices[p];
        let mut pos = cursors[p];
        group.clear();
        group_pos.clear();
        // Drain the contiguous run for this term. Termination: either
        // the partition runs out, or the next record's term_id differs
        // (next term in this partition's lex-rank order, which can
        // only be a strictly higher `lex_rank` and so a different
        // `term_id`).
        while pos < slice.len() {
            let t = &slice[pos];
            if triple_term_id(t) != term_id {
                break;
            }
            group.push((triple_doc_id(t), triple_tf(t)));
            if blob_mmaps.is_some() {
                // The generic walk serves both widths; the offset
                // lanes exist only on the positional record, which is
                // the only case with `blob_mmaps` present.
                debug_assert_eq!(N, POSITIONAL_RECORD_LANES);
                let rec: &[u32; POSITIONAL_RECORD_LANES] =
                    t[..].try_into().expect("positional record width");
                group_pos.push(record_pos_off(rec));
            }
            pos += 1;
        }
        cursors[p] = pos;
        if group.is_empty() {
            // Term registered in `id_to_term` but no postings landed
            // for it — only possible if the in-RAM flush ran with an
            // empty postings vec. Defensive: skip without emitting.
            continue;
        }
        let term_positions = match blob_mmaps.is_some() {
            true => {
                // Assemble the term's position runs in merged (doc)
                // order: slice each posting's run out of the blob,
                // its end found by skipping `tf` varints.
                term_run.clear();
                let blob = blob_slices[p];
                for (i, &(_, tf)) in group.iter().enumerate() {
                    let start = group_pos[i] as usize;
                    let mut at = start;
                    skip_run(blob, &mut at, tf).expect("builder-encoded blob runs are well-formed");
                    term_run.extend_from_slice(&blob[start..at]);
                }
                Some((&mut *positions_sink, term_run.as_slice()))
            }
            false => None,
        };
        let term_bytes: &str = id_to_term[term_id as usize];
        encode_and_emit_term(
            term_bytes,
            &group,
            col_name_bytes,
            col_doc_lengths,
            avgdl,
            n_docs,
            key_buf,
            postings_writer,
            postings_crc_acc,
            postings_len,
            None,
            Some(fst_streaming),
            term_positions,
            finish_profile,
            term_scratch,
        )?;
        n_emitted += 1;
    }
    // Sanity: every partition should now be fully drained. If not, we
    // lost or mis-ordered records somewhere upstream.
    debug_assert!(
        cursors
            .iter()
            .zip(sorted_slices.iter())
            .all(|(c, s)| *c == s.len()),
        "lex-order partition traversal did not drain all records; \
         partition assignment or sort invariant violated"
    );
    Ok(n_emitted)
}

/// Encode one term's posting list and emit the resulting FST entry
/// into whichever sink the finish path uses. Exactly one of
/// `fst_entries_inram` / `fst_streaming` is `Some`; the function
/// dispatches accordingly.
///
/// Owns the per-term encoding policy (df=1 inline value, df≥2 PFOR
/// blocks via `encode_posting_group`).
#[allow(clippy::too_many_arguments)]
fn encode_and_emit_term<W: Write>(
    term: &str,
    pairs: &[(u32, u32)],
    col_name_bytes: &[u8],
    col_doc_lengths: &[u32],
    avgdl: f32,
    n_docs: u32,
    key_buf: &mut Vec<u8>,
    postings_writer: &mut W,
    postings_crc_acc: &mut u32,
    postings_len: &mut u64,
    fst_entries_inram: Option<&mut DictBuilder>,
    mut fst_streaming: Option<&mut StreamingDictBuilder<BufWriter<File>>>,
    mut term_positions: Option<(&mut PositionsSink, &[u8])>,
    profile: &mut FinishProfile,
    scratch: &mut TermScratch,
) -> Result<(), BuildError> {
    let encode_start = profile.enabled.then(Instant::now);
    profile.encode_calls += 1;
    // Build the FST key once; reused regardless of in-RAM vs spilled
    // emit policy.
    key_buf.clear();
    key_buf.extend_from_slice(col_name_bytes);
    key_buf.push(FST_SEPARATOR);
    key_buf.extend_from_slice(term.as_bytes());

    debug_assert!(
        pairs.windows(2).all(|w| w[0].0 < w[1].0),
        "posting list not sorted by doc_id"
    );

    let df = pairs.len() as u64;

    // A df=1 posting inlines into the FST value when the WHOLE
    // posting fits: a positionless column always does (doc_id + tf);
    // a positional column only when tf == 1 and the single position
    // fits the 30-bit slot — the position rides where tf normally
    // lives, tf implied 1 (one position is exactly what a phrase
    // check needs). Otherwise even a df=1 term takes the PFOR form so
    // its positions land in the region.
    let inline_value: Option<u64> = if df == 1 {
        let (doc_id, tf) = pairs[0];
        match &term_positions {
            None => Some(FstValue::pack_inline(doc_id, tf)),
            Some((_, runs)) if tf == 1 => {
                let mut at = 0;
                let pos = read_varint(runs, &mut at).expect("builder-encoded run is well-formed");
                (pos <= INLINE_TF_MAX).then(|| FstValue::pack_inline(doc_id, pos))
            }
            Some(_) => None,
        }
    } else {
        None
    };

    let fst_value: u64 = if let Some(v) = inline_value {
        profile.encode_df1 += 1;
        v
    } else {
        profile.encode_pfor += 1;
        let idf_t = bm25::idf(n_docs as u64, df);
        // Reuse `scratch.encoded_blocks` / `scratch.min_dl_per_block`
        // across every dense term in the column (one allocation amortised
        // over ~5K terms / ~1M blocks at 1M docs, vs `Vec::new` per term).
        let encoded_blocks = &mut scratch.encoded_blocks;
        let block_ub_per_block = &mut scratch.block_ub_per_block;
        encoded_blocks.clear();
        block_ub_per_block.clear();
        let block_build_start = profile.enabled.then(Instant::now);
        // Build each block by moving the reusable `doc_ids` / `tfs`
        // buffers into a `Block` (Vec move = pointer swap, no copy),
        // encoding, then moving them back so the next chunk reuses the
        // same heap allocation. `encode_block` only borrows, but the
        // public signature takes `&Block` whose fields are owned Vecs,
        // hence the take/put dance. The take/put preserves capacity at
        // `BLOCK_LEN`, so the steady-state per-chunk cost is
        // `clear` + `extend_from_slice` of ≤128 u32s with no realloc.
        let mut block_doc_ids = mem::take(&mut scratch.doc_ids);
        let mut block_tfs = mem::take(&mut scratch.tfs);
        if block_doc_ids.capacity() < BLOCK_LEN {
            block_doc_ids.reserve(BLOCK_LEN - block_doc_ids.capacity());
        }
        if block_tfs.capacity() < BLOCK_LEN {
            block_tfs.reserve(BLOCK_LEN - block_tfs.capacity());
        }
        for chunk in pairs.chunks(BLOCK_LEN) {
            block_doc_ids.clear();
            block_tfs.clear();
            block_doc_ids.extend(chunk.iter().map(|&(d, _)| d));
            block_tfs.extend(chunk.iter().map(|&(_, t)| t));
            // Exact per-block BM25 upper bound: the max actual per-doc
            // contribution over the block. score() rises with tf and falls
            // with dl, so the looser `score(max_tf, min_dl)` over-estimates
            // when the highest-tf doc isn't also the shortest. Computing the
            // real max here (build-time, off the query path) tightens the
            // skip-table bound so the reader skips more blocks.
            let block_ub = block_doc_ids
                .iter()
                .zip(block_tfs.iter())
                .map(|(&d, &t)| bm25::score(idf_t, t, col_doc_lengths[d as usize], avgdl))
                .fold(0.0f32, f32::max);
            block_ub_per_block.push(block_ub);
            let block = Block {
                doc_ids: mem::take(&mut block_doc_ids),
                tfs: mem::take(&mut block_tfs),
            };
            encoded_blocks.push(encode_block(&block));
            // Reclaim the underlying allocations for the next chunk.
            block_doc_ids = block.doc_ids;
            block_tfs = block.tfs;
        }
        scratch.doc_ids = block_doc_ids;
        scratch.tfs = block_tfs;
        if let Some(start) = block_build_start {
            profile.encode_block_build += start.elapsed();
        }
        let num_blocks = encoded_blocks.len() as u32;
        let metadata_offset = *postings_len;
        let skip_table_size = encoded_blocks.len() * SKIP_ENTRY_SIZE;
        let blocks_total_size: usize = encoded_blocks.iter().map(|b| b.bytes.len()).sum();
        let term_meta_size = match term_positions {
            Some(_) => TERM_META_POSITIONAL_SIZE,
            None => TERM_META_SIZE,
        };
        let postings_length = (term_meta_size + skip_table_size + blocks_total_size) as u64;

        // Per-block byte offsets into this term's position runs: walk
        // the runs once, recording where each 128-doc block's first
        // run starts, so the reader can fetch/decode one block's
        // positions without touching its predecessors.
        let pos_block_offsets = &mut scratch.pos_block_offsets;
        pos_block_offsets.clear();
        if let Some((_, runs)) = &term_positions {
            debug_assert!(
                runs.len() <= u32::MAX as usize,
                "single-term positions > 4 GiB"
            );
            let mut at: usize = 0;
            for (i, &(_, tf)) in pairs.iter().enumerate() {
                if i % BLOCK_LEN == 0 {
                    pos_block_offsets.push(at as u32);
                }
                skip_run(runs, &mut at, tf).expect("builder-encoded runs are well-formed");
            }
            debug_assert_eq!(at, runs.len(), "runs must cover exactly the pairs");
        }

        debug_assert!(df <= u32::MAX as u64, "df overflows u32");
        debug_assert!(
            postings_length <= u32::MAX as u64,
            "single-term posting > 4 GiB"
        );

        // Reuse `scratch.term_buf` across every dense term. `clear`
        // keeps the existing allocation; only a true grow (a term
        // larger than any previously seen) reallocs.
        let term_buf = &mut scratch.term_buf;
        term_buf.clear();
        if term_buf.capacity() < postings_length as usize {
            term_buf.reserve(postings_length as usize - term_buf.capacity());
        }
        let meta_write_start = profile.enabled.then(Instant::now);
        term_buf.extend_from_slice(&(df as u32).to_le_bytes());
        term_buf.extend_from_slice(&metadata_offset.to_le_bytes());
        term_buf.extend_from_slice(&(postings_length as u32).to_le_bytes());
        term_buf.extend_from_slice(&num_blocks.to_le_bytes());
        if let Some((sink, runs)) = &term_positions {
            term_buf.extend_from_slice(&sink.len.to_le_bytes());
            term_buf.extend_from_slice(&(runs.len() as u32).to_le_bytes());
        }
        debug_assert_eq!(term_buf.len(), term_meta_size);
        if let Some(start) = meta_write_start {
            profile.encode_meta_write += start.elapsed();
        }

        let mut block_offset: u32 = (term_meta_size + skip_table_size) as u32;
        let skip_write_start = profile.enabled.then(Instant::now);
        for (i, blk) in encoded_blocks.iter().enumerate() {
            let max_bm25 = block_ub_per_block[i];
            // ceil(): the stored fixed-point value must stay a true
            // UPPER bound after quantization — truncation would round
            // it below the real block max and let BMW / floor skips
            // drop blocks that still hold qualifying docs. (The reader
            // additionally adds one step on decode to cover files
            // written before this rounding fix.)
            let max_bm25_x1000 = (max_bm25 * format::fts::BLOCK_MAX_BM25_FIXED_POINT_SCALE)
                .ceil()
                .max(0.0)
                .min(u32::MAX as f32) as u32;
            term_buf.extend_from_slice(&blk.last_doc_id.to_le_bytes());
            term_buf.extend_from_slice(&block_offset.to_le_bytes());
            term_buf.extend_from_slice(&max_bm25_x1000.to_le_bytes());
            // Positionless columns keep writing zero here —
            // byte-identical to the field's reserved era.
            let pos_block_off = pos_block_offsets.get(i).copied().unwrap_or(0);
            term_buf.extend_from_slice(&pos_block_off.to_le_bytes());
            block_offset += blk.bytes.len() as u32;
        }
        if let Some(start) = skip_write_start {
            profile.encode_skip_write += start.elapsed();
        }

        let block_write_start = profile.enabled.then(Instant::now);
        for blk in encoded_blocks.iter() {
            term_buf.extend_from_slice(&blk.bytes);
        }
        debug_assert_eq!(term_buf.len(), postings_length as usize);
        write_counted(postings_writer, postings_crc_acc, postings_len, term_buf)?;
        if let Some(start) = block_write_start {
            profile.encode_block_write += start.elapsed();
        }

        if let Some((sink, runs)) = term_positions.as_mut() {
            sink.write(runs)?;
        }

        FstValue::pack_pfor(metadata_offset, postings_length as u32)
    };

    let fst_insert_start = profile.enabled.then(Instant::now);
    if let Some(db) = fst_entries_inram {
        db.insert(key_buf, fst_value);
    } else if let Some(sb) = fst_streaming.as_mut() {
        sb.insert_sorted(key_buf, fst_value).map_err(map_fst_err)?;
    }
    if let Some(start) = fst_insert_start {
        profile.fst_insert += start.elapsed();
    }

    if let Some(start) = encode_start {
        profile.encode_total += start.elapsed();
    }

    Ok(())
}

fn write_counted<W: Write>(
    w: &mut W,
    crc_acc: &mut u32,
    len: &mut u64,
    bytes: &[u8],
) -> Result<(), BuildError> {
    w.write_all(bytes)?;
    *crc_acc = crc32c_append(*crc_acc, bytes);
    *len += bytes.len() as u64;
    Ok(())
}

/// Sort one partition file to a sorted-triple file at `out_path`.
/// Uses an in-memory sort when the partition is at or below
/// `max_partition_bytes`, otherwise external merge over chunked
/// sorted spills (partition-skew defense: a single pathologically
/// large partition would otherwise blow the in-memory sort budget).
///
/// Both the input and the output are runs of fixed 12-byte triples
/// `(term_id_le, doc_id_le, tf_le)`. The ordering written to
/// `out_path` is `(lex_rank[term_id], doc_id)` so a downstream k-way
/// merge over multiple sorted partitions produces global lex order
/// in one pass.
fn sort_partition_to_file<const N: usize>(
    in_path: &Path,
    out_path: &Path,
    max_partition_bytes: u64,
    scratch_dir: &Path,
    partition_label: &str,
    lex_rank: &[u32],
) -> Result<(), BuildError> {
    let mut iter = open_partition_sorted::<N>(
        in_path,
        max_partition_bytes,
        scratch_dir,
        partition_label,
        lex_rank,
    )?;
    let mut w = BufWriter::with_capacity(PARTITION_BUF_SIZE, File::create(out_path)?);
    let mut batch: Vec<[u32; N]> = Vec::with_capacity(SORT_OUTPUT_BATCH_TRIPLES);
    while let Some(triple) = iter.next_with(lex_rank) {
        let t = triple?;
        batch.push(t);
        if batch.len() == SORT_OUTPUT_BATCH_TRIPLES {
            #[cfg(target_endian = "little")]
            {
                w.write_all(bytemuck::cast_slice::<[u32; N], u8>(&batch))?;
            }
            #[cfg(not(target_endian = "little"))]
            for t in &batch {
                write_record(&mut w, t)?;
            }
            batch.clear();
        }
    }
    if !batch.is_empty() {
        #[cfg(target_endian = "little")]
        {
            w.write_all(bytemuck::cast_slice::<[u32; N], u8>(&batch))?;
        }
        #[cfg(not(target_endian = "little"))]
        for t in &batch {
            write_record(&mut w, t)?;
        }
    }
    w.flush()?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_helpers::default_tokenizer as tokenizer;

    #[test]
    fn register_column_returns_sequential_ids() {
        let mut b = FtsBuilder::new(tokenizer());
        assert_eq!(
            b.register_column("title".into(), false)
                .expect("register column"),
            0
        );
        assert_eq!(
            b.register_column("body".into(), false)
                .expect("register column"),
            1
        );
        assert_eq!(
            b.register_column("tag".into(), false)
                .expect("register column"),
            2
        );
    }

    #[test]
    fn register_column_rejects_separator_byte() {
        let mut b = FtsBuilder::new(tokenizer());
        let bad = String::from("ti\x1Ftle");
        let err = b.register_column(bad, false).expect_err("expected error");
        assert!(matches!(err, BuildError::ReservedSeparatorInColumnName(_)));
    }

    #[test]
    fn register_column_rejects_reserved_prefix() {
        let mut b = FtsBuilder::new(tokenizer());
        let err = b
            .register_column("inf.title".into(), false)
            .expect_err("expected error");
        assert!(matches!(err, BuildError::ReservedPrefixInColumnName(_)));
    }

    #[test]
    fn register_column_rejects_duplicates() {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("title".into(), false)
            .expect("register column");
        let err = b
            .register_column("title".into(), false)
            .expect_err("expected error");
        assert!(matches!(err, BuildError::DuplicateColumnName(_)));
    }

    #[test]
    fn add_doc_unknown_column_id_errors() {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("title".into(), false)
            .expect("register column");
        let err = b.add_doc(99, 0, "text").expect_err("expected error");
        assert!(matches!(err, BuildError::FtsColumnTypeInvalid { .. }));
    }

    #[test]
    fn add_doc_reuses_term_frequency_table_capacity() {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("title".into(), false)
            .expect("register column");
        b.add_doc(0, 0, "alpha beta gamma delta epsilon zeta eta theta")
            .expect("add first doc");

        assert!(b.doc_tf.is_empty(), "per-document table must be drained");
        let capacity = b.doc_tf.capacity();
        assert!(capacity > 0, "first document must allocate table buckets");

        b.add_doc(0, 1, "alpha beta alpha").expect("add second doc");
        assert!(b.doc_tf.is_empty(), "per-document table must be drained");
        assert_eq!(
            b.doc_tf.capacity(),
            capacity,
            "subsequent documents must reuse the existing buckets"
        );
    }

    #[tokio::test]
    async fn add_doc_accumulates_tf_within_doc() {
        use bytes::Bytes;

        use crate::superfile::fts::reader::{BoolMode, FtsReader};

        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("title".into(), false)
            .expect("register column");
        b.add_doc(0, 0, "rust rust rust async").expect("add doc");

        let blob = Bytes::from(b.finish().expect("finish"));
        let r =
            FtsReader::open(blob, r#"[{"name":"title","tokenizer":"ascii_lower"}]"#).expect("open");
        let rust_hits = r
            .search("title", &["rust"], 10, BoolMode::Or)
            .await
            .expect("rust search");
        let async_hits = r
            .search("title", &["async"], 10, BoolMode::Or)
            .await
            .expect("async search");
        assert_eq!(rust_hits.len(), 1);
        assert_eq!(rust_hits[0].0, 0);
        assert_eq!(async_hits.len(), 1);
        assert_eq!(async_hits[0].0, 0);
    }

    #[tokio::test]
    async fn cross_column_same_term_stays_isolated_through_round_trip() {
        // A term that appears in two different columns must keep
        // its posting lists scoped per column in the emitted FST +
        // posting region. This also exercises the spill-backed
        // accumulator: column id is implicit in the selected partition
        // set, while the final FST key remains `<col>\x1F<term>`.
        use bytes::Bytes;

        use crate::superfile::fts::reader::{BoolMode, FtsReader};

        let mut b = FtsBuilder::new(tokenizer());
        let title_id = b
            .register_column("title".into(), false)
            .expect("register title");
        let body_id = b
            .register_column("body".into(), false)
            .expect("register body");

        // Doc 0: "rust" + "tokio" in title, "rust" + "async" in body.
        // Doc 1: only in body — "rust".
        // Doc 2: only in title — "rust".
        b.add_doc(title_id, 0, "rust tokio")
            .expect("add title doc 0");
        b.add_doc(body_id, 0, "rust async").expect("add body doc 0");
        b.add_doc(body_id, 1, "rust").expect("add body doc 1");
        b.add_doc(title_id, 1, "rust").expect("add title doc 1");

        // Round-trip through finish() + FtsReader::search. The
        // reader looks up via `dict::make_key(column, term)`, so this
        // is the strict on-disk equivalent of "two columns share a
        // term — does each see its own postings?"
        let blob = Bytes::from(b.finish().expect("finish"));
        let json = r#"[{"name":"title","tokenizer":"ascii_lower"},{"name":"body","tokenizer":"ascii_lower"}]"#;
        let r = FtsReader::open(blob, json).expect("open");

        // "rust" in title returns title's docs (0, 1) and no others.
        let hits_t = r
            .search("title", &["rust"], 10, BoolMode::Or)
            .await
            .expect("title search");
        let ids_t: Vec<u32> = hits_t.iter().map(|(d, _)| *d).collect();
        assert_eq!(ids_t.len(), 2, "title 'rust' hit count");
        assert!(ids_t.contains(&0));
        assert!(ids_t.contains(&1));

        // "rust" in body also returns its own docs (0, 1). Same ids
        // by coincidence; what matters is the search is scoped to
        // body's posting list, not title's.
        let hits_b = r
            .search("body", &["rust"], 10, BoolMode::Or)
            .await
            .expect("body search");
        let ids_b: Vec<u32> = hits_b.iter().map(|(d, _)| *d).collect();
        assert_eq!(ids_b.len(), 2, "body 'rust' hit count");
        assert!(ids_b.contains(&0));
        assert!(ids_b.contains(&1));

        // Cross-leak negative: a term that lives only in body
        // (`async`) must NOT be findable in title, and vice versa
        // (`tokio` in body).
        let hits_async_in_title = r
            .search("title", &["async"], 10, BoolMode::Or)
            .await
            .expect("title async search");
        assert!(
            hits_async_in_title.is_empty(),
            "title must not return 'async' (lives only in body)"
        );
        let hits_tokio_in_body = r
            .search("body", &["tokio"], 10, BoolMode::Or)
            .await
            .expect("body tokio search");
        assert!(
            hits_tokio_in_body.is_empty(),
            "body must not return 'tokio' (lives only in title)"
        );
    }

    #[test]
    fn add_doc_tracks_doc_lengths_clamped() {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("body".into(), false)
            .expect("register column");
        b.add_doc(0, 0, "alpha beta gamma").expect("add doc");
        b.add_doc(0, 1, "").expect("add doc"); // zero-token doc
        b.add_doc(0, 2, "delta").expect("add doc");
        let col = &b.columns[0];
        assert_eq!(col.doc_lengths, vec![3, 0, 1]);
        assert_eq!(col.total_tokens, 4);
    }

    #[test]
    fn add_doc_updates_n_docs_per_call() {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("body".into(), false)
            .expect("register column");
        // Contract: local_doc_id is consecutive from 0 (per column).
        // n_docs ends up == max(local_doc_id) + 1 == call count.
        b.add_doc(0, 0, "a").expect("add doc");
        b.add_doc(0, 1, "b").expect("add doc");
        b.add_doc(0, 2, "c").expect("add doc");
        assert_eq!(b.n_docs, 3);
    }

    #[test]
    fn finish_emits_valid_header() {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("title".into(), false)
            .expect("register column");
        b.add_doc(0, 0, "hello world").expect("add doc");
        let blob = b.finish().expect("finish");

        // Magic.
        assert_eq!(&blob[0..8], format::fts::MAGIC);
        // Version — new code always writes the v2 (positions) layout.
        let version = u32::from_le_bytes([blob[8], blob[9], blob[10], blob[11]]);
        assert_eq!(version, format::fts::VERSION_V2);
        // n_columns.
        let n_cols = u32::from_le_bytes([blob[12], blob[13], blob[14], blob[15]]);
        assert_eq!(n_cols, 1);
        // n_docs (u32 at 16..20).
        let n_docs = u32::from_le_bytes([blob[16], blob[17], blob[18], blob[19]]);
        assert_eq!(n_docs, 1);
        // n_terms_total = 2 ("hello", "world") (u32 at 20..24).
        let n_terms = u32::from_le_bytes([blob[20], blob[21], blob[22], blob[23]]);
        assert_eq!(n_terms, 2);
        // fst_offset == the v2 header size (u64 at 24..32).
        let mut buf = [0u8; 8];
        buf.copy_from_slice(&blob[24..32]);
        let fst_off = u64::from_le_bytes(buf);
        assert_eq!(fst_off, format::fts::HEADER_SIZE_V2 as u64);
    }

    /// Determinism gate: two independent in-RAM builds over the
    /// same corpus must emit byte-identical blobs. Catches hasher
    /// / iteration-order regressions on the in-RAM finish path.
    #[test]
    fn finish_to_matches_finish_byte_for_byte() {
        fn build() -> FtsBuilder {
            let mut b = FtsBuilder::new(tokenizer());
            b.register_column("title".into(), false)
                .expect("register title");
            for (i, text) in [
                "rust async rust",
                "tokio runtime",
                "rust search engine",
                "async search",
            ]
            .iter()
            .enumerate()
            {
                b.add_doc(0, i as u32, text).expect("add doc");
            }
            b
        }

        let via_finish = build().finish().expect("finish");
        let mut via_finish_to = Vec::new();
        build()
            .finish_to(&mut via_finish_to)
            .expect("finish_to Vec");
        assert_eq!(via_finish_to, via_finish);
    }

    #[tokio::test]
    async fn finish_to_temp_file_round_trips_through_reader() {
        use std::io::BufWriter;

        use bytes::Bytes;

        use crate::superfile::fts::reader::{BoolMode, FtsReader};

        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("title".into(), false)
            .expect("register title");
        for i in 0..256u32 {
            b.add_doc(0, i, &format!("common term{i:03}"))
                .expect("add doc");
        }

        let tmp = tempfile::tempdir().expect("tempdir");
        let path = tmp.path().join("fts.blob");
        {
            let file = File::create(&path).expect("create blob");
            let writer = BufWriter::new(file);
            b.finish_to(writer).expect("finish_to file");
        }
        let blob = fs::read(&path).expect("read blob");
        let r = FtsReader::open(
            Bytes::from(blob),
            r#"[{"name":"title","tokenizer":"ascii_lower"}]"#,
        )
        .expect("open FTS reader");
        let hits = r
            .search("title", &["common"], 10, BoolMode::Or)
            .await
            .expect("search");
        assert_eq!(hits.len(), 10);
    }

    #[test]
    fn finish_with_no_docs_still_produces_valid_blob() {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("title".into(), false)
            .expect("register column");
        let blob = b.finish().expect("finish");
        assert_eq!(&blob[0..8], format::fts::MAGIC);
        // n_docs == 0 (u32 at 16..20), n_terms_total == 0 (u32 at 20..24).
        assert_eq!(
            u32::from_le_bytes([blob[16], blob[17], blob[18], blob[19]]),
            0
        );
        assert_eq!(
            u32::from_le_bytes([blob[20], blob[21], blob[22], blob[23]]),
            0
        );
    }

    #[test]
    fn small_build_stays_in_ram_no_spill_files_created() {
        // Mirror of vector's "small build never touches the disk
        // during add_doc" gate. With the default spill threshold
        // (256 MiB) a 100-doc build can never cross it.
        let parent = tempfile::tempdir().expect("parent");
        let mut b = FtsBuilder::with_scratch(tokenizer(), parent.path().to_path_buf())
            .expect("with_scratch");
        b.register_column("body".into(), false)
            .expect("register col");
        for i in 0..100u32 {
            b.add_doc(0, i, &format!("alpha beta gamma{i}"))
                .expect("add doc");
        }
        // Every column must still be in InRam mode.
        for cp in &b.postings {
            assert!(
                !cp.is_spilled(),
                "small build must not have spilled to disk"
            );
        }
        // And the scratch tempdir under the override must contain no
        // posting partition files yet (FtsBuilder's scratch tempdir is
        // a *sub*directory of `parent`).
        let mut spill_files_found = 0usize;
        for entry in walkdir_files(parent.path()) {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with("fts_col") && name.ends_with(".bin") {
                spill_files_found += 1;
            }
        }
        assert_eq!(
            spill_files_found, 0,
            "small build must not pre-create posting spill files"
        );
        // Sanity: finish_to still produces a working blob via the
        // in-RAM path.
        let _blob = b.finish().expect("finish");
    }

    #[test]
    fn build_above_threshold_spills_and_matches_in_ram_byte_for_byte() {
        // Threshold mode = real test: a low spill threshold forces
        // the same corpus to take the spilled finish_to path; result
        // must match the in-RAM finish byte-for-byte. This is the
        // streaming-FST regression gate — the spilled path uses
        // `StreamingDictBuilder` writing to a scratch file, while
        // the in-RAM path uses the in-memory `DictBuilder`. Both
        // must produce identical FST bytes.
        fn build_corpus(b: &mut FtsBuilder) {
            b.register_column("body".into(), false)
                .expect("register col");
            // 1000 docs, each unique → 1000+ distinct terms forces
            // partitions to fill if threshold is low.
            for i in 0..1000u32 {
                b.add_doc(
                    0,
                    i,
                    &format!("common shared term{i:04} payload{i:04} extra word{i:04}"),
                )
                .expect("add doc");
            }
        }

        let mut baseline = FtsBuilder::new(tokenizer());
        build_corpus(&mut baseline);
        // Baseline must stay in RAM.
        for cp in &baseline.postings {
            assert!(!cp.is_spilled(), "baseline must stay in RAM");
        }
        let baseline_blob = baseline.finish().expect("finish baseline");

        // Force spill via low threshold. 16 KiB is well below the
        // corpus's accumulator size. Pin the scratch dir under a
        // tempdir we control so we can inspect on-disk partition
        // files mid-build (counterpart to the negative assertion in
        // `small_build_stays_in_ram_no_spill_files_created`).
        let parent = tempfile::tempdir().expect("parent");
        let mut spilled = FtsBuilder::with_scratch(tokenizer(), parent.path().to_path_buf())
            .expect("with_scratch");
        spilled.set_spill_threshold_bytes(16 * 1024);
        build_corpus(&mut spilled);
        let any_spilled = spilled.postings.iter().any(|c| c.is_spilled());
        assert!(any_spilled, "low threshold must force spill");
        // Positive walkdir assert: at least one `fts_col*.bin`
        // partition spill file must exist before `finish()`
        // consumes the builder and drops the scratch tempdir. This
        // gates against future refactors that keep the `Spilled`
        // variant flag but bypass the on-disk write path.
        let mut spill_files_found = 0usize;
        for entry in walkdir_files(parent.path()) {
            let name = entry.file_name().to_string_lossy().to_string();
            if name.starts_with("fts_col") && name.ends_with(".bin") {
                spill_files_found += 1;
            }
        }
        assert!(
            spill_files_found > 0,
            "spilled build must materialise at least one fts_col*.bin partition file on disk"
        );
        let spilled_blob = spilled.finish().expect("finish spilled");

        assert_eq!(
            spilled_blob, baseline_blob,
            "streaming-FST + spill path must produce byte-identical blob"
        );
    }

    /// Walk a directory recursively yielding only files.
    /// Local helper used by `small_build_stays_in_ram_no_spill_files_created`;
    /// avoids pulling in a dev-dep on `walkdir` for one test.
    fn walkdir_files(root: &Path) -> Vec<fs::DirEntry> {
        let mut out = Vec::new();
        let mut stack: Vec<PathBuf> = vec![root.to_path_buf()];
        while let Some(dir) = stack.pop() {
            let rd = match fs::read_dir(&dir) {
                Ok(r) => r,
                Err(_) => continue,
            };
            for entry in rd.flatten() {
                let ft = match entry.file_type() {
                    Ok(t) => t,
                    Err(_) => continue,
                };
                if ft.is_dir() {
                    stack.push(entry.path());
                } else if ft.is_file() {
                    out.push(entry);
                }
            }
        }
        out
    }

    #[test]
    fn external_merge_path_matches_in_memory_path_byte_for_byte() {
        // Drive the over-budget branch of `open_partition_sorted`: a
        // single very common term gets hashed into one partition and
        // its on-disk records exceed an aggressively low
        // `max_partition_bytes`, forcing chunked sort + k-way merge.
        // The encoded blob must match a baseline build that used the
        // default (effectively unbounded) per-partition budget.
        fn build_corpus(builder: &mut FtsBuilder) {
            builder
                .register_column("body".into(), false)
                .expect("register col");
            // `common` appears in every doc → one term dominates one
            // hash partition. ~600 docs is enough that the per-record
            // bytes for that partition pass a 4 KiB budget.
            for i in 0..600u32 {
                builder
                    .add_doc(0, i, &format!("common term{i:04} payload{i:04}"))
                    .expect("add doc");
            }
        }

        // Baseline: force the *spilled* finish path (low spill
        // threshold), but leave `max_partition_bytes` at its
        // effectively-unbounded default so every partition fits in
        // memory and `open_partition_sorted` takes the in-memory
        // branch. This isolates the variable under test (in-memory
        // partition sort vs external merge) from the baseline's
        // identity (the spilled finish path).
        let mut baseline = FtsBuilder::new(tokenizer());
        baseline.set_spill_threshold_bytes(1);
        build_corpus(&mut baseline);
        let baseline_blob = baseline.finish().expect("finish baseline");

        // Tight budget forces external merge. The column must
        // spill (`set_spill_threshold_bytes(1)`) so the spilled
        // finish path is even taken; then 1 KiB per partition is
        // well below the dominant partition's on-disk size, so the
        // merge path is exercised on at least one partition.
        finish_debug::reset();
        let mut tight = FtsBuilder::new(tokenizer());
        tight.set_spill_threshold_bytes(1);
        tight.set_max_partition_bytes(1024);
        build_corpus(&mut tight);
        let tight_blob = tight.finish().expect("finish tight");

        assert_eq!(
            tight_blob, baseline_blob,
            "external-merge path must produce identical blob bytes"
        );
        // Positive gate: at least one sorted-chunk file must have
        // been written during the tight build. Without this assert
        // the test would pass trivially if a future refactor made
        // every partition fit in budget.
        let chunks = finish_debug::observed();
        assert!(
            !chunks.is_empty(),
            "external-merge path must have written at least one sorted-chunk file; \
             observed chunks were empty (test no longer exercises the over-budget branch)"
        );
    }

    #[test]
    fn scratch_dir_under_with_scratch_is_removed_after_finish() {
        // `with_scratch(PathBuf)` lets operators pin spill files to
        // instance-store NVMe. The `tempfile::TempDir` produced under the
        // override must still be cleaned up when the builder is
        // consumed by `finish`; if it isn't, repeated builds leak
        // disk. This test asserts the directory the builder created
        // under the override path is gone after the build.
        let parent = tempfile::tempdir().expect("parent tempdir");
        let dir_count_before = fs::read_dir(parent.path()).expect("read parent").count();

        let mut b = FtsBuilder::with_scratch(tokenizer(), parent.path().to_path_buf())
            .expect("with_scratch");
        b.register_column("body".into(), false)
            .expect("register col");
        b.add_doc(0, 0, "alpha beta gamma").expect("add doc");
        let _blob = b.finish().expect("finish");

        let dir_count_after = fs::read_dir(parent.path()).expect("read parent").count();
        assert_eq!(
            dir_count_after, dir_count_before,
            "FtsBuilder scratch tempdir leaked under override path"
        );
    }

    #[tokio::test]
    async fn configurable_spill_partitions_round_trips_through_reader() {
        use bytes::Bytes;

        use crate::superfile::fts::reader::{BoolMode, FtsReader};

        // Higher partition count: more files, smaller per-partition
        // working set. Must still produce a queryable blob.
        let mut b = FtsBuilder::new(tokenizer());
        b.set_spill_partitions(256).expect("set partitions");
        b.register_column("body".into(), false)
            .expect("register col");
        for i in 0..50u32 {
            b.add_doc(0, i, &format!("alpha beta gamma{i:02}"))
                .expect("add doc");
        }
        let blob = b.finish().expect("finish");
        let r = FtsReader::open(
            Bytes::from(blob),
            r#"[{"name":"body","tokenizer":"ascii_lower"}]"#,
        )
        .expect("open reader");
        let hits = r
            .search("body", &["alpha"], 100, BoolMode::Or)
            .await
            .expect("search alpha");
        assert_eq!(hits.len(), 50, "alpha is in every doc");
    }

    #[test]
    fn finish_offsets_are_consistent() {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("body".into(), false)
            .expect("register column");
        for i in 0..10 {
            b.add_doc(0, i, &format!("term{i} common"))
                .expect("add doc");
        }
        let blob = b.finish().expect("finish");

        // Header layout post-u32-narrowing: fst_offset at 24..32,
        // postings_offset at 32..40, doc_lengths_table_offset at 40..48.
        let mut buf = [0u8; 8];
        buf.copy_from_slice(&blob[24..32]);
        let fst_off = u64::from_le_bytes(buf) as usize;
        buf.copy_from_slice(&blob[32..40]);
        let postings_off = u64::from_le_bytes(buf) as usize;
        buf.copy_from_slice(&blob[40..48]);
        let dir_off = u64::from_le_bytes(buf) as usize;

        assert_eq!(fst_off, format::fts::HEADER_SIZE_V2);
        assert!(postings_off > fst_off, "postings after FST");
        assert!(dir_off > postings_off, "directory after postings");
        assert!(dir_off <= blob.len(), "directory offset within blob");
        buf.copy_from_slice(&blob[48..56]);
        let positions_off = u64::from_le_bytes(buf) as usize;
        assert!(positions_off > postings_off, "positions after postings");
        assert!(dir_off > positions_off, "directory after positions");
    }

    #[test]
    fn set_spill_partitions_rejects_after_register_column() {
        // Must be called before the first `register_column`.
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("body".into(), false)
            .expect("register col");
        let err = b.set_spill_partitions(16).expect_err("expected error");
        match err {
            BuildError::Io(e) => {
                assert!(e.to_string().contains("before any register_column"));
            }
            other => panic!("expected Io error, got {:?}", other),
        }
    }

    #[test]
    fn set_spill_partitions_rejects_zero() {
        let mut b = FtsBuilder::new(tokenizer());
        let err = b.set_spill_partitions(0).expect_err("expected error");
        match err {
            BuildError::Io(e) => assert!(e.to_string().contains("must be ≥ 1")),
            other => panic!("expected Io error, got {:?}", other),
        }
    }

    #[test]
    fn set_spill_partitions_rejects_non_power_of_two() {
        // Partition selection is `term_id & (n - 1)`, only correct for
        // power-of-two `n`.
        const NON_PO2: usize = 7;
        let mut b = FtsBuilder::new(tokenizer());
        let err = b.set_spill_partitions(NON_PO2).expect_err("expected error");
        match err {
            BuildError::Io(e) => assert!(e.to_string().contains("power of two")),
            other => panic!("expected Io error, got {:?}", other),
        }
    }

    #[test]
    fn read_partition_triples_empty_file_is_empty() {
        // An empty spill partition file decodes to zero triples.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("empty.part");
        fs::write(&path, []).expect("write empty file");
        let triples = read_partition_records::<PLAIN_RECORD_LANES>(&path).expect("read empty");
        assert!(triples.is_empty());
    }

    #[test]
    fn read_partition_triples_round_trips_le_bytes() {
        // Spill files are a contiguous run of 12-byte little-endian
        // `[term_id, doc_id, tf]` triples; decoding restores them.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("good.part");
        let mut bytes = Vec::new();
        for field in [3u32, 4, 5, 6, 7, 8] {
            bytes.extend_from_slice(&field.to_le_bytes());
        }
        fs::write(&path, &bytes).expect("write triples");
        let triples = read_partition_records::<PLAIN_RECORD_LANES>(&path).expect("read triples");
        assert_eq!(triples, vec![[3u32, 4, 5], [6u32, 7, 8]]);
    }

    #[test]
    fn read_partition_triples_rejects_non_multiple_length() {
        // A file whose byte length isn't a multiple of the 12-byte
        // triple size is malformed and must error.
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("ragged.part");
        // One full triple plus a stray byte.
        fs::write(
            &path,
            vec![0u8; mem::size_of::<[u32; PLAIN_RECORD_LANES]>() + 1],
        )
        .expect("write ragged file");
        let err = read_partition_records::<PLAIN_RECORD_LANES>(&path).expect_err("expected error");
        match err {
            BuildError::Io(e) => {
                assert_eq!(e.kind(), ErrorKind::InvalidData);
                assert!(e.to_string().contains("not a multiple"));
            }
            other => panic!("expected Io error, got {:?}", other),
        }
    }

    #[test]
    fn merge_entry_orders_by_sort_key_reversed() {
        // `MergeEntry` is a min-heap entry: `Ord` is reversed so a
        // BinaryHeap (max-heap) pops the smallest sort_key first. This
        // exercises the derived `PartialEq` / `PartialOrd` bridges too.
        let small = MergeEntry {
            sort_key: 10,
            rec: [1u32, 10, 1],
            reader_idx: 0,
        };
        let large = MergeEntry {
            sort_key: 20,
            rec: [2u32, 20, 1],
            reader_idx: 1,
        };
        // Reversed ordering: the smaller sort_key is the "greater"
        // entry so the max-heap surfaces it first.
        assert_eq!(small.cmp(&large), Ordering::Greater);
        assert_eq!(small.partial_cmp(&large), Some(Ordering::Greater));
        assert!(small != large);

        let small_dup = MergeEntry {
            sort_key: 10,
            rec: [9u32, 10, 9],
            reader_idx: 0,
        };
        // Equality is keyed on the comparator (sort_key then
        // reader_idx); the record lanes are payload and don't
        // affect it.
        assert!(small == small_dup);

        let mut heap: BinaryHeap<MergeEntry<PLAIN_RECORD_LANES>> = BinaryHeap::new();
        heap.push(large);
        heap.push(small);
        assert_eq!(heap.pop().expect("non-empty heap").sort_key, 10);
    }

    // ---- positional format (v2 blob) ----

    /// Rewrite a freshly-built positionless v2 blob into the legacy v1
    /// layout: version 1, 48-byte header (drop the positions-offset
    /// field), the empty positions region (4-byte CRC) removed, and
    /// every absolute offset — the three header offsets plus each
    /// doc-lengths directory entry's array offset — shifted
    /// accordingly. This is exactly the byte layout pre-positions
    /// code wrote, letting the "new code reads v1" contract be tested
    /// without keeping a binary fixture.
    fn synthesize_v1_blob(v2: &[u8]) -> Vec<u8> {
        const V2_HEADER: usize = 56;
        const V1_HEADER: usize = 48;
        const HEADER_SHRINK: u64 = (V2_HEADER - V1_HEADER) as u64;
        const EMPTY_REGION_CRC: u64 = 4;

        let read_u64 = |at: usize| u64::from_le_bytes(v2[at..at + 8].try_into().expect("8 bytes"));
        let read_u32 = |at: usize| u32::from_le_bytes(v2[at..at + 4].try_into().expect("4 bytes"));
        assert_eq!(read_u32(8), format::fts::VERSION_V2);
        let fst_off = read_u64(24);
        let postings_off = read_u64(32);
        let doc_lengths_off = read_u64(40);
        let positions_off = read_u64(48);
        assert_eq!(
            doc_lengths_off - positions_off,
            EMPTY_REGION_CRC,
            "synthesis requires a positionless blob (empty region)"
        );
        let n_columns = read_u32(12) as usize;

        let mut out = Vec::with_capacity(v2.len() - V2_HEADER + V1_HEADER);
        out.extend_from_slice(&v2[0..8]); // magic
        out.extend_from_slice(&format::fts::VERSION_V1_LEGACY.to_le_bytes());
        out.extend_from_slice(&v2[12..24]); // n_columns, n_docs, n_terms
        out.extend_from_slice(&(fst_off - HEADER_SHRINK).to_le_bytes());
        out.extend_from_slice(&(postings_off - HEADER_SHRINK).to_le_bytes());
        let v1_doc_lengths_off = doc_lengths_off - HEADER_SHRINK - EMPTY_REGION_CRC;
        out.extend_from_slice(&v1_doc_lengths_off.to_le_bytes());
        // FST + postings regions byte-for-byte (their internal offsets
        // are region-relative).
        out.extend_from_slice(&v2[V2_HEADER..positions_off as usize]);
        // Skip the empty positions region; doc-lengths directory
        // entries carry ABSOLUTE array offsets — shift each by the
        // total shrink. Entry layout: column_id u32 | array_off u64 |
        // avgdl u32 (16 bytes), then a directory CRC we must
        // recompute since its bytes changed.
        let dir_start = doc_lengths_off as usize;
        let dir_size = n_columns * 16;
        let mut dir = Vec::with_capacity(dir_size);
        for c in 0..n_columns {
            let e = dir_start + c * 16;
            dir.extend_from_slice(&v2[e..e + 4]);
            let arr_off = read_u64(e + 4) - HEADER_SHRINK - EMPTY_REGION_CRC;
            dir.extend_from_slice(&arr_off.to_le_bytes());
            dir.extend_from_slice(&v2[e + 12..e + 16]);
        }
        let dir_crc = crc32c(&dir);
        out.extend_from_slice(&dir);
        out.extend_from_slice(&dir_crc.to_le_bytes());
        // Per-column arrays (+ their CRCs) byte-for-byte.
        out.extend_from_slice(&v2[dir_start + dir_size + 4..]);
        out
    }

    /// Spill-forcing variant of [`build_title_blob`]: a 1-byte
    /// threshold pushes the column through the in-RAM → spill
    /// transition on the first doc; `max_partition_bytes` under the
    /// partition size additionally forces the chunked external merge.
    fn build_title_blob_spilled(
        docs: &[String],
        positional: bool,
        max_partition_bytes: Option<u64>,
    ) -> bytes::Bytes {
        let mut b = FtsBuilder::new(tokenizer());
        b.set_spill_threshold_bytes(1);
        if let Some(m) = max_partition_bytes {
            b.set_max_partition_bytes(m);
        }
        b.register_column("title".into(), positional)
            .expect("register column");
        for (i, text) in docs.iter().enumerate() {
            b.add_doc(0, i as u32, text).expect("add doc");
        }
        bytes::Bytes::from(b.finish().expect("finish"))
    }

    /// The full positional query battery must agree bit-for-bit
    /// across build paths: spilled positional vs in-RAM positional vs
    /// in-RAM positionless. Covers the spilled capture (5-lane
    /// records + positions blobs), the in-RAM → spill transition
    /// carrying accumulated runs, the lex-order merge's run assembly,
    /// and the df=1 inline packing fed from the spill path.
    async fn assert_title_blobs_agree(
        a: bytes::Bytes,
        a_json: &str,
        b: bytes::Bytes,
        b_json: &str,
        k: usize,
    ) {
        use crate::superfile::fts::reader::{BoolMode, FtsReader};
        let ra = FtsReader::open(a, a_json).expect("open a");
        let rb = FtsReader::open(b, b_json).expect("open b");
        let queries: &[(&[&str], BoolMode)] = &[
            (&["common"], BoolMode::Or),
            (&["uniqueonce"], BoolMode::Or),
            (&["dupdup"], BoolMode::Or),
            (&["medium", "uniqueonce"], BoolMode::Or),
            (&["common", "medium"], BoolMode::And),
        ];
        for (terms, mode) in queries {
            let ha = ra.search("title", terms, k, *mode).await.expect("search a");
            let hb = rb.search("title", terms, k, *mode).await.expect("search b");
            assert_eq!(ha, hb, "results diverged for {terms:?} ({mode:?})");
            assert!(!ha.is_empty(), "corpus sanity: {terms:?} matches");
        }
        for term in ["common", "medium", "uniqueonce", "dupdup"] {
            assert_eq!(
                ra.term_df("title", term).await.expect("df a"),
                rb.term_df("title", term).await.expect("df b"),
                "df diverged for {term}"
            );
        }
    }

    #[tokio::test]
    async fn spilled_positional_build_searches_identically() {
        let docs = positional_corpus();
        let k = docs.len();
        let spilled_pos = build_title_blob_spilled(&docs, true, None);
        assert_eq!(
            u32::from_le_bytes(spilled_pos[8..12].try_into().expect("version bytes")),
            format::fts::VERSION_V2
        );
        let inram_pos = build_title_blob(&docs, true);
        let inram_plain = build_title_blob(&docs, false);
        assert_title_blobs_agree(
            spilled_pos.clone(),
            title_json(true),
            inram_pos,
            title_json(true),
            k,
        )
        .await;
        assert_title_blobs_agree(
            spilled_pos,
            title_json(true),
            inram_plain,
            title_json(false),
            k,
        )
        .await;
    }

    #[tokio::test]
    async fn spilled_positional_external_merge_searches_identically() {
        // A tiny per-partition sort budget forces the chunked
        // external-merge path over the 5-lane records.
        let docs = positional_corpus();
        let k = docs.len();
        let spilled = build_title_blob_spilled(&docs, true, Some(64));
        let inram = build_title_blob(&docs, true);
        assert_title_blobs_agree(spilled, title_json(true), inram, title_json(true), k).await;
    }

    #[tokio::test]
    async fn new_code_reads_synthesized_v1_blob() {
        use crate::superfile::fts::reader::{BoolMode, FtsReader};

        let docs = positional_corpus();
        let v2_blob = build_title_blob(&docs, false);
        let v1_blob = bytes::Bytes::from(synthesize_v1_blob(&v2_blob));
        assert_eq!(
            u32::from_le_bytes(v1_blob[8..12].try_into().expect("version bytes")),
            format::fts::VERSION_V1_LEGACY
        );

        let v1 = FtsReader::open(v1_blob, title_json(false)).expect("v1 opens");
        let v2 = FtsReader::open(v2_blob, title_json(false)).expect("v2 opens");
        let queries: &[&[&str]] = &[&["common"], &["uniqueonce"], &["common", "medium"]];
        for terms in queries {
            let a = v1
                .search("title", terms, docs.len(), BoolMode::Or)
                .await
                .expect("v1 search");
            let b = v2
                .search("title", terms, docs.len(), BoolMode::Or)
                .await
                .expect("v2 search");
            assert_eq!(a, b, "v1/v2 results diverged for {terms:?}");
            assert!(!a.is_empty());
        }
        assert_eq!(
            v1.term_df("title", "common").await.expect("v1 df"),
            v2.term_df("title", "common").await.expect("v2 df"),
        );
    }

    /// Column-json for the single "title" column, with or without the
    /// positions flag — matching what `fts_columns_json` emits.
    fn title_json(positional: bool) -> &'static str {
        match positional {
            true => r#"[{"name":"title","tokenizer":"ascii_lower","positions":true}]"#,
            false => r#"[{"name":"title","tokenizer":"ascii_lower"}]"#,
        }
    }

    /// Build a one-column blob from `docs`, positional or not.
    fn build_title_blob(docs: &[String], positional: bool) -> bytes::Bytes {
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("title".into(), positional)
            .expect("register column");
        for (i, text) in docs.iter().enumerate() {
            b.add_doc(0, i as u32, text).expect("add doc");
        }
        bytes::Bytes::from(b.finish().expect("finish"))
    }

    /// Corpus exercising every positional emit shape: a multi-block
    /// common term (> 2 × BLOCK_LEN docs), a df=1 tf=1 term (inline
    /// position packing), a df=1 tf>1 term (PFOR-forced df=1), and a
    /// medium term with within-doc repeats (multi-varint runs).
    fn positional_corpus() -> Vec<String> {
        let n_docs = 3 * BLOCK_LEN + 7;
        let mut docs = Vec::with_capacity(n_docs);
        for i in 0..n_docs {
            let mut t = String::from("common filler");
            if i % 5 == 0 {
                t.push_str(" medium medium");
            }
            if i == 42 {
                t.push_str(" uniqueonce");
            }
            if i == 43 {
                t.push_str(" dupdup dupdup dupdup");
            }
            docs.push(t);
        }
        docs
    }

    #[test]
    fn every_build_writes_v2_and_positionless_region_is_empty() {
        let docs = positional_corpus();
        let plain = build_title_blob(&docs, false);
        let positional = build_title_blob(&docs, true);

        let version_of = |blob: &bytes::Bytes| {
            u32::from_le_bytes(blob[8..12].try_into().expect("4 header bytes"))
        };
        // New code always writes v2; v1 is a read-only legacy format.
        assert_eq!(version_of(&plain), format::fts::VERSION_V2);
        assert_eq!(version_of(&positional), format::fts::VERSION_V2);

        // A positionless build's region is just the CRC-of-empty.
        let read_u64_plain =
            |at: usize| u64::from_le_bytes(plain[at..at + 8].try_into().expect("8 header bytes"));
        let region_len = read_u64_plain(40) - read_u64_plain(48);
        assert_eq!(region_len, 4, "positionless region = 4-byte CRC only");

        // The v2 positions-region offset points between the postings
        // region and the doc-lengths directory.
        let read_u64 = |blob: &bytes::Bytes, at: usize| {
            u64::from_le_bytes(blob[at..at + 8].try_into().expect("8 header bytes"))
        };
        let postings_off = read_u64(&positional, 32);
        let doc_lengths_off = read_u64(&positional, 40);
        let positions_off = read_u64(&positional, 48);
        assert!(postings_off < positions_off, "positions follow postings");
        assert!(
            positions_off < doc_lengths_off,
            "doc-lengths directory follows positions"
        );
        // The region is non-empty: the corpus has multi-doc terms
        // whose runs must land in it (only df=1 tf=1 inlines skip it).
        assert!(doc_lengths_off - positions_off > 4, "region has a body");
    }

    #[tokio::test]
    async fn positional_build_searches_identically_to_positionless() {
        use crate::superfile::fts::reader::{BoolMode, FtsReader};

        let docs = positional_corpus();
        let v1 = FtsReader::open(build_title_blob(&docs, false), title_json(false)).expect("v1");
        let v2 = FtsReader::open(build_title_blob(&docs, true), title_json(true)).expect("v2");

        // Positions must never change matching or scoring: identical
        // (doc, score) lists for every query shape — multi-block
        // common term, inline df=1 (tf=1), PFOR-forced df=1 (tf>1),
        // AND / OR multi-term.
        let queries: &[(&[&str], BoolMode)] = &[
            (&["common"], BoolMode::Or),
            (&["uniqueonce"], BoolMode::Or),
            (&["dupdup"], BoolMode::Or),
            (&["medium", "uniqueonce"], BoolMode::Or),
            (&["common", "medium"], BoolMode::And),
        ];
        let k = docs.len();
        for (terms, mode) in queries {
            let a = v1
                .search("title", terms, k, *mode)
                .await
                .expect("v1 search");
            let b = v2
                .search("title", terms, k, *mode)
                .await
                .expect("v2 search");
            assert_eq!(a, b, "results diverged for {terms:?} ({mode:?})");
            assert!(!a.is_empty(), "corpus sanity: {terms:?} matches");
        }

        // Count + df fast paths agree too (df reads the term meta's
        // first bytes — layout-stable across the stride change).
        for term in ["common", "medium", "uniqueonce", "dupdup"] {
            let a = v1.term_df("title", term).await.expect("v1 df");
            let b = v2.term_df("title", term).await.expect("v2 df");
            assert_eq!(a, b, "df diverged for {term}");
            let ca = v1
                .token_match_count("title", &[term], BoolMode::Or)
                .await
                .expect("v1 count");
            let cb = v2
                .token_match_count("title", &[term], BoolMode::Or)
                .await
                .expect("v2 count");
            assert_eq!(ca, cb, "count diverged for {term}");
        }
    }

    #[tokio::test]
    async fn mixed_columns_only_positional_column_pays() {
        use crate::superfile::fts::reader::{BoolMode, FtsReader};

        // Two columns, one positional: the blob is v2, and both
        // columns keep answering queries (each with its own term-meta
        // stride).
        let mut b = FtsBuilder::new(tokenizer());
        b.register_column("body".into(), false).expect("register");
        b.register_column("title".into(), true).expect("register");
        for i in 0..(BLOCK_LEN as u32 + 9) {
            b.add_doc(0, i, "shared bodyterm").expect("body doc");
            b.add_doc(1, i, "shared titleterm titleterm")
                .expect("title doc");
        }
        let blob = bytes::Bytes::from(b.finish().expect("finish"));
        assert_eq!(
            u32::from_le_bytes(blob[8..12].try_into().expect("version bytes")),
            format::fts::VERSION_V2
        );
        let json = r#"[{"name":"body","tokenizer":"ascii_lower"},{"name":"title","tokenizer":"ascii_lower","positions":true}]"#;
        let r = FtsReader::open(blob, json).expect("open");
        let body_hits = r
            .search("body", &["bodyterm"], 10, BoolMode::Or)
            .await
            .expect("body search");
        let title_hits = r
            .search("title", &["titleterm"], 10, BoolMode::Or)
            .await
            .expect("title search");
        assert_eq!(body_hits.len(), 10);
        assert_eq!(title_hits.len(), 10);
        // The same term string scoped to each column stays isolated.
        let shared_body = r
            .token_match_count("body", &["shared"], BoolMode::Or)
            .await
            .expect("shared body");
        assert_eq!(shared_body, BLOCK_LEN as u64 + 9);
    }
}