ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
//! The Tantivy full-text backend, in the two store layers: the connection-manager [`TantivyStore`]
//! owns ONE index ROOT — a local mmap directory tree, no server — and hands out the STATELESS
//! [`TantivyFulltext`] handle per slot.
//!
//! # THE THREE LAWS, and why each is a law rather than a preference
//!
//! Each was measured on the reference implementation, and each is stated here as the reason it is.
//!
//! ## ONE index PER SLOT, because BM25's corpus statistics are index-wide
//!
//! A slot is a DIRECTORY under the root holding its own index — its own lockfile, its own writer,
//! its own reader. Not one shared index keyed by slot, and the reason is not tidiness:
//!
//! - **The statistics pool.** Both of them: `docfreq` over `numdocs` (hence IDF), and the average
//!   document length (`avgdl`) that the length normalization divides by. One shared index would pool
//!   every slot into ONE corpus, so indexing transcripts would move captions' scores AND reorder
//!   them. A single-term query is exposed too, which is the part that surprises: IDF is then one
//!   factor common to every hit and so cannot reorder them, but `avgdl` sits inside each document's
//!   OWN length normalization, scaled by that document's OWN length, and never factors out — so a
//!   sibling slot's long documents reweight this slot's long documents against its short ones.
//!   `tests::a_sibling_slot_cannot_move_this_slot_s_bm25_ranking` is that leak as an assertion, and
//!   its two documents sit either side of the tipping point on purpose.
//! - **The writer lock is per-DIRECTORY.** A second `IndexWriter` over one directory fails
//!   `LockFailure(LockBusy)`, so under a shared index every slot would queue through one writer.
//!   Per-slot directories mean per-slot lockfiles: two handles minted from one store can hold their
//!   writers CONCURRENTLY as long as they name different slots.
//!
//! ## The keyed replace rides the IDENTITY TERM, because `delete_term` is the only door
//!
//! Tantivy deletes by a SINGLE term. Its [`delete_query`] twin — which would take a conjunction over
//! several fields — is `#[doc(hidden)]` in 0.26.1 (`src/indexer/index_writer.rs:697`), and
//! `delete_term` is a THIN WRAPPER over it: it builds a one-term `TermQuery` and calls it. So a
//! multi-field identity cannot be the delete target as separate columns; the identity has to be ONE
//! value, and this backend builds it.
//!
//! What that value must satisfy is INJECTIVITY and nothing else. It is never ranged over, never
//! sorted, never prefix-scanned — it is looked up exactly, once, by a delete — so an ordering
//! property would be a promise with no reader. [`TantivyAddress`] delivers exactly that: each append
//! writes a fixed-width big-endian `u32` length and then the field's raw bytes, so a rendered term
//! parses back into exactly ONE field sequence and the `("ab", "c")` versus `("a", "bc")` collision
//! class is structurally dead — there is no separator character to collide, because there is no
//! separator.
//!
//! `delete_term` also SWALLOWS a term it cannot resolve: it returns a bare opstamp rather than an
//! error when the term's field is not indexed (the `unwrap_or_else` at that same site). A schema
//! that made the identity field stored-only would therefore turn every keyed replace into an APPEND,
//! silently. `tests::a_keyed_replace_leaves_exactly_one_document` is what stands where that error
//! would have been.
//!
//! ## The writer is serialized by an EXCLUSIVE BORROW, because the replace is not atomic
//!
//! [`WriteContext`](FulltextWrite::WriteContext) is `&mut `[`SlotWriter`], and the exclusivity is
//! LOAD-BEARING rather than a bound left un-minimized — see that type's own doc for the mechanism
//! and the measurement. A keyed replace is `delete_term` THEN `add_document`, and a delete only
//! tombstones documents whose opstamp is LOWER than its own, so two `upsert` calls sharing one
//! writer can interleave as (delete, delete, add, add) and leave TWO documents under ONE identity.
//!
//! Both of tantivy's calls take `&self`, which is exactly the observation that misleads: `Sync` is
//! not *safe to use concurrently for this protocol*. The borrow is what forbids the interleaving,
//! and it is pinned by the doctest pair on [`SlotWriter`].
//!
//! # The schema is four fields, and each is spent
//!
//! ```text
//! source     STRING  (indexed)          the DISCRIMINANT — which source this entry came in under
//! identity   BYTES   (indexed)          the delete_term target: source ⊕ id, length-prefixed
//! key        BYTES   (stored)           the whole `R::Key` — what a hit is handed back under
//! body       TEXT    (indexed)          the tokenized text BM25 ranks — `| STORED` where the
//!                                        declaration wrote `stored`; see the posture note
//! ```
//!
//! **The discriminant is a native FIELD**, untokenized and indexed, so *which source* is a `Term` an
//! engine builds rather than something a later reader reconstructs by scanning. Nothing in this
//! crate queries it yet; `tests::the_source_word_is_a_native_term` is what keeps that property
//! measured rather than assumed, and it is the read side a fan-in will reach for.
//!
//! **The identity is `source ⊕ id`, framed**, not the id alone. Today one source writes into one
//! slot, so the source append is inert — and it is written anyway, because the alternative is an
//! identity that is injective only under a precondition nothing enforces: two sources sharing a slot
//! with overlapping id spaces would have one's write DELETE the other's entry, silently, and the
//! repair would be a reindex rather than a code change. Four bytes and a word per document buy the
//! injectivity outright.
//!
//! **The key is stored and not indexed.** It is the hit's ADDRESS — the whole chain, ancestry
//! included — and nothing looks an entry up by it: what names an entry is the identity above. A
//! caller that could search this field would have an EXISTENCE PROBE for any row from a query string
//! alone, which is the hole [`TantivyFulltextError::UnsearchableField`] closes on the other side.
//!
//! # THE ROWS THIS BACKEND NO LONGER SHIPS, and why there are none left to ship
//!
//! A block of one `impl FulltextField<TantivyFulltext> for …` — the retired per-engine row — per
//! member of [`Id`](crate::Id) stood in this file, with a compiler-instantiated SHIPPED-PARITY AUDIT
//! closing it. Both are gone, and the deletion is the column language arriving: a key reports itself
//! in COLUMNS ([`Field`](crate::Field)) and this engine LANDS them ([`TantivyTerms`] /
//! [`TantivyColumns`]), so a row is written once per TYPE and every engine reads it.
//!
//! The retired row carried the ENGINE as a parameter, which is what made all three of its axes
//! orphan-legal after the engine-specific key trait's `E0117` wall. The column language does not
//! widen that table — it deletes the axis the table existed to enumerate:
//!
//! | a new … | writes | and pairs with |
//! |---|---|---|
//! | ENGINE | `impl ColumnWriter for MyTerms` + `impl ColumnReader for MyColumns` | EVERY row anybody has written, including rows in crates it has never heard of |
//! | value TYPE | `impl Field for MyId` | EVERY engine there is, present and future |
//! | KEY | `impl Field for MyKey` | the same, with one `where` per column type |
//!
//! So the ROW TAX is dead: a vocabulary of N types across M engines was N×M impls and each new
//! engine started at zero, where it is N + M now and a new engine starts complete. The audit went
//! with it because its OBLIGATION went with it — *this crate's engine pairs this crate's
//! vocabulary* is not a question a backend can fail once a backend names no type. What replaced it
//! is `store::field`'s own audit, which is stronger where it counts: it says every member of the id
//! vocabulary is crossable AT ALL, since one row there is the only row a member now needs.
//!
//! What this backend still owes is three things, and each has a home:
//!
//! - **The KINDS.** [`ColumnWriter`] and [`ColumnReader`] have required methods and defaulted ones;
//!   this backend faces the five required writes, the five required reads and
//!   [`fixed`](ColumnReader::fixed), and deliberately leaves every other kind on its fallback — see
//!   [`TantivyTerms`]' impl, where the reason is the STORED LAYOUT rather than laziness.
//! - **The WORDS.** [`ColumnError`] is the floor a row's own refusals are raised through, and
//!   [`TantivyFulltextError`] answers it — with [`domain`](ColumnError::domain) and
//!   [`width`](ColumnError::width) overridden onto the arms this backend already had, so a
//!   `NonZero*` reading a zero and an `IpAddr` reading five octets refuse in exactly the words they
//!   refused in before.
//! - **The ROUND TRIP.** A bound only ever says a row EXISTS. Whether a row is RIGHT is
//!   `store::field`'s suite and `tests::vocabulary`'s question, and the two stay two.
//!
//! # No async runtime, and no dependency beyond tantivy
//!
//! Tantivy is a SYNCHRONOUS engine, so `upsert` and `search` do their work inline and return a
//! ready future — the shape [`LocalFsBlob`](crate::LocalFsBlob) already established here. A
//! caller wanting the work off the async thread wraps the call. The reference implementation
//! instead ran every tantivy call through `spawn_blocking`, which cost it a tokio dependency with
//! `rt` and `sync` features; this crate has no async runtime at all, and a backend is not the
//! place to acquire one.
//!
//! [`delete_query`]: https://docs.rs/tantivy/0.26.1/tantivy/struct.IndexWriter.html

use core::{
  future::{Future, ready},
  num::NonZeroUsize,
};
use std::{
  collections::HashMap,
  io,
  path::{Path, PathBuf},
  sync::{Arc, Mutex, PoisonError},
};

use smol_bytes::Utf8Bytes;
// `schema::Field` is ALIASED: `Field` is the column-language ROW in this crate, and tantivy's is a
// schema field's handle. Both are named in this file, so the foreign one wears the qualifier.
use tantivy::{
  Index, IndexReader, IndexWriter, Opstamp, ReloadPolicy, TantivyDocument, Term,
  collector::TopDocs,
  directory::MmapDirectory,
  doc,
  query::{QueryParser, QueryParserError},
  query_grammar::{UserInputAst, UserInputLeaf},
  schema::{
    BytesOptions, Field as SchemaField, IndexRecordOption, STRING, Schema, TextFieldIndexing,
    TextOptions, Value,
  },
  tokenizer::TokenizerManager,
};

use super::{
  AsyncFulltextRead, AsyncFulltextStore, AsyncFulltextWrite, ColumnError, ColumnReader,
  ColumnWriter, Connected, Field, FulltextEngine, FulltextLane, FulltextRead, FulltextStore,
  FulltextSubset, FulltextWrite, Hits, Noop, Scored,
};
use crate::{Lane, LaneIdent};

/// The searchable field an UNFANNED corpus holds — the zero-configuration lane's own.
///
/// A slot's searchable fields are its LANES: one per partition, each carrying that lane's analyzer,
/// and a corpus that declared no fan has exactly one — [`LaneIdent::UND`]'s — which is this name and
/// the only name this backend ever wrote before the fan word existed. So the byte-for-byte shape of
/// an unfanned slot is unchanged, and [`lane_field`] is the one function that says so.
///
/// The whitelist DIRECTION is unchanged and is the whole of what keeps the guard honest as the
/// schema grows: a query may name a searchable field, and every other field of the schema — the
/// stored `key` above all — is refused by default rather than admitted by default.
const SEARCHABLE_FIELD: &str = "body";

/// THE SCHEMA WORDS THIS BACKEND SPELLS ITSELF, which a lane key may therefore not take.
///
/// A lane's field is named after the lane, so a lane keyed `key` would collide with the stored
/// address — silently, since tantivy's schema builder is happy to hold two fields of one name and
/// only one of them can be resolved. `body` is here for the same reason one grain over: it is
/// [`LaneIdent::UND`]'s own field, so a second lane spelling it would be two lanes in one field.
const RESERVED_LANE_KEYS: [&str; 4] = ["source", "identity", "key", SEARCHABLE_FIELD];

/// The analyzer a lane rides where the deployment named none — tantivy's own, and the one every
/// corpus this backend ever wrote has been tokenized by.
const DEFAULT_ANALYZER: &str = "default";

/// **EVERY ANALYZER A TANTIVY BUILD SHIPS REGISTERED**, for the refusal that lists them.
///
/// It is a MEASUREMENT of `TokenizerManager::default()` and not a vocabulary: those four names are
/// what tantivy 0.26 registers, `en_stem` behind its own `stemmer` feature which this crate keeps on
/// with the rest of tantivy's defaults. Every other analyzer tantivy SHIPS — `NgramTokenizer`,
/// `RegexTokenizer`, the non-English `Stemmer`s, `AsciiFoldingFilter` — is an exported type that
/// nothing registers, so it reaches a lane the same way a third party's own does: the deployment
/// registers it on the manager and names it here. See [`TantivyStore::with_tokenizers`].
///
/// The list is restated rather than read back because tantivy's manager has no enumeration —
/// `register` and `get`, and nothing that walks it — so a refusal that wanted to print the registry
/// has nowhere to read it from. What it prints instead is what a build is GUARANTEED to hold, said
/// plainly, beside the sentence that names the door for everything else.
const SHIPPED_ANALYZERS: [&str; 4] = ["default", "raw", "en_stem", "whitespace"];

/// **ONE SLOT'S FAN, RESOLVED** — `(lane key, the analyzer name that lane's field is built with)`, in
/// the roster's own order.
///
/// It is what layer two produces at [`create_slot`](TantivyStore::create_slot) — the declaration's
/// roster joined to the deployment's table, with every name already checked against the manager —
/// and what the schema builder, the write and the read all read back. A name of its own because
/// three signatures spell it: the pair is a fact with two halves, and a reader should not have to
/// parse the type to learn which half is which.
///
/// `Arc<[…]>` for the reason the slot cache holds `Arc`s: a fan is settled once and handed out per
/// open, so a clone is a refcount rather than a walk.
type Fan = Arc<[(Utf8Bytes, Utf8Bytes)]>;

/// The schema field one lane's text is indexed into.
///
/// [`LaneIdent::UND`] keeps `body`, which is what makes an unfanned corpus byte-identical to every
/// corpus this backend wrote before lanes existed; every other lane is its own key. One function,
/// spent by the schema builder, the write and the read, so the three cannot name different fields.
fn lane_field(lane: &LaneIdent) -> &str {
  if lane == LaneIdent::UND {
    SEARCHABLE_FIELD
  } else {
    lane.as_str()
  }
}

/// **THE PER-SLOT ANALYZER TABLE** — this backend's answer to
/// [`FulltextEngine::Options`](crate::FulltextEngine::Options), one analyzer NAME per lane.
///
/// ```
/// use ingraph::LaneAnalyzers;
///
/// let knobs = LaneAnalyzers::new()
///   .with("en", "en_stem")
///   .with("rest", "whitespace");
///
/// assert_eq!(knobs.analyzer("en"), Some("en_stem"));
/// // A lane the table says nothing about rides tantivy's own `default`.
/// assert_eq!(knobs.analyzer("zh"), None);
/// ```
///
/// # It carries NAMES, and the instance stays the manager's
///
/// The ruling split a lane in two: its EXISTENCE is a declaration fact that shapes the slot, and its
/// INSTANCE is an assembly fact that arrives at boot. This is the join between them, and it is a
/// name rather than a `TextAnalyzer` for one reason — tantivy already has a registry of built
/// analyzers, so a table holding instances would be a second one, and two registries is how a
/// corpus comes to be written by one analyzer and searched by another. What a deployment does
/// instead is register its own on the manager ([`TantivyStore::with_tokenizers`]) and NAME it here.
///
/// # It is FRAMEWORK-OPEN by construction
///
/// A name is resolved against the manager the store holds, so the vocabulary is the deployment's:
/// `SHIPPED_ANALYZERS` is what a build is guaranteed to hold, and a jieba, a Thai dictionary or an
/// n-gram is one `register` call away with no word here changing. A name the manager does not hold
/// is refused AT CONSTRUCTION —
/// [`UnknownAnalyzer`](TantivyFulltextError::UnknownAnalyzer) — rather than silently falling back to
/// `default`, which is the mis-filing the whole lane layer exists to prevent.
///
/// # ABSENCE IS THE DEFAULT, and that is presence-is-enablement at this seat
///
/// A lane the table says nothing about is tokenized by tantivy's `default`, which is exactly what an
/// unfanned corpus already was. So a deployment naming no knobs at all gets the corpus it had, byte
/// for byte.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LaneAnalyzers {
  /// Lane key → analyzer name, in the order a caller named them.
  ///
  /// A `Vec` rather than a map: a roster is a handful of lanes, the lookup is a walk over four
  /// entries, and the ORDER is what a refusal lists them in.
  named: Vec<(Utf8Bytes, Utf8Bytes)>,
}

impl LaneAnalyzers {
  /// The empty table — every lane on tantivy's own `default`.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self { named: Vec::new() }
  }

  /// The same table, with `lane` tokenized by the analyzer named `analyzer`.
  ///
  /// A lane named twice keeps the LAST word, which is the ordinary shape of a builder: what a
  /// caller wrote most recently is what they meant.
  #[must_use]
  pub fn with(mut self, lane: impl Into<Utf8Bytes>, analyzer: impl Into<Utf8Bytes>) -> Self {
    self.set(lane, analyzer);
    self
  }

  /// [`with`](Self::with), in place.
  pub fn set(&mut self, lane: impl Into<Utf8Bytes>, analyzer: impl Into<Utf8Bytes>) -> &mut Self {
    let (lane, analyzer) = (lane.into(), analyzer.into());
    match self.named.iter_mut().find(|(named, _)| named == &lane) {
      Some((_, held)) => *held = analyzer,
      None => self.named.push((lane, analyzer)),
    }
    self
  }

  /// The analyzer named for `lane`, or [`None`] where the table says nothing about it.
  #[must_use]
  pub fn analyzer(&self, lane: &str) -> Option<&str> {
    self
      .named
      .iter()
      .find(|(named, _)| named.as_str() == lane)
      .map(|(_, analyzer)| analyzer.as_str())
  }

  /// Every `(lane, analyzer)` this table names, in the order they were named.
  pub fn iter(&self) -> impl ExactSizeIterator<Item = (&str, &str)> {
    self
      .named
      .iter()
      .map(|(lane, analyzer)| (lane.as_str(), analyzer.as_str()))
  }
}

/// The payload of [`TantivyFulltextError::UnknownAnalyzer`]: which lane named an analyzer, and what
/// it named.
///
/// BOXED at the error for [`SlotMismatch`]'s measured reason exactly — two [`Utf8Bytes`] inline
/// would widen every `Result` on this backend's paths past `clippy::result_large_err`'s ceiling to
/// describe a boot-time arrangement mistake.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownAnalyzer {
  lane: Utf8Bytes,
  analyzer: Utf8Bytes,
}

impl UnknownAnalyzer {
  /// The refusal `lane` earns for naming `analyzer`.
  #[must_use]
  pub fn new(lane: impl Into<Utf8Bytes>, analyzer: impl Into<Utf8Bytes>) -> Self {
    Self {
      lane: lane.into(),
      analyzer: analyzer.into(),
    }
  }

  /// The lane that named it.
  #[inline]
  #[must_use]
  pub const fn lane(&self) -> &Utf8Bytes {
    &self.lane
  }

  /// The analyzer name the manager does not hold.
  #[inline]
  #[must_use]
  pub const fn analyzer(&self) -> &Utf8Bytes {
    &self.analyzer
  }
}

/// A stored address failed to parse back into the values it was written from.
///
/// Every arm is a SHAPE failure of the stored bytes rather than a domain refusal: a value whose own
/// domain is narrower than the width it stores has no arm here, because this codec knows widths and
/// not meanings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyDecodeError {
  /// The address ended inside a length prefix or a field body.
  Truncated,
  /// A field's bytes are not the UTF-8 a [`text`](TantivyColumns::text) column demands.
  NotText,
  /// A field's width is not the 8 bytes an [`i64`](TantivyColumns::i64) or a
  /// [`u64`](TantivyColumns::u64) column demands.
  NotI64,
  /// A field's width is not the 16 bytes a [`uuid`](TantivyColumns::uuid) column demands.
  NotUuid,
  /// A field's width is not the one a [`fixed`](TantivyColumns::fixed) column demands.
  ///
  /// The arm the whole fixed-width half of the id vocabulary shares — every narrow integer, every
  /// fixed byte array, and the network family's octets. It does not carry the width it wanted, and
  /// that is the same restraint the two arms above take: a stored address is read back by the value
  /// that wrote it, so the width the read expected is the reading type's, and naming it here would
  /// put a per-row number in a codec that knows widths and not meanings.
  ///
  /// It is also what [`ColumnError::width`] lands as, so a ROW that reads its arms apart by width —
  /// the two untagged network enums — refuses in this engine's own vocabulary without naming it.
  Width,
  /// A field decoded to a value the reading type does not admit — a zero read back into a
  /// `NonZero*`.
  ///
  /// The one arm that is not about a WIDTH, and it is here because the transparency law forces it:
  /// a `NonZeroU64` writes the same eight bytes its `u64` does, so the narrowing happens on the way
  /// out and the address that fails it is well-formed. It is what [`ColumnError::domain`] lands as:
  /// the refusal is the ROW's to make and this engine's to word.
  Domain,
  /// Bytes remain after the last value was read — the stored address carries MORE than the read
  /// takes, which is a drifted column sequence rather than a corrupt byte.
  ///
  /// Raised by [`TantivyColumns::finish`], which is where the completeness question lives: the
  /// engine no longer knows what a key is, so *did the key read all of it* is asked once, by the
  /// walk that owns the read phase, after the read.
  Trailing,
}

impl core::fmt::Display for KeyDecodeError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str(match self {
      Self::Truncated => "the stored address is truncated",
      Self::NotText => "a stored field is not valid UTF-8 text",
      Self::NotI64 => "a stored field is not an 8-byte integer",
      Self::NotUuid => "a stored field is not a 16-byte uuid",
      Self::Width => "a stored field is not the width this value's read expects",
      Self::Domain => "a stored field decoded to a value this value's type does not admit",
      Self::Trailing => "the stored address has trailing bytes after the last value read",
    })
  }
}

impl core::error::Error for KeyDecodeError {}

/// THIS ENGINE'S ADDRESS VOCABULARY — the canonical binary form a key's columns seal into, and the
/// form a hit's stored address arrives in.
///
/// It is [`FulltextEngine::Address`] for [`TantivyFulltext`]: what
/// [`finalize`](FulltextEngine::finalize) hands back and what [`open`](FulltextEngine::open) spends.
/// ONE type for both directions, because it is one correspondence — an address written by a key has
/// to be readable by that same key's type, and two members would let a backend supply one half and
/// not the other.
///
/// The length prefix IS the design. Each column is written as a fixed-width big-endian `u32` length
/// and then the value's raw bytes, so a rendered address parses back into exactly one column
/// sequence and two different sequences can never render identically — where a separator-character
/// scheme has no such guarantee, since `("ab", "c")` and `("a", "bc")` concatenate to the same
/// string and any separator byte can appear inside a field. Every column is a byte-copy, never a
/// string rendering.
///
/// INJECTIVITY is the whole contract, and ordering is deliberately not part of it: the identity is
/// looked up exactly by [`delete_term`](https://docs.rs/tantivy/0.26.1/tantivy/struct.IndexWriter.html#method.delete_term)
/// and by nothing else, so a big-endian layout here buys sortability no reader spends. What the
/// big-endian widths ARE for is determinism — one value renders to one address on every host.
///
/// # It holds BYTES and no cursor, and the two phases beside it are why
///
/// Writing is [`TantivyTerms`]' and reading is [`TantivyColumns`]', so an address is a VALUE
/// between them rather than a half-consumed buffer: it is sealed once, it rides inside a hit, and it
/// is spent once when a key opens it. A cursor living here would be meaningless until opened and
/// would put two addresses holding the same bytes at different read positions out of `Eq` with each
/// other.
///
/// **THE STORED LAYOUT IS UNCHANGED, BYTE FOR BYTE**, by these three types and by the column
/// language above them — see `store::field`'s layout-parity test, which pins the shipped rows'
/// bytes against hand-written expectations that encode what is already on disk.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TantivyAddress {
  bytes: Vec<u8>,
}

/// The fixed width of one column's length prefix — portable across targets, unlike a `usize`.
const PREFIX: usize = 4;

impl TantivyAddress {
  /// An empty address — no columns.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self { bytes: Vec::new() }
  }

  /// The rendered bytes — what a `delete_term` targets and what a document stores.
  #[inline]
  #[must_use]
  pub fn as_slice(&self) -> &[u8] {
    &self.bytes
  }

  /// The bytes, owned.
  #[inline]
  #[must_use]
  pub fn into_bytes(self) -> Vec<u8> {
    self.bytes
  }
}

impl From<Vec<u8>> for TantivyAddress {
  /// A stored address — what a hit's `key` bytes become.
  #[inline]
  fn from(bytes: Vec<u8>) -> Self {
    Self { bytes }
  }
}

/// THE WRITE PHASE — [`FulltextEngine::WriteBuffer`] for [`TantivyFulltext`], and the accumulator a
/// key reports its columns into.
///
/// It is a [`ColumnWriter`], so a key hands it one TYPED column at a time and it frames each
/// directly into the bytes a tantivy `Term` is built from — `i64`, `text`, `uuid` and the rest land
/// as themselves, with no intermediate encoding in between. That is the whole economy of the column
/// language at this backend: what used to be a per-(type × engine) row calling `push_i64` is now a
/// row calling `i64`, and the byte it lands is the same byte.
///
/// NOT an address, and the type says so. [`FulltextEngine::buffer`]'s own doc names this engine as
/// the cautionary case — `TantivyAddress::default()` is the empty byte string, which is exactly the
/// coincidence that would have made a `Default` bound look right — and the split is what makes the
/// confusion unrepresentable: a half-built address has no address's type here.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TantivyTerms {
  bytes: Vec<u8>,
}

impl TantivyTerms {
  /// An empty write phase, before the first column.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self { bytes: Vec::new() }
  }

  /// The bytes framed so far — what a [`TantivyDoc`]'s identity and stored address are read out of
  /// on the way into the index.
  #[inline]
  #[must_use]
  pub fn as_slice(&self) -> &[u8] {
    &self.bytes
  }

  /// The bytes, owned — what [`FulltextEngine::finalize`] seals into a [`TantivyAddress`].
  #[inline]
  #[must_use]
  pub fn into_bytes(self) -> Vec<u8> {
    self.bytes
  }

  /// Frame one column: the `u32` big-endian length prefix, then the bytes.
  ///
  /// The one door every kind below goes through, which is what makes the layout ONE line rather than
  /// one per kind.
  ///
  /// # Panics
  ///
  /// If the column exceeds `u32::MAX` bytes. A key column is an id, not a payload, so the fixed
  /// 4-byte prefix is not widened for it.
  fn frame(&mut self, value: &[u8]) {
    let len = u32::try_from(value.len()).expect("a key column longer than u32::MAX bytes");
    self.bytes.extend_from_slice(&len.to_be_bytes());
    self.bytes.extend_from_slice(value);
  }
}

/// The REQUIRED kinds only, each framed as itself — and the defaulted kinds are deliberately left
/// alone.
///
/// [`fixed`](ColumnWriter::fixed) falls through to [`bytes`](ColumnWriter::bytes), which is what
/// keeps every narrow integer, every fixed byte array and the network family landing the exact bytes
/// this backend has always stored for them: one length prefix and the value's own big-endian
/// octets. Overriding `fixed` here would land something else and break the read of every index
/// written before the move.
impl ColumnWriter for TantivyTerms {
  #[inline]
  fn i64(&mut self, value: i64) {
    self.frame(&value.to_be_bytes());
  }

  #[inline]
  fn u64(&mut self, value: u64) {
    self.frame(&value.to_be_bytes());
  }

  /// Text rides VERBATIM — its UTF-8 bytes, with no escape and no terminator. The length prefix is
  /// what makes that safe: a text column is the only variable-width member, and it is exactly the
  /// case a separator scheme cannot make injective.
  #[inline]
  fn text(&mut self, value: &str) {
    self.frame(value.as_bytes());
  }

  #[inline]
  fn bytes(&mut self, value: &[u8]) {
    self.frame(value);
  }

  /// A uuid's sixteen RAW bytes, never the hyphenated text — the codec is already length-prefixed,
  /// so it rides as one more column with no new machinery.
  #[inline]
  fn uuid(&mut self, value: uuid::Uuid) {
    self.frame(value.as_bytes());
  }
}

/// THE READ PHASE — [`FulltextEngine::ReadBuffer`] for [`TantivyFulltext`], and the cursor a key
/// takes its columns back off.
///
/// It is minted by [`FulltextEngine::open`] out of an address it CONSUMES, so it owns the bytes and
/// borrows nothing; the cursor advances and is never rewound. A hit's address is read once, by the
/// key that owns it, in the order that key's columns were written.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TantivyColumns {
  bytes: Vec<u8>,
  at: usize,
}

impl TantivyColumns {
  /// Open a read phase over `bytes` — positioned at the first column.
  #[inline]
  #[must_use]
  pub const fn new(bytes: Vec<u8>) -> Self {
    Self { bytes, at: 0 }
  }

  /// Take the next column's raw bytes off the front.
  ///
  /// The one door every kind below goes through, so the framing is read in ONE place exactly as it
  /// is written in one.
  fn next(&mut self) -> Result<&[u8], TantivyFulltextError> {
    let prefix = self
      .bytes
      .get(self.at..self.at + PREFIX)
      .ok_or(KeyDecodeError::Truncated)?;
    // The prefix is exactly `PREFIX` bytes by the slice above.
    let len = u32::from_be_bytes(prefix.try_into().expect("a 4-byte slice")) as usize;
    let start = self.at + PREFIX;
    let end = start.checked_add(len).ok_or(KeyDecodeError::Truncated)?;
    if end > self.bytes.len() {
      return Err(KeyDecodeError::Truncated.into());
    }
    self.at = end;
    Ok(&self.bytes[start..end])
  }
}

/// The REQUIRED kinds only, mirroring [`TantivyTerms`]' writes — and
/// [`fixed`](ColumnReader::fixed), which is the one place a WIDTH is checked and therefore the one
/// kind an engine has to face itself.
///
/// Every defaulted narrow integer arrives through `fixed`, which is why they need no arm here: the
/// width is settled once and turning `N` bytes into the value they are cannot fail.
impl ColumnReader for TantivyColumns {
  type Error = TantivyFulltextError;

  #[inline]
  fn i64(&mut self) -> Result<i64, Self::Error> {
    let value: [u8; 8] = self
      .next()?
      .try_into()
      .map_err(|_| KeyDecodeError::NotI64)?;
    Ok(i64::from_be_bytes(value))
  }

  #[inline]
  fn u64(&mut self) -> Result<u64, Self::Error> {
    let value: [u8; 8] = self
      .next()?
      .try_into()
      .map_err(|_| KeyDecodeError::NotI64)?;
    Ok(u64::from_be_bytes(value))
  }

  #[inline]
  fn text(&mut self) -> Result<&str, Self::Error> {
    core::str::from_utf8(self.next()?).map_err(|_| KeyDecodeError::NotText.into())
  }

  #[inline]
  fn bytes(&mut self) -> Result<&[u8], Self::Error> {
    self.next()
  }

  #[inline]
  fn uuid(&mut self) -> Result<uuid::Uuid, Self::Error> {
    let value: [u8; 16] = self
      .next()?
      .try_into()
      .map_err(|_| KeyDecodeError::NotUuid)?;
    Ok(uuid::Uuid::from_bytes(value))
  }

  #[inline]
  fn fixed<const N: usize>(&mut self) -> Result<[u8; N], Self::Error> {
    Ok(self.next()?.try_into().map_err(|_| KeyDecodeError::Width)?)
  }

  /// Did the key take every column?
  ///
  /// The seat the retired `exhausted` verb held. It consumes the phase where that verb took an
  /// address by reference, and the difference is the whole of what the split bought: a read that has
  /// been asked whether it is whole is a read that is over.
  ///
  /// # Errors
  ///
  /// [`KeyDecodeError::Trailing`] if any column remains — a drifted column sequence rather than a
  /// corrupt byte, and a key that is not the key this entry was written under.
  #[inline]
  fn finish(self) -> Result<(), Self::Error> {
    if self.at == self.bytes.len() {
      Ok(())
    } else {
      Err(KeyDecodeError::Trailing.into())
    }
  }
}

/// ONE ENTRY under construction — [`FulltextWrite::Doc`] for [`TantivyFulltext`].
///
/// It is the whole of what this backend needs to index something, and it names no record: the
/// EMISSION fills it in, because the emission is the code that can see what a record's id, key and
/// text are. Everything typed happens there; what crosses the seam is this.
///
/// Three positions, and each is spent on one of the schema's four fields:
///
/// | position | schema field | what it is |
/// |---|---|---|
/// | `source` | `source` (indexed) + the identity's first column | the DISCRIMINANT — which source this entry came in under |
/// | identity | `identity` (indexed) | the `delete_term` target: source ⊕ id, framed |
/// | address | `key` (stored) | the whole key — what a hit is handed back under |
/// | body | `body` (indexed, stored) | the tokenized text BM25 ranks |
///
/// The SOURCE is framed into the identity by [`new`](Self::new), before anything else is appended.
/// Today one source writes into one slot, so the append is inert — and it is written anyway, because
/// the alternative is an identity that is injective only under a precondition nothing enforces: two
/// sources sharing a slot with overlapping id spaces would have one's write DELETE the other's
/// entry, silently, and the repair would be a reindex rather than a code change.
///
/// # Both accumulators are WRITE PHASES, and that is the honest type for a builder
///
/// The identity and the address are [`TantivyTerms`], not [`TantivyAddress`]es: an entry under
/// construction is exactly a key REPORTING itself, and it reports across two calls — the source at
/// [`new`](Self::new), the id at [`with_identity`](Self::with_identity). What
/// [`FulltextEngine::finalize`] seals is the same bytes; nothing here needs a sealed address,
/// because what the write path spends is a byte slice for a `Term`.
#[derive(Debug, Clone)]
pub struct TantivyDoc {
  source: Utf8Bytes,
  identity: TantivyTerms,
  address: TantivyTerms,
  /// The text this entry carries, PER LANE — lane key → the run of text that reached it.
  ///
  /// A list rather than one string, because a slot is cut into lanes and a transcript that mixes
  /// scripts reaches several of them: the fan is BY RUN and not by document, so one entry may carry
  /// Chinese for `zh` and English for `en` and land both in one keyed replace.
  ///
  /// EMPTY is an entry with no text at all, which is the same entry it always was: an unfanned
  /// corpus's [`with_body`](Self::with_body) writes one row keyed [`LaneIdent::UND`], and the write
  /// walk fills every lane the slot holds — from this list where a run reached it, and with the
  /// empty string where none did.
  bodies: Vec<(Utf8Bytes, String)>,
}

impl TantivyDoc {
  /// Begin an entry entering the index under `source` — the record's own slot word, framed into the
  /// identity as its first column.
  pub fn new(source: impl Into<Utf8Bytes>) -> Self {
    let source = source.into();
    let mut identity = TantivyTerms::new();
    identity.text(&source);
    Self {
      source,
      identity,
      address: TantivyTerms::new(),
      bodies: Vec::new(),
    }
  }

  /// Report `id`'s columns into the identity this entry replaces on.
  ///
  /// The engine's unique identity is not the whole key: this is an unbrowsable store, so what tells
  /// one entry from another is which source it came from and that source's id.
  ///
  /// `I` is a [`Field`] — ENGINE-BLIND, one impl per TYPE — where it used to be a row keyed on this
  /// engine. A declaring crate that writes one row for its id crosses into every engine there is,
  /// and this backend brings no vocabulary of its own for it to be paired against.
  #[must_use]
  pub fn with_identity<I: Field>(mut self, id: &I) -> Self {
    id.write(&mut self.identity);
    self
  }

  /// Report `key`'s columns into the stored address this entry is handed back under.
  ///
  /// The chain the key carries rides the same entry as a STORED field — read back out with every
  /// hit, which is what lets a search answer with an address rather than with a bare id.
  #[must_use]
  pub fn with_address<K: Field>(mut self, key: &K) -> Self {
    key.write(&mut self.address);
    self
  }

  /// The text to tokenize — the UNFANNED corpus's door, and the one every entry wrote before lanes
  /// existed.
  ///
  /// It writes [`LaneIdent::UND`]'s row, which is the zero-configuration lane: on a corpus that
  /// declared no fan this is the whole document, and the field it lands in is the same `body` it
  /// always was.
  #[must_use]
  pub fn with_body(self, body: impl Into<String>) -> Self {
    self.with_body_in(LaneIdent::UND.as_str(), body)
  }

  /// **THE TEXT ONE LANE TAKES** — the fan's own door, one call per run.
  ///
  /// An index-time fan cuts a transcript into [script runs](crate::script_runs), resolves each
  /// through [`lane_for`](crate::lane_for), and calls this once per lane with the text that reached
  /// it. Each lane's text is tokenized by that lane's own analyzer, which is the whole point of
  /// cutting the corpus up.
  ///
  /// A lane named TWICE has its text REPLACED rather than appended: merging same-lane runs is the
  /// router's policy and not this builder's — see
  /// [`ScriptRouter`](crate::ScriptRouter), which does exactly that on the read side — so a caller
  /// that means *and this too* joins the runs itself and calls once. Two silent policies for one
  /// question is how the write side and the read side come to disagree.
  #[must_use]
  pub fn with_body_in(mut self, lane: impl Into<Utf8Bytes>, body: impl Into<String>) -> Self {
    let (lane, body) = (lane.into(), body.into());
    match self.bodies.iter_mut().find(|(named, _)| named == &lane) {
      Some((_, held)) => *held = body,
      None => self.bodies.push((lane, body)),
    }
    self
  }

  /// The source word this entry entered under.
  #[inline]
  #[must_use]
  pub fn source(&self) -> &str {
    &self.source
  }

  /// The identity a keyed replace deletes on — source ⊕ whatever
  /// [`with_identity`](Self::with_identity) reported.
  #[inline]
  #[must_use]
  pub const fn identity(&self) -> &TantivyTerms {
    &self.identity
  }

  /// The stored address a hit is handed back under.
  #[inline]
  #[must_use]
  pub const fn address(&self) -> &TantivyTerms {
    &self.address
  }

  /// The text this entry is ranked on in the UNFANNED lane — [`LaneIdent::UND`]'s row, or the empty
  /// string where no text reached it.
  #[inline]
  #[must_use]
  pub fn body(&self) -> &str {
    self.body_in(LaneIdent::UND.as_str()).unwrap_or_default()
  }

  /// The text this entry carries for `lane`, or [`None`] where none reached it.
  #[must_use]
  pub fn body_in(&self, lane: &str) -> Option<&str> {
    self
      .bodies
      .iter()
      .find(|(named, _)| named.as_str() == lane)
      .map(|(_, body)| body.as_str())
  }

  /// Every `(lane, text)` this entry carries, in the order the lanes were written.
  pub fn bodies(&self) -> impl ExactSizeIterator<Item = (&str, &str)> {
    self
      .bodies
      .iter()
      .map(|(lane, body)| (lane.as_str(), body.as_str()))
  }
}

/// The payload of [`TantivyFulltextError::SlotMismatch`]: which slot the handle indexes into, and
/// which slot the [`SlotWriter`] it was handed is the capability for.
///
/// BOXED at the error, and that is measured rather than stylistic: a slot name is a
/// [`Utf8Bytes`] and two of them are 128 bytes, which is exactly `clippy::result_large_err`'s
/// ceiling — so carrying the pair inline would widen every `Result` on the write path, the OK arm
/// included, to describe a state that is a caller's programming error and never a runtime condition.
/// The other arms are already small, so this one variant decides the whole error's size.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SlotMismatch {
  handle: Utf8Bytes,
  writer: Utf8Bytes,
}

impl SlotMismatch {
  /// Record that a handle for `handle` was given `writer`'s write capability.
  #[inline]
  pub(crate) const fn new(handle: Utf8Bytes, writer: Utf8Bytes) -> Self {
    Self { handle, writer }
  }

  /// The slot the handle indexes into.
  #[inline]
  pub fn handle(&self) -> &str {
    &self.handle
  }

  /// The slot the [`SlotWriter`] it was given is the capability for.
  #[inline]
  pub fn writer(&self) -> &str {
    &self.writer
  }
}

/// A Tantivy full-text failure — of the manager's open or writer path, or of a handle's op.
///
/// `Debug` and no more: tantivy's own error types are neither `Clone` nor `PartialEq`, and every one
/// this backend can meet — a directory open, an IO error, a malformed query, a second writer's
/// `LockFailure` — folds into the [`Tantivy`](Self::Tantivy) arm through `TantivyError`'s own `From`
/// conversions. One backend-error surface, as the filesystem blob face has one.
#[derive(Debug)]
#[non_exhaustive]
pub enum TantivyFulltextError {
  /// A tantivy call — or the directory / IO / query-parse underneath one — failed.
  Tantivy(tantivy::TantivyError),
  /// The slot is not an identifier, so this store will not name an index directory after it. A slot
  /// NAMES the first path level under the root, which makes an unchecked one a path-traversal
  /// surface, and it is also every other backend's resource name, so it answers to the crate's ONE
  /// identifier rule rather than to a per-backend one. Rendered with `Debug` because it is
  /// caller-supplied and may carry control characters that `Display` would emit raw into a log.
  InvalidSlot(Utf8Bytes),
  /// A handle was paired with ANOTHER slot's [`SlotWriter`] — see [`SlotMismatch`]. Every slot's
  /// schema is structurally identical, so an unchecked mispairing would queue this handle's document
  /// into the writer's index — silently, with no schema, identity or error path able to catch it,
  /// and the handle's own slot left empty. One compare per document makes it loud instead.
  SlotMismatch(Box<SlotMismatch>),
  /// The query names a field this slot does not search. Only `body` is searchable, and naming any
  /// other is refused at the op head, before the index is touched.
  ///
  /// # The hole this closes
  ///
  /// A slot's schema carries the stored `key` bytes, and a `QueryParser` built `for_index(…,
  /// vec![body])` sets only the DEFAULT field for BARE terms — an explicit `field:value` still
  /// resolves against the whole schema, and for a bytes field the parser base64-DECODES the phrase
  /// into a term. So `key:<base64 of a stored address>` would be a well-formed query matching
  /// exactly the document with that key: an EXISTENCE PROBE for any row, from a caller holding only
  /// the search string.
  UnsearchableField {
    /// The field name the query string used.
    field: String,
  },
  /// The [`FulltextSubset`](crate::FulltextSubset) named a column this slot does not hold.
  ///
  /// The scope's own refusal, and the counterpart of [`UnsearchableField`](Self::UnsearchableField)
  /// on the argument the grammar is NOT trusted with: a column arriving beside the query is checked
  /// against this slot's schema before the searcher is touched, and an unheld one is NAMED rather
  /// than quietly dropped from the scope — a dropped column widens a search the caller narrowed,
  /// which is the answering-from-the-wrong-corpus class one grain down.
  ///
  /// A slot holds ONE searchable column today (`body`), so a subset naming a declaration's own field
  /// — `title` — lands here. That is the per-field DOCUMENT's absence, reported at the seam that
  /// wants it, and not a refusal of the subset grammar.
  UnheldColumn {
    /// The column the subset named.
    column: crate::FulltextColumn,
  },
  /// The [`FulltextSubset`](crate::FulltextSubset) named NO column at all — an empty
  /// [`These`](crate::FulltextSubset::These).
  ///
  /// A search over no columns has no answer to give, and both shapes it could be given are wrong:
  /// an empty result reads as *nothing matched* where nothing was asked, and falling back to the
  /// whole subject answers a question the caller did not ask. The seam leaves an empty subset to the
  /// engine on purpose — see [`FulltextSubset`](crate::FulltextSubset) — and this is that answer.
  EmptySubset,
  /// A hit's stored `key` field was absent or not bytes. This backend writes it on every document,
  /// so it signals a corrupt index — surfaced as a typed error rather than a panic, and never an
  /// expected path.
  MissingKey,
  /// A hit's stored term did not decode back into the record's key — a corrupt index, or a key whose
  /// field sequence no longer matches what was indexed.
  Key(KeyDecodeError),
  /// A ROW REFUSED, IN THE ROW'S OWN WORDS — [`ColumnError::custom`]'s arm, and the open floor the
  /// column language requires of an engine's error.
  ///
  /// A row is engine-blind, so it cannot name this type and cannot pick one of the arms above; what
  /// it has is a sentence. The two refusals the framework NAMES — a value outside the reading type's
  /// domain and a column of an unexpected width — never reach here, because this backend overrides
  /// both onto [`Key`](Self::Key) arms it already had. So what lands in this arm is a refusal from a
  /// row in a crate this one has never heard of, which is exactly the case the floor exists for.
  ///
  /// It KEEPS the words rather than dropping them: a stored address that will not decode is a
  /// corrupt-index report somebody reads, and a code with no sentence would make the one refusal
  /// this backend cannot phrase itself the one refusal with nothing to say.
  Column(String),
  /// **A LANE NAMED AN ANALYZER THIS BUILD'S MANAGER DOES NOT HOLD** — refused at construction, in
  /// the walk that shapes the slot, before a single document is written.
  ///
  /// PRESENCE IS ENABLEMENT and the other direction is the mis-filing: falling back to `default`
  /// for a lane that asked for a Chinese segmenter would index Han text one codepoint at a time and
  /// answer nothing, months later, with no error anywhere. So an unresolvable name stops the boot
  /// and says which lane asked, what it asked for, and where the answer is registered.
  UnknownAnalyzer(Box<UnknownAnalyzer>),
  /// **A LANE KEY THIS BACKEND SPELLS ITSELF** — one of `source`, `identity`, `key` or `body`.
  ///
  /// A lane's field is named after the lane, and tantivy's schema builder accepts two fields of one
  /// name while resolving only one of them, so this is refused where it is decidable rather than
  /// discovered as a corpus that quietly indexes nothing.
  ReservedLane(Utf8Bytes),
  /// **AN ENTRY NAMED A LANE THIS SLOT DOES NOT HOLD** — the write half of the roster's guardrail.
  ///
  /// [`UnroutableLane`](crate::UnroutableLane)'s sibling on the other side of the corpus: the read
  /// refuses a router that asks for a lane nobody declared, and this refuses a document that arrives
  /// for one. Accepting it would drop the text on the floor, which is the one outcome a write must
  /// not have.
  LaneAbsent(Utf8Bytes),
  /// **THE KNOB TABLE NAMED A LANE THE ROSTER DOES NOT CARRY** — an analyzer bound to nothing.
  ///
  /// The ruling's own word: a boot checks that every binding lands, and an extra one is refused BY
  /// NAME. A binding that quietly bound nothing is how a deployment comes to believe its Chinese
  /// lane has a segmenter when the roster spells the lane differently.
  UnboundAnalyzer(Utf8Bytes),
  /// **A DECLARED ROAD SEGMENTED AN ENTRY THIS BACKEND HOLDS IN ONE PIECE** —
  /// [`FulltextLane::entry`](crate::FulltextLane::entry)'s refusal, at the boundary between what a
  /// declaration said and what this engine can store.
  ///
  /// A `multi` road pushes one segment per value so that a phrase CANNOT match across two of them;
  /// this backend writes one text per lane, so the only thing it could do with several is join them
  /// — which allows exactly the match the declaration wrote the road to stop, and tells nobody. So
  /// it refuses by name, carrying the count, and the fix is at the declaration: `join` where the
  /// values belong in one value, a positional backend where they do not.
  ///
  /// ONE segment and ZERO segments are both ordinary: the identity road and `join` push exactly
  /// one, and a converter that meant to skip a value pushes none — an entry with an empty lane
  /// rather than a refusal.
  Segmented {
    /// The slot the entry was being built for.
    slot: Utf8Bytes,
    /// How many segments the declared road pushed.
    segments: usize,
  },
}

impl core::fmt::Display for TantivyFulltextError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Tantivy(error) => error.fmt(f),
      Self::InvalidSlot(slot) => write!(
        f,
        "{slot:?} is not a valid slot: it must be an identifier — `[A-Za-z_][A-Za-z0-9_]*`"
      ),
      Self::SlotMismatch(error) => write!(
        f,
        "slot mismatch: the handle indexes into {:?}, but its write scope is {:?}'s",
        error.handle(),
        error.writer()
      ),
      Self::UnsearchableField { field } => write!(
        f,
        "the query names field {field:?}, which this slot does not search — a slot's searchable \
         fields are its LANES, `{SEARCHABLE_FIELD}` being the unfanned corpus's own"
      ),
      Self::UnheldColumn { column } => write!(
        f,
        "the subset names column {name:?}, which this slot does not hold — its searchable columns \
         are its LANES, `{SEARCHABLE_FIELD}` being the unfanned corpus's own",
        name = column.as_str()
      ),
      Self::EmptySubset => f.write_str(
        "the subset names no column at all, so there is nothing to search — pass \
         `FulltextSubset::All` for the whole subject",
      ),
      Self::MissingKey => {
        f.write_str("a search hit is missing its stored key bytes — corrupt index")
      }
      Self::Key(error) => write!(f, "a search hit's stored term does not decode: {error}"),
      Self::Column(words) => write!(f, "a stored column was refused by its row: {words}"),
      Self::UnknownAnalyzer(named) => write!(
        f,
        "lane `{lane}` names the analyzer `{analyzer}`, which this store's tokenizer manager does \
         not hold; a tantivy build ships `{shipped}` registered, and anything else — a segmenter, a \
         stemmer of another language, an n-gram — is registered on the manager by the deployment \
         and named here",
        lane = named.lane(),
        analyzer = named.analyzer(),
        shipped = SHIPPED_ANALYZERS.join("`, `"),
      ),
      Self::ReservedLane(lane) => write!(
        f,
        "lane `{lane}` takes a field name this backend spells itself — a lane's text is indexed \
         into a field of the lane's own name, and `{reserved}` are the schema's",
        reserved = RESERVED_LANE_KEYS.join("`, `"),
      ),
      Self::LaneAbsent(lane) => write!(
        f,
        "an entry carries text for lane `{lane}`, which this slot does not hold — a document \
         reaches a lane the declaration cut its corpus into, and no other"
      ),
      Self::UnboundAnalyzer(lane) => write!(
        f,
        "an analyzer is bound to lane `{lane}`, which this corpus's roster does not carry — every \
         binding names a declared lane, so a binding that lands nowhere is a lane spelled two ways"
      ),
      Self::Segmented { slot, segments } => write!(
        f,
        "the road into slot `{slot}` pushed {segments} segments, and this backend holds ONE value \
         per lane — joining them would let a phrase match across a boundary the `multi` road was \
         written to stop, with nobody told. Write `join = \"…\"` where the values belong in one \
         value, or point this leg at a backend that stores them positionally"
      ),
    }
  }
}

/// The COLUMN LANGUAGE's floor, answered in this backend's own arms.
///
/// [`custom`](ColumnError::custom) is the whole obligation and the one method with nowhere else to
/// go. The two NAMED refusals are overridden rather than defaulted, and that is a compatibility act
/// as much as a wording one: the retired per-engine rows raised
/// [`Domain`](KeyDecodeError::Domain) for a zero read back into a `NonZero*` and
/// [`Width`](KeyDecodeError::Width) for an untagged network enum's unexpected octet count, and the
/// engine-blind rows that replaced them raise exactly those two through this trait. Left defaulted,
/// both would have become a sentence in [`Column`](TantivyFulltextError::Column) and every caller
/// matching on the old arm would have gone quietly wrong.
impl ColumnError for TantivyFulltextError {
  #[inline]
  fn custom<T: core::fmt::Display>(msg: T) -> Self {
    Self::Column(msg.to_string())
  }

  #[inline]
  fn domain<T: core::fmt::Display>(_value: T) -> Self {
    Self::Key(KeyDecodeError::Domain)
  }

  #[inline]
  fn width(_got: usize, _expected: &'static [usize]) -> Self {
    Self::Key(KeyDecodeError::Width)
  }
}

impl core::error::Error for TantivyFulltextError {
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Tantivy(error) => Some(error),
      Self::Key(error) => Some(error),
      _ => None,
    }
  }
}

impl From<tantivy::TantivyError> for TantivyFulltextError {
  #[inline]
  fn from(error: tantivy::TantivyError) -> Self {
    Self::Tantivy(error)
  }
}

impl From<io::Error> for TantivyFulltextError {
  #[inline]
  fn from(error: io::Error) -> Self {
    Self::Tantivy(tantivy::TantivyError::from(error))
  }
}

impl From<KeyDecodeError> for TantivyFulltextError {
  #[inline]
  fn from(error: KeyDecodeError) -> Self {
    Self::Key(error)
  }
}

/// Refuse a slot that is not an identifier — the guard that keeps every slot's index INSIDE the
/// store root and keeps one slot vocabulary across the crate's stores.
///
/// It is the first act of [`TantivyStore::slot_index`], the only route from a slot NAME to the
/// filesystem, so no directory can be created around it.
///
/// A charset rather than a path rule, which is what makes it portable: `..`, `/`, `\`, an absolute
/// path, the empty name and a NUL fall outside it on EVERY target, where a `Path`-based rule would
/// admit `a\b` on unix and refuse it on Windows. The residual, stated rather than papered over: a
/// charset does not make directory CREATION platform-independent — Windows reserves device names
/// (`con`, `nul`, `aux`, `com1`, …) that are perfectly good identifiers and illegal directory names,
/// so a slot called `nul` still fails there, as an IO error rather than as silent corruption.
fn validate_slot(slot: &str) -> Result<(), TantivyFulltextError> {
  if crate::slot::is_identifier(slot.as_bytes()) {
    Ok(())
  } else {
    Err(TantivyFulltextError::InvalidSlot(Utf8Bytes::from(slot)))
  }
}

// WHETHER a slot's index KEEPS the text it indexed — the `stored` word's whole reach into this
// backend, carried as the bit it is.
//
// The indexed half is not a choice: a full-text slot exists to be searched, so `body` is tokenized
// in every posture. What varies is whether tantivy also writes the text into the doc store, and the
// answer rides `STORED` on that one field. The default is NOT KEPT, and the default is the point:
// what a full-text index promises is that the text is FINDABLE, and handing it back is a second
// promise paid for in bytes on every entry — a caller that wants the value has the system of record,
// addressed by the key every hit already carries.
//
// ONE POSTURE PER SLOT, and the first open decides. `Index::open_or_create` REJECTS a directory
// whose on-disk schema differs from the one asked for, so a slot written under one posture and
// reopened under the other is a loud tantivy error rather than a silent disagreement. Within one
// `TantivyStore` the slot cache holds the first answer, and a reader that reaches a never-written
// slot CREATES it at the default — so a stored slot is opened for writing before it is searched,
// which is the order an emitted arrangement runs in anyway.
//
// It USED to be a `SlotSchema` type of its own, holding exactly this bit. The FULL-TEXT KIND's
// blueprint now carries the posture (`crate::SlotSchema::is_stored`) beside the corpus name and the
// columns a declaration elected, so one name means one thing: two types differing by two members and
// sharing a name is drift a reader pays for. What crosses this backend's own doors is the bit.

/// A slot index's fields, resolved once when the slot is opened.
///
/// A tantivy `Field` is a `u32` handle, so the three fixed ones cost nothing to carry; the LANES are
/// an `Arc<[…]>` because a fanned corpus holds as many as it declared and a [`SlotWriter`] carries
/// the set rather than re-resolving it per document. That is what took `Copy` off this type: one
/// refcount bump per writer, against a resolve per entry.
#[derive(Debug, Clone)]
struct Fields {
  source: SchemaField,
  identity: SchemaField,
  key: SchemaField,
  /// One field per lane, in the roster's own order — `(lane key, that lane's field)`.
  ///
  /// The unfanned corpus is the single row `(und, body)`, which is the one field this backend held
  /// before the fan word existed.
  lanes: Arc<[(Utf8Bytes, SchemaField)]>,
}

impl Fields {
  /// The field `lane`'s text is indexed into, or [`None`] where this slot holds no such lane.
  fn lane(&self, lane: &str) -> Option<SchemaField> {
    self
      .lanes
      .iter()
      .find(|(named, _)| named.as_str() == lane)
      .map(|(_, field)| *field)
  }

  /// Every searchable field this slot holds, in roster order — what an unscoped search asks.
  fn searchable(&self) -> Vec<SchemaField> {
    self.lanes.iter().map(|(_, field)| *field).collect()
  }

  /// Whether `name` is one of this slot's searchable field NAMES — the whitelist the query guard
  /// walks, widened from one name to the roster and no further.
  fn searches(&self, name: &str) -> bool {
    self
      .lanes
      .iter()
      .any(|(lane, _)| lane_field(LaneIdent::new(lane.as_str())) == name)
  }

  /// The UNFANNED corpus's own field — [`LaneIdent::UND`]'s, and the one field this backend held
  /// before the fan word existed.
  ///
  /// Test-only, because the shipped paths reach a field through the lane that names it and a helper
  /// that reached *the* body would be a reader believing there is only one.
  #[cfg(test)]
  fn body(&self) -> SchemaField {
    self
      .lane(LaneIdent::UND.as_str())
      .expect("an unfanned corpus holds the `und` lane")
  }

  /// The field the column `name` scopes a search to, or [`None`] where this slot holds no such
  /// column.
  fn column(&self, name: &str) -> Option<SchemaField> {
    self
      .lanes
      .iter()
      .find(|(lane, _)| lane_field(LaneIdent::new(lane.as_str())) == name)
      .map(|(_, field)| *field)
  }
}

/// A slot's opened index with its reader and its fields — what the cache memoizes, so the directory
/// scan and the reader build happen at most ONCE per slot, never per op.
///
/// `Clone` is three cheap handle clones (`Index` and `IndexReader` are `Arc`-backed, and so is
/// [`Fields`]' lane list): that is how a caller takes what it needs out of the cache without holding
/// a borrow of it.
#[derive(Clone)]
struct SlotIndex {
  index: Index,
  reader: IndexReader,
  fields: Fields,
}

/// The write capability for ONE slot: that slot's sole `IndexWriter` together with the schema fields
/// to write through.
///
/// [`TantivyStore::writer`] resolves both from the SAME slot and is the only way to obtain one, so
/// the pairing cannot be forged — and a face that queues through it reaches no index but that slot's
/// without resolving anything.
///
/// The pairing is the whole point. Every slot's schema is structurally identical — `open_index`
/// builds it identically and `Index::open_or_create` rejects a divergent on-disk one, so the four
/// fields are the same four ids in every slot — which means a handle for one slot holding another
/// slot's writer would land its document in that OTHER index and be told nothing. Carrying the slot
/// HERE turns that into a typed [`SlotMismatch`](TantivyFulltextError::SlotMismatch) at the op head,
/// and carrying the fields here is what lets the write path name no slot at all.
///
/// The caller owns it for a whole batch, queues through any number of handles on the slot — ONE AT A
/// TIME, which the exclusive [`WriteContext`](FulltextWrite::WriteContext) enforces — and
/// [`commit`](Self::commit)s it itself; dropping it releases the slot's writer lock and returns the
/// threads.
///
/// # Writers are TRANSIENT, and the resource ceiling is THREADS
///
/// An open writer is not free, and its dominant cost is OS threads rather than its arena. Every open
/// `IndexWriter` — including the single-threaded one [`writer`](TantivyStore::writer) mints — spawns
/// a fixed pool, so N writers held open at once cost a multiple of N threads: the exact constant is
/// platform- and version-specific, the LINEARITY is not. The `heap_bytes` arena is a lazily
/// committed CEILING rather than an upfront cost. Dropping the writer reclaims all of it. So a
/// driver that fans out across many slots must BOUND how many writers it holds open at once — a
/// foot-gun the heap budget alone would never reveal.
///
/// # Queueing two entries IN TURN is the shape, and each `upsert` takes a fresh reborrow
///
/// The entry arrives BUILT — a `TantivyDoc` the emission filled in — so this block names no record
/// face, no key trait and no newtype. That is the A′ dividend as a diff: the same doctest used to
/// need `Identifiable`, `Transformer`, `FulltextRecord`, `FulltextTable` and two hand-written key
/// codecs before it could queue one document, and a bare `i64` id could not be used at all without
/// one, because the engine's key trait was a local trait over foreign types.
///
/// The name in the `use` is the WRITE FACE now, not the base: the verb moved there with the scope
/// it spends, so a caller that only queues binds one trait and inherits no search.
///
/// ```no_run
/// use ingraph::{
///   AsyncFulltextWrite, Connected, SlotWriter, TantivyDoc, TantivyFulltext, TantivyStore,
/// };
///
/// /// The EMISSION's half, by hand: the record's source word, its id, its key and its text,
/// /// crossed into the engine's own entry. Every value here is a shipped row.
/// fn entry() -> TantivyDoc {
///   TantivyDoc::new("docs")
///     .with_identity(&7_i64)
///     .with_address(&(7_i64))
///     .with_body("a red car")
/// }
///
/// async fn queue_two_in_turn(store: &TantivyStore, face: &TantivyFulltext, writer: &mut SlotWriter) {
///   face
///     .upsert(Connected::new(store, &mut *writer), entry())
///     .await
///     .expect("the first entry queues");
///   face
///     .upsert(Connected::new(store, &mut *writer), entry())
///     .await
///     .expect("the second entry queues");
/// }
/// ```
///
/// A SHARED writer will not do — `upsert` cannot be HANDED one. That is the pin, and it is
/// deliberately this shape: two concurrent queuers would each need a shared context, so refusing the
/// context refuses the concurrency, and the keyed replace's delete-then-add pair is serialized.
///
/// ```compile_fail
/// # use ingraph::{
/// #   AsyncFulltextWrite, Connected, SlotWriter, TantivyDoc, TantivyFulltext, TantivyStore,
/// # };
/// # fn entry() -> TantivyDoc {
/// #   TantivyDoc::new("docs").with_identity(&7_i64).with_address(&(7_i64)).with_body("a red car")
/// # }
/// fn queue_through_a_shared_writer(
///   store: &TantivyStore,
///   face: &TantivyFulltext,
///   writer: &SlotWriter, // shared — what a second concurrent queuer would have to hold
/// ) {
///   let _ = face.upsert(Connected::new(store, writer), entry());
/// }
/// ```
///
/// Both blocks earn their keep only TOGETHER. Stable rustdoc runs a `compile_fail` block just far
/// enough to see it fail and never checks WHY, so a negative test can pass while testing nothing —
/// this one would still "pass" if the imports went stale. The twin above shares the imports and the
/// calls and must COMPILE, and the block here is written so that loosening the write context back to
/// a shared borrow would make it compile too. Between them, a regression turns one of the two red.
///
/// An EXCLUSIVE-borrow phrasing of the negative — two overlapping `&mut` reborrows, `E0499` — would
/// NOT do, and that is measured on the reference implementation: it keeps failing under a loosened
/// context, so it would pin nothing.
pub struct SlotWriter {
  slot: Utf8Bytes,
  fields: Fields,
  writer: IndexWriter,
}

impl core::fmt::Debug for SlotWriter {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    // `IndexWriter` is not `Debug`; the slot is what identifies the capability, and what a
    // mispairing has to report.
    f.debug_struct("SlotWriter")
      .field("slot", &self.slot)
      .finish()
  }
}

impl SlotWriter {
  /// The slot this is the write capability for — the only slot a face may queue into through it.
  #[inline]
  pub fn slot(&self) -> &str {
    &self.slot
  }

  /// Publish everything queued through this writer, returning the committed opstamp. The CALLER's
  /// verb, never a face's: a batch commits once.
  ///
  /// One UNDOCUMENTED tantivy coupling is worth naming here, because nothing in this crate enforces
  /// it: `commit` runs `prepare_commit` FIRST, which joins the indexing workers and re-raises a dead
  /// worker's error before any commit I/O. That is the load-bearing reason a writer left holding a
  /// half-applied replace cannot silently commit today; if a future tantivy stops re-raising,
  /// [`rollback`](Self::rollback) on an `upsert` error is what keeps that unpaired delete out.
  ///
  /// # Errors
  ///
  /// [`TantivyFulltextError::Tantivy`] if the commit fails.
  #[inline]
  pub fn commit(&mut self) -> Result<Opstamp, TantivyFulltextError> {
    self.writer.commit().map_err(Into::into)
  }

  /// Discard everything queued since the last commit, resetting this writer to the last committed
  /// opstamp. The caller's obligation on an `upsert` error, and the reason a half-applied replace
  /// never reaches a commit.
  ///
  /// A keyed replace is delete-then-add, and the two halves fail differently: `delete_term` never
  /// fails and never consults the indexing worker — it pushes to the delete queue and returns an
  /// opstamp — while `add_document` is rejected by a dead worker. So a mid-`upsert` failure
  /// leaves a queued DELETE with no paired add, and committing would then tombstone the entry
  /// with no replacement.
  ///
  /// Tantivy's rollback swaps in a FRESH writer over the same index, so this [`SlotWriter`] stays
  /// usable afterwards — a reset, not a poison.
  ///
  /// # Errors
  ///
  /// [`TantivyFulltextError::Tantivy`] if the rollback fails.
  #[inline]
  pub fn rollback(&mut self) -> Result<Opstamp, TantivyFulltextError> {
    self.writer.rollback().map_err(Into::into)
  }
}

/// The Tantivy connection-manager and the shared connection its handles thread: ONE index root plus
/// the lazily-opened per-slot index cache.
///
/// It IS the [`FulltextEngine::Connection`] of the [`TantivyFulltext`] handles
/// [`fulltext`](Self::fulltext) mints — a handle holds only its slot and reaches its index through
/// `ctx.connection()`, so a slot's directory is opened exactly ONCE however many handles name it.
///
/// # The cache is two locks, and the split is what each one buys
///
/// The outer `Mutex` guards the map LOOKUP alone and is released before anything is opened; the
/// per-slot `Mutex` is what the open runs under. So one slot's open never blocks another slot's
/// lookup, and two racing first-uses of ONE never-opened slot converge on a single open rather than
/// both taking the create path. An init failure is not cached — a later call retries.
///
/// Not `Clone`: the cache is the manager's identity, and a clone would fork it into a second cache
/// over the same root. Share it by reference — `Connected::new(&store, scope)` — or behind an `Arc`.
pub struct TantivyStore {
  root: PathBuf,
  indices: Mutex<HashMap<Utf8Bytes, Arc<Mutex<Option<SlotIndex>>>>>,
  /// **WHAT EACH SLOT'S FAN IS** — slot name → `(lane, analyzer name)`, learned at
  /// [`create_slot`](Self::create_slot).
  ///
  /// The roster shapes the SCHEMA, so the open has to know it — and the doors that open a slot
  /// lazily ([`writer_with`](Self::writer_with), a read reaching a never-created corpus) hold a slot
  /// NAME and nothing else. So the fan is recorded where it IS known, which is layer two's own act,
  /// and the lazy doors read it here rather than growing a parameter each that every caller would
  /// have to carry the roster to.
  ///
  /// A slot absent from this table is UNFANNED, which is the same default a slot absent from the
  /// blueprint already had: a reader that reaches a never-created corpus creates it at the default
  /// posture, and the ordering note above [`Fields`] is where that is already written down.
  fans: Mutex<HashMap<Utf8Bytes, Fan>>,
  /// **THE ANALYZER REGISTRY EVERY LANE NAME RESOLVES AGAINST** — tantivy's own manager, this
  /// store's copy.
  ///
  /// `TokenizerManager::default()` unless a deployment handed one in through
  /// [`with_tokenizers`](Self::with_tokenizers), and it is set on every index this store opens, so
  /// the analyzer a lane's field was built with is the analyzer its queries are parsed with. Two
  /// managers would be exactly the write-side/read-side disagreement the lane layer exists to
  /// prevent.
  tokenizers: TokenizerManager,
}

impl core::fmt::Debug for TantivyStore {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    // `Index` and `IndexReader` are not `Debug`; the root and the opened slot names are the
    // manager's identifying state, and a poisoned cache prints as none rather than panicking a
    // formatter.
    let slots = self
      .indices
      .lock()
      .map(|indices| indices.keys().cloned().collect::<Vec<_>>())
      .unwrap_or_default();
    f.debug_struct("TantivyStore")
      .field("root", &self.root)
      .field("slots", &slots)
      .finish()
  }
}

impl TantivyStore {
  /// Tantivy's per-thread memory-arena floor: a [`writer`](Self::writer) `heap_bytes` below this is
  /// rejected by the engine.
  ///
  /// The engine's own `MEMORY_BUDGET_NUM_BYTES_MIN` — 15 × its 1 MB margin — restated because that
  /// constant is not re-exported from tantivy's root, so a caller sizing a budget has no other way
  /// to name the floor it will be checked against.
  pub const MIN_WRITER_HEAP_BYTES: usize = 15_000_000;

  /// Open the store rooted at `root`, creating the directory and any missing parents. Opens NO
  /// index: the per-slot indices under it open lazily, on first use.
  ///
  /// # Errors
  ///
  /// [`TantivyFulltextError::Tantivy`] if the root cannot be created.
  pub fn open(root: impl AsRef<Path>) -> Result<Self, TantivyFulltextError> {
    let root = root.as_ref().to_path_buf();
    std::fs::create_dir_all(&root)?;
    Ok(Self {
      root,
      indices: Mutex::new(HashMap::new()),
      fans: Mutex::new(HashMap::new()),
      tokenizers: TokenizerManager::default(),
    })
  }

  /// **THE ANALYZER DOOR** — the same store, resolving lane analyzer names against `tokenizers`.
  ///
  /// ```no_run
  /// # fn main() -> Result<(), Box<dyn core::error::Error>> {
  /// use ingraph::TantivyStore;
  /// use tantivy::tokenizer::{NgramTokenizer, TokenizerManager};
  ///
  /// let analyzers = TokenizerManager::default();
  /// analyzers.register("ngram2", NgramTokenizer::all_ngrams(2, 2)?);
  ///
  /// let store = TantivyStore::open("/tmp/corpus")?.with_tokenizers(analyzers);
  /// # Ok(())
  /// # }
  /// ```
  ///
  /// This is the whole of what makes the analyzer vocabulary FRAMEWORK-OPEN. A lane names an
  /// analyzer as a word ([`LaneAnalyzers`]), the word is resolved here, and what the manager holds
  /// is the deployment's business: tantivy's four shipped names by default, plus every analyzer this
  /// deployment registered — a CJK segmenter, a Thai dictionary, an n-gram, a stemmer of another
  /// language. Nothing in this file names one of those, and nothing has to.
  ///
  /// Start from `TokenizerManager::default()` and register on top of it, as the example does: a
  /// manager built with `new()` holds NOTHING, so a corpus whose lanes named no analyzer at all
  /// would fail to resolve tantivy's own `default`.
  #[must_use]
  pub fn with_tokenizers(mut self, tokenizers: TokenizerManager) -> Self {
    self.tokenizers = tokenizers;
    self
  }

  /// The analyzer registry this store resolves lane names against.
  #[inline]
  #[must_use]
  pub const fn tokenizers(&self) -> &TokenizerManager {
    &self.tokenizers
  }

  /// The root every slot's index directory sits under.
  #[inline]
  pub fn root(&self) -> &Path {
    &self.root
  }

  /// Mint the [`SlotWriter`] for `slot` — a fresh single-threaded `IndexWriter` on that slot's
  /// index, bound to the slot it was opened from and to that index's fields.
  ///
  /// It is the SOLE writer for the slot (tantivy enforces one per directory through a lockfile, so a
  /// second concurrent call on the same slot fails `LockFailure`; a different slot is a different
  /// lockfile and does not collide), and the ONLY constructor of a [`SlotWriter`] — which is what
  /// makes the slot/writer/fields triple unforgeable. `heap_bytes` is the in-memory segment arena
  /// and must be at least [`MIN_WRITER_HEAP_BYTES`](Self::MIN_WRITER_HEAP_BYTES); single-threaded is
  /// deliberate, since a sole-writer caller wants deterministic opstamp ordering rather than
  /// parallel segment writers splitting the budget.
  ///
  /// This is also what OPENS a never-before-used slot.
  ///
  /// # Errors
  ///
  /// [`TantivyFulltextError::InvalidSlot`] if `slot` is not an identifier;
  /// [`TantivyFulltextError::Tantivy`] if opening the slot fails, its lock is already held, or the
  /// budget is out of range.
  pub fn writer(&self, slot: &str, heap_bytes: usize) -> Result<SlotWriter, TantivyFulltextError> {
    self.writer_with(slot, heap_bytes, false)
  }

  /// [`writer`](Self::writer) at a stated schema posture — the door a caller reaches when it knows
  /// whether the slot KEEPS its body.
  ///
  /// # Errors
  ///
  /// [`writer`](Self::writer)'s, plus [`TantivyFulltextError::Tantivy`] where `stored` disagrees
  /// with a posture this slot's directory was already created under — `Index::open_or_create`'s own
  /// refusal, surfaced where the disagreement is.
  pub fn writer_with(
    &self,
    slot: &str,
    heap_bytes: usize,
    stored: bool,
  ) -> Result<SlotWriter, TantivyFulltextError> {
    let SlotIndex { index, fields, .. } = self.slot_index(slot, stored)?;
    let writer = index.writer_with_num_threads(1, heap_bytes)?;
    Ok(SlotWriter {
      slot: Utf8Bytes::from(slot),
      fields,
      writer,
    })
  }

  /// The writer for the slot `S` NAMES, at the posture `S` DECLARES — the one door that spends the
  /// `stored` word without a caller retyping either half.
  ///
  /// A derived index emits one [`FulltextRoad`](crate::FulltextRoad) impl per full-text slot,
  /// carrying that slot's name and its `stored` answer. Passing both by hand is two chances to pass
  /// the wrong one; naming the slot TYPE is none, and it is the same brand
  /// [`SlotWriter`](SlotWriter) already exists to protect.
  ///
  /// # Errors
  ///
  /// [`writer_with`](Self::writer_with)'s.
  pub fn slot_writer<S>(&self, heap_bytes: usize) -> Result<SlotWriter, TantivyFulltextError>
  where
    S: crate::FulltextRoad,
  {
    self.writer_with(
      S::SLOT.as_ref(),
      heap_bytes,
      <S as crate::FulltextRoad>::STORED,
    )
  }

  /// **MAKE THE CORPUS `schema` DESCRIBES** — layer two's act at this backend.
  ///
  /// The name and the `stored` posture are the DECLARATION's, read off the blueprint rather than
  /// passed beside it, so the corpus a boot creates and the corpus a read opens cannot be given two
  /// answers. It is idempotent by construction: `Index::open_or_create` opens an existing directory
  /// and creates a missing one, so a second launch over a live index root does nothing — and a
  /// posture that disagrees with what is on disk is tantivy's own loud refusal rather than a silent
  /// reopen.
  ///
  /// # `knobs` is the [`Options`](crate::FulltextEngine::Options) SEAT, spent here
  ///
  /// It is this engine's per-handle construction input, projected off the base, and the day the
  /// seat's own doc anticipated has arrived: it is a [`LaneAnalyzers`] table, one analyzer NAME per
  /// lane, and no caller changed shape to receive it. `None` is *this deployment named no knobs for
  /// this corpus*, which puts every lane on tantivy's own `default` — the analyzer every corpus this
  /// backend ever wrote was tokenized by.
  ///
  /// Every name is RESOLVED HERE, against the manager this store holds
  /// ([`with_tokenizers`](Self::with_tokenizers)), before the schema is built: an unresolvable one
  /// is [`UnknownAnalyzer`](TantivyFulltextError::UnknownAnalyzer) at boot rather than a lane
  /// quietly indexed by the wrong analyzer. And a binding naming a lane the ROSTER does not carry is
  /// [`UnboundAnalyzer`](TantivyFulltextError::UnboundAnalyzer), which is the ruling's own *every
  /// binding lands, and an extra one is refused by name*.
  ///
  /// # The blueprint's LANES are spent and its COLUMNS are not
  ///
  /// A tantivy slot's on-disk schema is three fixed fields plus ONE PER LANE, and the lanes are the
  /// declaration's own ([`SlotSchema::lanes`](crate::SlotSchema::lanes)) — a corpus that declared no
  /// fan holds exactly one, keyed [`und`](crate::LaneIdent::UND) and named `body`, which is the
  /// schema this backend has always built. The COLUMN list still varies nothing: under the slot
  /// grain one corpus is one election, so the list has one entry and it is already the corpus's own
  /// identity. A backend with a real multi-column schema reads it; this one has nothing to vary.
  ///
  /// # Errors
  ///
  /// [`TantivyFulltextError::InvalidSlot`] if the blueprint's name is not an identifier — which
  /// [`SlotName`](crate::SlotName) already refuses at the declaration, so reaching it here means a
  /// hand-built name; [`TantivyFulltextError::ReservedLane`] for a lane keyed after one of this
  /// schema's own fields; [`TantivyFulltextError::UnknownAnalyzer`] and
  /// [`TantivyFulltextError::UnboundAnalyzer`] for the two halves of the binding check;
  /// [`TantivyFulltextError::Tantivy`] if the directory cannot be made or the index cannot be opened
  /// at this posture.
  pub fn create_slot(
    &self,
    schema: &crate::SlotSchema,
    knobs: Option<&<TantivyFulltext as crate::FulltextEngine>::Options>,
  ) -> Result<(), TantivyFulltextError> {
    let fan = self.resolve_fan(schema.lanes(), knobs)?;
    // RECORDED BEFORE THE OPEN, so the open below reads this slot's own roster rather than the
    // unfanned default — and so a later lazy door (a writer, a read reaching a corpus nothing has
    // written) opens the same schema this call created.
    self
      .fans
      .lock()
      .unwrap_or_else(PoisonError::into_inner)
      .insert(Utf8Bytes::from_static(schema.slot().as_ref()), fan);
    self.slot_index(schema.slot().as_ref(), schema.is_stored())?;
    Ok(())
  }

  /// **THE BOOT CHECK**: every lane's analyzer resolved, every binding landed.
  ///
  /// Validate-then-act, and the order inside it is the ruling's: a lane keyed after one of this
  /// schema's own fields is refused first (it could not have a field at all), then each lane's
  /// analyzer — named or `default` — is resolved against this store's manager, and finally every
  /// binding is checked to have landed on a declared lane.
  ///
  /// # Errors
  ///
  /// [`TantivyFulltextError::ReservedLane`], [`TantivyFulltextError::UnknownAnalyzer`],
  /// [`TantivyFulltextError::UnboundAnalyzer`].
  fn resolve_fan(
    &self,
    lanes: &'static [Lane],
    knobs: Option<&LaneAnalyzers>,
  ) -> Result<Fan, TantivyFulltextError> {
    let mut fan: Vec<(Utf8Bytes, Utf8Bytes)> = Vec::with_capacity(lanes.len());
    for lane in lanes {
      let key = lane.key().as_str();
      if RESERVED_LANE_KEYS.contains(&key) {
        return Err(TantivyFulltextError::ReservedLane(Utf8Bytes::from_static(
          key,
        )));
      }
      let analyzer = knobs
        .and_then(|knobs| knobs.analyzer(key))
        .unwrap_or(DEFAULT_ANALYZER);
      if self.tokenizers.get(analyzer).is_none() {
        return Err(TantivyFulltextError::UnknownAnalyzer(Box::new(
          UnknownAnalyzer::new(Utf8Bytes::from(key.to_owned()), analyzer.to_owned()),
        )));
      }
      fan.push((
        Utf8Bytes::from_static(key),
        Utf8Bytes::from(analyzer.to_owned()),
      ));
    }

    // EVERY BINDING LANDS. A table naming a lane the roster does not carry bound an analyzer to
    // nothing, which is how a deployment comes to believe a lane has a segmenter it never got.
    if let Some(knobs) = knobs {
      for (bound, _) in knobs.iter() {
        if !lanes.iter().any(|lane| lane.key().as_str() == bound) {
          return Err(TantivyFulltextError::UnboundAnalyzer(Utf8Bytes::from(
            bound.to_owned(),
          )));
        }
      }
    }

    Ok(fan.into())
  }

  /// The fan recorded for `slot`, or the UNFANNED one where layer two has not reached it.
  fn fan(&self, slot: &str) -> Fan {
    self
      .fans
      .lock()
      .unwrap_or_else(PoisonError::into_inner)
      .get(slot)
      .map_or_else(
        || {
          Arc::from(
            [(
              Utf8Bytes::from_static(LaneIdent::UND.as_str()),
              Utf8Bytes::from_static(DEFAULT_ANALYZER),
            )]
            .as_slice(),
          )
        },
        Arc::clone,
      )
  }

  /// Refresh `slot`'s reader against its latest committed segments — the explicit step
  /// [`ReloadPolicy::Manual`] requires. A caller invokes it AFTER committing that slot's writer, so
  /// a subsequent search observes those writes: deterministic read-your-committed-writes, rather
  /// than the default policy's asynchronous lag.
  ///
  /// A slot this store has never opened is a NO-OP rather than an error: a reader that does not
  /// exist yet cannot be stale, because the one built when the slot IS first reached snapshots
  /// whatever is committed at that moment.
  ///
  /// It validates the slot itself rather than going through [`slot_index`](Self::slot_index), which
  /// would OPEN the very index it must not. That guard buys a consistent typed error and not path
  /// safety: this verb reaches no filesystem either way.
  ///
  /// # Errors
  ///
  /// [`TantivyFulltextError::InvalidSlot`] if `slot` is not an identifier;
  /// [`TantivyFulltextError::Tantivy`] if reloading the searcher generation fails.
  pub fn reload(&self, slot: &str) -> Result<(), TantivyFulltextError> {
    validate_slot(slot)?;
    let cell = self.cell(slot);
    let opened = cell.lock().unwrap_or_else(PoisonError::into_inner);
    match opened.as_ref() {
      Some(opened) => opened.reader.reload().map_err(Into::into),
      None => Ok(()),
    }
  }

  /// The per-slot cell, minted on first mention. The map lock is taken for the lookup ALONE and
  /// dropped at the end of this call, which is what keeps one slot's open off another slot's path.
  fn cell(&self, slot: &str) -> Arc<Mutex<Option<SlotIndex>>> {
    // A poisoned cache is still sound: the critical section only inserts into a map, so a panic
    // elsewhere cannot leave it half-updated — recover rather than propagate.
    let mut indices = self.indices.lock().unwrap_or_else(PoisonError::into_inner);
    Arc::clone(indices.entry(Utf8Bytes::from(slot)).or_default())
  }

  /// `slot`'s index, opened (or created) on first use and cached thereafter — and the ONLY route
  /// from a slot NAME to the filesystem, so validating the slot here validates it on every path that
  /// can create a directory.
  ///
  /// The opened index is CLONED out rather than borrowed — cheaply, per its own doc — so no caller
  /// holds a borrow of the cache.
  ///
  /// # Errors
  ///
  /// [`TantivyFulltextError::InvalidSlot`] if `slot` is not an identifier;
  /// [`TantivyFulltextError::Tantivy`] if opening the index fails.
  /// `stored` is spent ONLY on a first open. A slot already in the cache is handed back as it
  /// stands — see the posture note above `Fields` for why one posture per slot is the rule and where a disagreement
  /// surfaces.
  fn slot_index(&self, slot: &str, stored: bool) -> Result<SlotIndex, TantivyFulltextError> {
    validate_slot(slot)?;
    let cell = self.cell(slot);
    let mut opened = cell.lock().unwrap_or_else(PoisonError::into_inner);
    if let Some(opened) = opened.as_ref() {
      return Ok(opened.clone());
    }
    // The slot passed the guard above, so joining it to the root cannot leave it. A failure stores
    // nothing, which is what makes a later call retry rather than inherit this one's outcome.
    let index = open_index(
      &self.root.join(slot),
      stored,
      &self.fan(slot),
      &self.tokenizers,
    )?;
    Ok(opened.insert(index).clone())
  }
}

/// The `body` options ONE LANE's field is built with — tokenized by `analyzer`, and KEPT only where
/// the declaration asked.
///
/// # It reproduces `TEXT` exactly at the default analyzer
///
/// tantivy's `TEXT` constant IS this construction with the tokenizer name `default`: fieldnorms on,
/// positions recorded, not stored, not fast. Building it out by hand is what lets the tokenizer name
/// vary, and `the_default_lane_is_tantivys_own_TEXT` pins the equality so an unfanned corpus's
/// schema stays byte-for-byte the one this backend has always written.
fn lane_options(analyzer: &str, stored: bool) -> TextOptions {
  let indexing = TextFieldIndexing::default()
    .set_tokenizer(analyzer)
    .set_fieldnorms(true)
    .set_index_option(IndexRecordOption::WithFreqsAndPositions);
  let options = TextOptions::default().set_indexing_options(indexing);
  if stored {
    options.set_stored()
  } else {
    options
  }
}

/// [`open_index`] over the UNFANNED corpus — one lane, keyed `und`, on tantivy's own `default`.
///
/// Test-only: it is the arrangement layer two produces for a declaration that named no lanes, spelled
/// once so the tests that predate the fan word read as they did.
#[cfg(test)]
fn open_unfanned(dir: &Path, stored: bool) -> Result<SlotIndex, TantivyFulltextError> {
  open_index(
    dir,
    stored,
    &[(
      Utf8Bytes::from_static(LaneIdent::UND.as_str()),
      Utf8Bytes::from_static(DEFAULT_ANALYZER),
    )],
    &TokenizerManager::default(),
  )
}

/// Open (or create) the index in one slot's directory, at the posture `stored` asks for and cut into
/// the lanes `fan` names.
///
/// The directory must exist before `MmapDirectory` will open it, so a fresh slot is created first.
fn open_index(
  dir: &Path,
  stored: bool,
  fan: &[(Utf8Bytes, Utf8Bytes)],
  tokenizers: &TokenizerManager,
) -> Result<SlotIndex, TantivyFulltextError> {
  std::fs::create_dir_all(dir)?;
  let mut builder = Schema::builder();
  // `STRING`: untokenized and indexed, so the discriminant is ONE exact term rather than a word
  // stream. Not stored — nothing reads it back off a hit yet, and a term query does not need it
  // to be.
  let source = builder.add_text_field("source", STRING);
  // Indexed and NOT stored: this is the `delete_term` target and nothing else. A stored-only bytes
  // field would make `delete_term` swallow its own miss and turn every replace into an append.
  let identity = builder.add_bytes_field("identity", BytesOptions::default().set_indexed());
  // Stored and NOT indexed: the hit's address, read back out of every hit and searchable by
  // nobody — see `UnsearchableField` for the probe an indexed one would open.
  let key = builder.add_bytes_field("key", BytesOptions::default().set_stored());
  // ONE FIELD PER LANE, in the roster's own order — each tokenized for BM25 by ITS OWN analyzer,
  // and KEPT only where the declaration asked (see the posture note, and `FulltextRoad::STORED` for
  // the word that decides it). An unfanned corpus is one row here, keyed `und` and named `body`,
  // which is the field this backend built before the fan word existed.
  let lanes: Arc<[(Utf8Bytes, SchemaField)]> = fan
    .iter()
    .map(|(lane, analyzer)| {
      let name = lane_field(LaneIdent::new(lane.as_str()));
      let field = builder.add_text_field(name, lane_options(analyzer.as_str(), stored));
      (lane.clone(), field)
    })
    .collect();
  let fields = Fields {
    source,
    identity,
    key,
    lanes,
  };
  let directory = MmapDirectory::open(dir).map_err(tantivy::TantivyError::from)?;
  // `open_or_create` REJECTS a directory whose on-disk schema differs from this one, so the fields
  // just built ARE the opened index's fields and nothing has to be re-resolved. That refusal now
  // covers the FAN as well as the posture: a corpus reopened under a different roster, or under a
  // lane bound to a different analyzer, is tantivy's own loud error rather than a silent reopen
  // against a schema nothing matches.
  let mut index = Index::open_or_create(directory, builder.build())?;
  // THE SAME MANAGER FOR BOTH DIRECTIONS. A field is built naming an analyzer, and the query parser
  // resolves that name through the index's own manager — so handing the index this store's manager
  // is what makes the analyzer a lane was WRITTEN with the analyzer its questions are PARSED with.
  index.set_tokenizers(tokenizers.clone());
  let reader = index
    .reader_builder()
    .reload_policy(ReloadPolicy::Manual)
    .try_into()?;
  Ok(SlotIndex {
    index,
    reader,
    fields,
  })
}

/// The BLOCKING construction face, and the one that HOLDS THE BODY.
///
/// Opening an index root is `MmapDirectory::open` and `Index::open_or_create` — syscalls that
/// return, with nothing to await anywhere beneath them. The inherent [`TantivyStore::open`] always
/// said so; this seam is where the trait face stops wrapping that fact in an `async fn`. It is the
/// shipped full-text citizen taking the posture [`LocalFsStore`](crate::LocalFsStore) already takes
/// on the blob side, for the same measured reason: the blocking face IS the act, and the async face
/// is what bridges to it.
impl FulltextStore for TantivyStore {
  /// The index root directory, created if missing; each slot is one directory under it.
  type Options = PathBuf;
  type Error = TantivyFulltextError;
  type Handle = TantivyFulltext;

  #[inline]
  fn open(options: Self::Options) -> Result<Self, Self::Error> {
    TantivyStore::open(options)
  }

  #[inline]
  fn fulltext(&self, slot: impl Into<Utf8Bytes>) -> Self::Handle {
    TantivyFulltext::new(slot)
  }
}

/// The ASYNCHRONOUS construction face — the blocking body above, resolved immediately.
///
/// It exists so a deployment whose launch is bounded on the async face reaches this store at all,
/// and it DELEGATES rather than duplicating: there is exactly one opening here, and both faces name
/// it. Written out rather than bridged by a blanket, per the dual-mode law — a blanket from one face
/// to the other would hand every blocking store an async face and blind the bound that selects.
impl AsyncFulltextStore for TantivyStore {
  type Options = PathBuf;
  type Error = TantivyFulltextError;
  type Handle = TantivyFulltext;

  #[inline]
  fn open(options: Self::Options) -> impl Future<Output = Result<Self, Self::Error>> + Send {
    ready(<Self as FulltextStore>::open(options))
  }

  #[inline]
  fn fulltext(&self, slot: impl Into<Utf8Bytes>) -> Self::Handle {
    <Self as FulltextStore>::fulltext(self, slot)
  }
}

/// The Tantivy full-text face — a STATELESS keyed handle holding ONLY its slot name: no index, no
/// reader, no writer.
///
/// It threads the [`TantivyStore`] as its connection, so `upsert` queues into the writer the
/// caller
/// took on this slot and `search` reads this slot's reader. The original defect this two-layer shape
/// exists to prevent is a face that opened its own `Index`, so two faces over one directory
/// deadlocked on the writer lock — a handle opens nothing, and the store owns every index.
#[derive(Debug, Clone)]
pub struct TantivyFulltext {
  slot: Utf8Bytes,
}

impl TantivyFulltext {
  /// A full-text handle for the `slot` index of a [`TantivyStore`].
  #[inline]
  pub fn new(slot: impl Into<Utf8Bytes>) -> Self {
    Self { slot: slot.into() }
  }

  /// The slot — the index directory — this handle indexes into and searches.
  #[inline]
  pub fn slot(&self) -> &str {
    &self.slot
  }
}

// THE BASE: what this engine SPEAKS and the address lifecycle it speaks it through. No verb, no
// lease, no GAT — those are the four faces below.
//
// R-FREE, and the whole `where` clause went with the record. What used to ride here —
// `R: TantivyRecord + FulltextTable`, `R::Key: TantivyKey + Send`, `R::Document: AsRef<str>` — was
// five bounds describing a record this engine never has to know about: the source word, the id, the
// key and the text all arrive inside the `TantivyDoc` the emission built, and the hit's address goes
// back out as this engine's own. There is nothing left to bound.
//
// `R::Key: 'static` was NOT among them, and that is what doing the work inline buys: a face that ran
// its search on a blocking pool would inherit `spawn_blocking`'s `T: Send + 'static` output bound.
impl FulltextEngine for TantivyFulltext {
  /// **THE PER-LANE ANALYZER TABLE** — see [`LaneAnalyzers`], where the whole of it is written.
  ///
  /// The seat's own doc reserved this position for *a tokenizer, an analyzer chain* arriving at
  /// boot, and that is exactly what lands in it: one analyzer NAME per lane, resolved against this
  /// store's manager at [`create_slot`](TantivyStore::create_slot). The empty table is the corpus
  /// this backend always had.
  type Options = LaneAnalyzers;
  /// `()`, and it is a MEASUREMENT rather than a placeholder.
  ///
  /// The trait's own note anticipates four per-query knobs for a full-text engine — an analyzer, a
  /// boost, a fuzziness, a conjunction default — and this backend implements NONE of them:
  /// [`search_slot`] builds its parser with [`QueryParser::for_index`] and a field list and calls
  /// no setter, registers no [`TextAnalyzer`](::tantivy::tokenizer::TextAnalyzer), and generates no
  /// snippet. So there is no knob here to give a home to.
  ///
  /// The ONE per-query value it does read is `k`, and that one is not this member's: `k` is
  /// UNIVERSAL — every engine of every family takes one — and a universal parameter is not a knob
  /// *in this engine's own currency*. It is a positional parameter of the verb, which is where the
  /// seam's parameter law puts every universal fact.
  ///
  /// It is [`Noop`](crate::Noop) rather than `()`, and the day the seam's own note anticipated has
  /// arrived: a `#[ingraph::resource(tantivy)]` declaration is NAMED by an election, so the emitted
  /// `options` row is projected off this member and published as an input — and `async_graphql`
  /// implements `InputType` for no unit type. One word, and no knob invented to justify it: `Noop`
  /// is the framework's crossable spelling of *nothing here*, and what it says about this backend
  /// is exactly what `()` said.
  type SearchOptions = Noop;
  type Error = TantivyFulltextError;
  /// `f32`, which is BM25's native shape — tantivy computes and collects in it, so anything else
  /// here would be a conversion this seam performed on the way out.
  ///
  /// THIS BACKEND's fact and not the family's. It is unbounded above and higher-is-better, at
  /// corpus statistics that belong to one slot's index; a face over a different engine names
  /// whatever its own scoring produces, and a reader who wants the closed unit interval gets it
  /// from a normalising layer that declares the act in [`Score`](crate::Score).
  type Score = f32;
  /// The manager, which owns the slot's index and its reader.
  type Connection = TantivyStore;
  /// [`TantivyAddress`] — the length-prefixed binary vocabulary, the same type in both directions,
  /// and the SAME BYTES this backend has always stored.
  type Address = TantivyAddress;
  /// [`TantivyTerms`] — the framing accumulator, landing each typed column directly as the bytes a
  /// `Term` is built from.
  type WriteBuffer = TantivyTerms;
  /// [`TantivyColumns`] — the cursor over one stored address, refusing in this engine's own
  /// [`Error`](Self::Error) so a caller has one type to unwrap.
  type ReadBuffer = TantivyColumns;

  #[inline]
  fn buffer() -> Self::WriteBuffer {
    TantivyTerms::new()
  }

  /// The bytes pass through UNCHANGED — the write phase framed them and the address IS them. There
  /// is no second encoding here and there must not be one: what a hit arrives under is what this
  /// sealed.
  #[inline]
  fn finalize(buf: Self::WriteBuffer) -> Self::Address {
    TantivyAddress::from(buf.into_bytes())
  }

  #[inline]
  fn open(address: Self::Address) -> Self::ReadBuffer {
    TantivyColumns::new(address.into_bytes())
  }
}

/// THE BLOCKING READ FACE, and it holds no body of its own — [`search_slot`] is the body, and it was
/// already the body.
///
/// The claim a blocking face makes is STRUCTURAL, so it is worth stating what was measured before it
/// was made: nothing under this verb awaits. [`search_slot`] is a plain `fn` — it opens the slot
/// through the manager's cache, parses and checks the query, runs `Searcher::search` and reads each
/// hit's stored bytes — and the base impl's `ready(…)` wraps a `Result` that is already computed by
/// the time the wrapper is reached. So this face is that call with the wrapper never applied, which
/// is why it can be written at all: this module's own header states the same fact from the engine's
/// side (*tantivy is a SYNCHRONOUS engine*), and the reference implementation's `spawn_blocking` is
/// the shape this backend declined along with its runtime.
impl FulltextRead for TantivyFulltext {
  /// `()` — a PURE LEASE with nothing in it, which is this backend's honest read scope.
  ///
  /// It carried a `TantivySearch { limit }` until `k` took its seat on the verb, and what is left is
  /// nothing: the searcher was never here (it comes from the connection's per-slot reader), and the
  /// limit was the universal `k` sitting in a room the caller could not see. A scope holding one
  /// universal fact and no lease is a scope with no reason to exist, so it does not.
  ///
  /// ON THE FACE, so the two modes may lease differently. They do not here — this engine is
  /// synchronous to the bottom and both faces run the one body — and the seat is written twice
  /// anyway, because an engine whose async transaction hands out a ticket its blocking searcher does
  /// not is the case the split exists for.
  type ReadContext<'a> = ();

  /// `options` is `Option<&()>` here and is therefore read by nothing — see
  /// [`SearchOptions`](FulltextEngine::SearchOptions) for the measurement that made it `()`.
  fn search(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    subset: FulltextSubset<'_>,
    query: &str,
    k: NonZeroUsize,
    _options: Option<&Self::SearchOptions>,
  ) -> Result<Hits<Self::Address, Self::Score>, Self::Error> {
    let (store, ()) = ctx.into_parts();
    search_slot(store, &self.slot, subset, query, k)
  }
}

/// The ASYNCHRONOUS read face — the blocking body above, resolved immediately.
///
/// It DELEGATES rather than reaching [`search_slot`] a second time, which is the discipline
/// [`FulltextStore`] / [`AsyncFulltextStore`] already keep two layers up: there is one search here
/// and both faces name it, so a fix to one is a fix to both. Written out rather than bridged by a
/// blanket, per the dual-mode law — a blanket from one face to the other would hand every blocking
/// engine an async face and blind the bound that selects.
impl AsyncFulltextRead for TantivyFulltext {
  /// `()` — a PURE LEASE with nothing in it, which is this backend's honest read scope.
  ///
  /// It carried a `TantivySearch { limit }` until `k` took its seat on the verb, and what is left is
  /// nothing: the searcher was never here (it comes from the connection's per-slot reader), and the
  /// limit was the universal `k` sitting in a room the caller could not see. A scope holding one
  /// universal fact and no lease is a scope with no reason to exist, so it does not.
  ///
  /// ON THE FACE, so the two modes may lease differently. They do not here — this engine is
  /// synchronous to the bottom and both faces run the one body — and the seat is written twice
  /// anyway, because an engine whose async transaction hands out a ticket its blocking searcher does
  /// not is the case the split exists for.
  type ReadContext<'a> = ();

  #[inline]
  fn search(
    &self,
    ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
    subset: FulltextSubset<'_>,
    query: &str,
    k: NonZeroUsize,
    options: Option<&Self::SearchOptions>,
  ) -> impl Future<Output = Result<Hits<Self::Address, Self::Score>, Self::Error>> + Send {
    ready(<Self as FulltextRead>::search(
      self, ctx, subset, query, k, options,
    ))
  }
}

/// THE BLOCKING WRITE FACE — [`upsert_entry`] is the body, and both of its steps are in-memory queue
/// ops with no IO: `delete_term` pushes onto the delete queue and returns an opstamp, and
/// `add_document` sends to the indexing worker. Visibility waits on the caller's commit, which is
/// not this verb's act.
///
/// The EXCLUSIVE write scope is unchanged and remains load-bearing — see
/// [`WriteContext`](FulltextWrite::WriteContext). Taking the future off a signature changes nothing
/// about the delete-then-add pair's non-atomicity, and a face that relaxed the borrow would break
/// the same invariant in a new place.
impl FulltextWrite for TantivyFulltext {
  /// `&mut `[`SlotWriter`]: the caller's write CAPABILITY for this slot, and NOT a transaction — the
  /// slot's sole writer and the fields to write through, minted together.
  ///
  /// **The EXCLUSIVE borrow is load-bearing.** It is not a stricter-than-necessary bound and the
  /// crate's bound-minimization convention does not reach it: a keyed replace is `delete_term` THEN
  /// `add_document`, a NON-ATOMIC two-step, and a tantivy delete only tombstones documents whose
  /// opstamp is LOWER than the delete's. Two `upsert` calls sharing one writer can therefore
  /// interleave as (delete, delete, add, add) and leave TWO documents under ONE identity — which is
  /// this backend's core obligation, keyed-idempotent apply, broken. `&mut` serializes the pair by
  /// construction: the borrow checker admits only (delete, add, delete, add).
  ///
  /// Both tantivy receivers being `&self` is exactly the observation that misleads here — `Sync` is
  /// not *safe to use concurrently for this protocol*, and a shared context was measured duplicating
  /// the entry in 24 of 30 raced iterations on the reference implementation.
  ///
  /// `IndexWriter::run` is NOT the rescue it looks like. It takes `&self` and allocates its group a
  /// CONTIGUOUS opstamp range, so `run([Delete, Add])` reads as an atomic replace that would make a
  /// shared context sound. Only the stamp RANGE is atomic: the body that spends it still pushes the
  /// delete and sends the add as separate unsynchronized steps, which two concurrent `run`s
  /// interleave — measured at 9 duplications in 30, against 24 for the plain pair. Contiguous stamps
  /// NARROW the window; they do not close it. Shared queueing needs an internal
  /// `Mutex<IndexWriter>`, and should be motivated by a measured throughput need rather than by the
  /// shape of a receiver.
  ///
  /// The `&mut` that [`commit`](SlotWriter::commit) wants is the caller's, on the [`SlotWriter`] it
  /// OWNS — outside this scope.
  ///
  /// ON THE FACE, beside [`Doc`](Self::Doc), because only a write spends either: a reader is never
  /// handed a writer's capability and is never shown a payload.
  type WriteContext<'a> = &'a mut SlotWriter;
  /// The engine's own entry — the source word, the identity, the stored address and the body,
  /// filled in by the emission and carried across the seam as one value.
  type Doc = TantivyDoc;

  fn upsert(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    doc: Self::Doc,
  ) -> Result<(), Self::Error> {
    upsert_entry(&self.slot, ctx.into_scope(), doc)
  }
}

/// The ASYNCHRONOUS write face — the blocking body above, resolved immediately, for
/// [`AsyncFulltextRead`]'s stated reason.
impl AsyncFulltextWrite for TantivyFulltext {
  /// `&mut `[`SlotWriter`]: the caller's write CAPABILITY for this slot, and NOT a transaction — the
  /// slot's sole writer and the fields to write through, minted together.
  ///
  /// **The EXCLUSIVE borrow is load-bearing.** It is not a stricter-than-necessary bound and the
  /// crate's bound-minimization convention does not reach it: a keyed replace is `delete_term` THEN
  /// `add_document`, a NON-ATOMIC two-step, and a tantivy delete only tombstones documents whose
  /// opstamp is LOWER than the delete's. Two `upsert` calls sharing one writer can therefore
  /// interleave as (delete, delete, add, add) and leave TWO documents under ONE identity — which is
  /// this backend's core obligation, keyed-idempotent apply, broken. `&mut` serializes the pair by
  /// construction: the borrow checker admits only (delete, add, delete, add).
  ///
  /// Both tantivy receivers being `&self` is exactly the observation that misleads here — `Sync` is
  /// not *safe to use concurrently for this protocol*, and a shared context was measured duplicating
  /// the entry in 24 of 30 raced iterations on the reference implementation.
  ///
  /// `IndexWriter::run` is NOT the rescue it looks like. It takes `&self` and allocates its group a
  /// CONTIGUOUS opstamp range, so `run([Delete, Add])` reads as an atomic replace that would make a
  /// shared context sound. Only the stamp RANGE is atomic: the body that spends it still pushes the
  /// delete and sends the add as separate unsynchronized steps, which two concurrent `run`s
  /// interleave — measured at 9 duplications in 30, against 24 for the plain pair. Contiguous stamps
  /// NARROW the window; they do not close it. Shared queueing needs an internal
  /// `Mutex<IndexWriter>`, and should be motivated by a measured throughput need rather than by the
  /// shape of a receiver.
  ///
  /// The `&mut` that [`commit`](SlotWriter::commit) wants is the caller's, on the [`SlotWriter`] it
  /// OWNS — outside this scope.
  ///
  /// ON THE FACE, beside [`Doc`](Self::Doc), because only a write spends either: a reader is never
  /// handed a writer's capability and is never shown a payload.
  type WriteContext<'a> = &'a mut SlotWriter;
  /// The engine's own entry — the source word, the identity, the stored address and the body,
  /// filled in by the emission and carried across the seam as one value.
  type Doc = TantivyDoc;

  #[inline]
  fn upsert(
    &self,
    ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
    doc: Self::Doc,
  ) -> impl Future<Output = Result<(), Self::Error>> + Send {
    ready(<Self as FulltextWrite>::upsert(self, ctx, doc))
  }
}

/// **THE WRITE LANE** — the four acts around [`upsert`](AsyncFulltextWrite::upsert) that a caller
/// holding only this engine cannot spell, answered in this backend's own terms.
///
/// Every member is the road an existing hand-written caller already takes, moved behind the seam
/// with nothing added: [`open`](FulltextLane::open) is
/// [`TantivyStore::writer`](TantivyStore::writer) at this handle's own slot,
/// [`scope`](FulltextLane::scope) is the `&mut SlotWriter` the write face's GAT already names,
/// [`entry`](FulltextLane::entry) is the [`TantivyDoc`] builder, and
/// [`publish`](FulltextLane::publish) is `commit` then `reload` — the pair that makes a write
/// findable rather than merely durable.
///
/// # `publish` DROPS the writer between the two steps, and that is load-bearing
///
/// A slot's writer holds tantivy's per-directory lockfile, and a subscriber opens one batch per
/// delivery — so a lane that reloaded while still holding the writer would leave the next delivery's
/// [`open`](FulltextLane::open) racing its own lock. The batch is taken BY VALUE for exactly this
/// reason: the drop is the release, and it is spelled where a reader can see it happen before the
/// reload.
///
/// # The ARENA is this backend's floor, and the knob for it is recorded rather than invented
///
/// [`MIN_WRITER_HEAP_BYTES`](TantivyStore::MIN_WRITER_HEAP_BYTES) is what a batch opens at. A
/// per-deployment arena is a real want and it has a home already — the node's own `options = "…"`
/// word, which is how every other launched node is tuned — so inventing a second one here would put
/// one knob in two places.
impl FulltextLane for TantivyFulltext {
  /// The slot's own [`SlotWriter`], held for one delivery.
  type Batch = SlotWriter;

  #[inline]
  fn open<S: crate::FulltextRoad>(
    &self,
    connection: &Self::Connection,
  ) -> Result<Self::Batch, Self::Error> {
    connection.slot_writer::<S>(TantivyStore::MIN_WRITER_HEAP_BYTES)
  }

  #[inline]
  fn scope(batch: &mut Self::Batch) -> Self::WriteContext<'_> {
    batch
  }

  fn entry<I, K>(
    &self,
    identity: &I,
    address: &K,
    segments: &crate::BoxWriter,
  ) -> Result<Self::Doc, Self::Error>
  where
    I: crate::Field,
    K: crate::Field,
  {
    let entry = TantivyDoc::new(self.slot.clone())
      .with_identity(identity)
      .with_address(address);
    let mut written = segments.segments();
    match (written.next(), written.len()) {
      (None, _) => Ok(entry),
      (Some(body), 0) => Ok(entry.with_body(body)),
      (Some(_), rest) => Err(TantivyFulltextError::Segmented {
        slot: self.slot.clone(),
        segments: rest + 1,
      }),
    }
  }

  fn publish(
    &self,
    connection: &Self::Connection,
    mut batch: Self::Batch,
  ) -> Result<(), Self::Error> {
    batch.commit()?;
    drop(batch);
    connection.reload(self.slot())
  }

  fn discard(&self, _connection: &Self::Connection, mut batch: Self::Batch) {
    // The rollback's own answer is dropped, and the trait's note is why: this runs where a refusal
    // is already on its way to a caller, and a second one has nowhere to go. Tantivy's rollback
    // swaps in a fresh writer, so the drop below releases a writer that is consistent either way.
    let _ = batch.rollback();
  }
}

/// Queue one entry's keyed replace through `writer` — the body of [`FulltextWrite::upsert`].
///
/// The connection is not needed at all: the scope carries BOTH halves of a write — the slot's writer
/// and that slot's fields — so this path resolves no slot, takes no cache lock and names no path.
/// What is left to check is the PAIRING, one compare per document, before either in-memory side
/// effect. It also subsumes the slot guard: a [`SlotWriter`] exists only for a slot
/// [`writer`](TantivyStore::writer) accepted, so a handle naming an INVALID slot can never match
/// one.
///
/// It reads NOTHING about a record. The identity, the address and the text were decided where the
/// record's type was known, and what arrives here is a built entry — which is why this function has
/// no type parameter and no `where` clause left.
fn upsert_entry(
  slot: &Utf8Bytes,
  writer: &mut SlotWriter,
  doc: TantivyDoc,
) -> Result<(), TantivyFulltextError> {
  if &writer.slot != slot {
    return Err(TantivyFulltextError::SlotMismatch(Box::new(
      SlotMismatch::new(slot.clone(), writer.slot.clone()),
    )));
  }
  let fields = writer.fields.clone();
  // EVERY LANE THIS ENTRY NAMED HAS TO EXIST, checked before either in-memory side effect. A lane
  // this slot does not hold has no field to land in, and the only alternatives to refusing are
  // dropping the text or inventing a field — see `LaneAbsent`.
  for (lane, _) in doc.bodies() {
    if fields.lane(lane).is_none() {
      return Err(TantivyFulltextError::LaneAbsent(Utf8Bytes::from(
        lane.to_owned(),
      )));
    }
  }
  // Delete-then-add: the delete tombstones the documents added at a LOWER opstamp, then the add
  // lands at a higher one and survives it. Both are in-memory QUEUE ops with no IO; visibility waits
  // on the caller's commit, never called here.
  //
  // The pair is NOT atomic, and the opstamp rule is why that matters: interleave a second replace of
  // the same identity between these two lines and its delete lands BELOW this add, tombstoning
  // nothing — two documents, one identity. The exclusive write scope is what forbids the
  // interleaving; see its doc, which is where that has already shipped a bug once.
  writer.writer.delete_term(Term::from_field_bytes(
    fields.identity,
    doc.identity().as_slice(),
  ));
  let mut entry = doc!(
    fields.source => doc.source(),
    fields.identity => doc.identity().as_slice().to_vec(),
    fields.key => doc.address().as_slice().to_vec(),
  );
  // ONE VALUE PER LANE FIELD, ALWAYS — the entry's own text where a run reached that lane, and the
  // empty string where none did. Writing every field rather than only the ones a run reached is what
  // keeps an unfanned corpus's document identical to the one this backend always wrote, and it is
  // the honest shape besides: a lane a document has nothing for HAS nothing, which is what an empty
  // field says.
  for (lane, field) in fields.lanes.iter() {
    entry.add_text(*field, doc.body_in(lane.as_str()).unwrap_or_default());
  }
  writer.writer.add_document(entry)?;
  Ok(())
}

/// Run one query against `slot`'s committed snapshot — the body of [`FulltextRead::search`].
///
/// Generic over NOTHING: no record and — since A′ — no key either. What a hit carries out is the
/// stored address VERBATIM, in this engine's own vocabulary, and reading it back into a declaration's
/// key type is the emission's act one layer up. That is where the `Trailing` check went too: this
/// function cannot know how many values a key reads, so it does not pretend to.
///
/// The score is tantivy's native BM25, which is already higher-is-better — so, unlike a cosine
/// face's `1 - distance`, there is NO negation. The query runs against the SUBSET's fields with no
/// clause beside them, and the corpus statistics it is computed from are this slot's own, which is
/// what makes scores from DIFFERENT slots incomparable: those are different corpora.
///
/// # The subset resolves against the SCHEMA, which is where the honest answer is short today
///
/// A tantivy slot's schema carries exactly one searchable text field ([`SEARCHABLE_FIELD`]), so
/// [`All`](FulltextSubset::All) is that field — the whole of what this backend has ever searched,
/// byte for byte — and a [`These`](FulltextSubset::These) naming it is the same query. Any OTHER
/// name is [`UnheldColumn`](TantivyFulltextError::UnheldColumn), which is this backend reporting
/// that the per-field document has not landed rather than answering from a box that holds every
/// elected field's text at once.
///
/// The resolution is a list because that is what it becomes: `QueryParser::for_index` takes the
/// default fields a BARE term resolves against, so a schema with several searchable columns needs no
/// second mechanism here — the same walk hands it a longer list.
fn search_slot(
  store: &TantivyStore,
  slot: &str,
  subset: FulltextSubset<'_>,
  query: &str,
  k: NonZeroUsize,
) -> Result<Hits<TantivyAddress, f32>, TantivyFulltextError> {
  // The DEFAULT posture, and a read is the wrong party to state one: what a slot keeps is the
  // declaration's word, spent at the write. A reader reaching a never-written slot creates it at the
  // default — see the posture note for the ordering that makes that harmless.
  let opened = store.slot_index(slot, false)?;
  let fields = opened.fields.clone();
  let scoped = scoped_fields(subset, &fields)?;
  let searcher = opened.reader.searcher();
  let parser = QueryParser::for_index(&opened.index, scoped);
  // Parse to the user AST, CHECK it, then build — validate-then-act, before the searcher is touched.
  // Splitting `parse_query` into its two halves is what makes the check possible at all: only
  // between them is the query still a tree of what the USER wrote rather than a `Box<dyn Query>`
  // nothing can inspect. `tantivy::query_grammar` is tantivy's own re-export, so the grammar is the
  // exact one the parser will use and not a second parser that could disagree with it.
  let ast = tantivy::query_grammar::parse_query(query)
    .map_err(|_| tantivy::TantivyError::from(QueryParserError::SyntaxError(query.to_owned())))?;
  refuse_unsearchable_fields(&ast, &fields)?;
  let parsed = parser
    .build_query_from_user_input_ast(ast)
    .map_err(tantivy::TantivyError::from)?;
  // The HANDED `k`, CLAMPED TO WHAT THE SLOT HOLDS — and the clamp is answer-preserving by
  // construction: a search cannot return more hits than there are live documents, so `min` can only
  // remove capacity this collector could never have filled. It is not a default and not a policy;
  // it is this backend refusing to allocate for hits that do not exist.
  //
  // It is load-bearing, not hygiene. `TopDocs::with_limit(n)` builds a `TopNComputer` that allocates
  // `Vec::with_capacity(n.max(1) * 2)` up front, so a caller meaning *no ceiling of my own* — the
  // emitted tier-B door says `usize::MAX`, which is a perfectly legal `NonZeroUsize` — would
  // overflow that multiply rather than search. `k` reaching the engine at all is what made an
  // unbounded ask expressible; this is the same seam's other half, where an engine states what
  // unbounded MEANS in its own storage.
  //
  // `.max(1)` because an EMPTY slot still has to run the query: `with_limit` asserts on zero, and a
  // never-written corpus answering *no hits* is the honest result rather than a panic.
  let ceiling = k.get().min(
    usize::try_from(searcher.num_docs())
      .unwrap_or(usize::MAX)
      .max(1),
  );
  // The fruit is score-descending; `order_by_score` is mandatory since 0.26 removed `TopDocs`'s bare
  // `Collector` impl.
  let top = searcher.search(&parsed, &TopDocs::with_limit(ceiling).order_by_score())?;
  let mut hits = Vec::with_capacity(top.len());
  for (score, at) in top {
    let retrieved: TantivyDocument = searcher.doc(at)?;
    let stored = retrieved
      .get_first(fields.key)
      .and_then(|value| value.as_bytes())
      .ok_or(TantivyFulltextError::MissingKey)?;
    hits.push(Scored::new(TantivyAddress::from(stored.to_vec()), score));
  }
  Ok(hits)
}

/// Resolve a [`FulltextSubset`] into the schema fields a bare term searches — validate-then-act, and
/// the whole of what a column selector costs this backend.
///
/// The slot's own [`Fields`] are passed in rather than looked up: the caller already opened the slot
/// and holds its field handles, and a second lookup here would be a second chance to resolve a
/// different one.
///
/// # A LANE IS A COLUMN, and that is what makes the read side of the fan need no new door
///
/// A slot's searchable columns are its lanes — `body` on an unfanned corpus, one per lane on a
/// fanned one — so asking ONE lane is a [`These`](FulltextSubset::These) naming it, and the probe a
/// router produced reaches this backend through the scope that already existed.
/// [`All`](FulltextSubset::All) is every lane, which on an unfanned corpus is the single `body` this
/// backend has always searched, byte for byte.
///
/// # Errors
///
/// [`TantivyFulltextError::EmptySubset`] for a [`These`](FulltextSubset::These) naming nothing;
/// [`TantivyFulltextError::UnheldColumn`] naming the FIRST column, in the caller's own order, that
/// this slot's schema does not hold.
fn scoped_fields(
  subset: FulltextSubset<'_>,
  fields: &Fields,
) -> Result<Vec<SchemaField>, TantivyFulltextError> {
  let columns = match subset {
    FulltextSubset::All => return Ok(fields.searchable()),
    FulltextSubset::These([]) => return Err(TantivyFulltextError::EmptySubset),
    FulltextSubset::These(columns) => columns,
  };
  columns
    .iter()
    .map(|column| {
      fields
        .column(column.as_str())
        .ok_or(TantivyFulltextError::UnheldColumn { column: *column })
    })
    .collect()
}

/// Refuse a parsed query that names any field but [`SEARCHABLE_FIELD`].
///
/// Walks the WHOLE AST, because a field name can be anywhere in it: nested boolean clauses carry
/// their own sub-trees, a boost wraps one, and a leaf carries the name itself — on a literal, on a
/// range's or a set's or a regex's field, and on an `Exists`, where the field IS the query. A check
/// that looked only at the top level would pass `body:fox AND key:<base64>`, which is the shape an
/// attacker writes.
///
/// `None` is the BARE form (`fox`, `[a TO b]`) and is legal: it resolves against the parser's
/// default fields, which are the SCOPE's and therefore this slot's lanes and nothing else. So this
/// rejects exactly the EXPLICIT names, which is the whole of what the default-field argument does
/// not constrain.
///
/// The whitelist is the slot's own [`Fields`] rather than one name, and the DIRECTION is unchanged:
/// a lane's field is admitted because the roster carried it, and every other field of the schema —
/// the stored `key` above all — is refused because it is not in the roster.
///
/// # Errors
///
/// [`TantivyFulltextError::UnsearchableField`] naming the first offending field in walk order.
fn refuse_unsearchable_fields(
  ast: &UserInputAst,
  fields: &Fields,
) -> Result<(), TantivyFulltextError> {
  fn named(field: Option<&String>, fields: &Fields) -> Result<(), TantivyFulltextError> {
    match field {
      Some(name) if !fields.searches(name) => Err(TantivyFulltextError::UnsearchableField {
        field: name.clone(),
      }),
      _ => Ok(()),
    }
  }

  match ast {
    UserInputAst::Clause(clauses) => clauses
      .iter()
      .try_for_each(|(_, sub)| refuse_unsearchable_fields(sub, fields)),
    UserInputAst::Boost(inner, _) => refuse_unsearchable_fields(inner, fields),
    UserInputAst::Leaf(leaf) => match leaf.as_ref() {
      UserInputLeaf::Literal(literal) => named(literal.field_name.as_ref(), fields),
      UserInputLeaf::Range { field, .. }
      | UserInputLeaf::Set { field, .. }
      | UserInputLeaf::Regex { field, .. } => named(field.as_ref(), fields),
      // `Exists` has no `Option`: the field IS the leaf, so a bare form does not exist here.
      UserInputLeaf::Exists { field } => named(Some(field), fields),
      UserInputLeaf::All => Ok(()),
    },
  }
}

/// **THE FACTORY VISITOR** — layer two's machine for a tantivy-backed resource: shown one declared
/// type at a time, it creates every corpus that type owns in this mount.
///
/// ```text
/// Shared<Ft> ──► TantivySlotMaker<Ft> ──next_type::<Media>()──► Media's blueprint
///                       │                                             │
///                       │  per corpus: create_slot(schema, knobs)      │
///                       └──────────────► TantivyStore ◄───────────────┘
/// ```
///
/// # It is the AUTHOR'S MACHINE, and this one happens to ship
///
/// A slot maker holds its own connection and its own per-slot values, which is why the walk hands it
/// nothing but types: `#[ingraph::resource(tantivy)]` names this as its initializer because the
/// framework wrote that engine, and a foreign resource's author writes theirs beside their own
/// faces. Nothing about the walk is specialised to it.
///
/// # THE KNOB TABLE is where the [`Options`](crate::FulltextEngine::Options) seat lands
///
/// The blueprint is a `const` and carries only what a DECLARATION states; a tokenizer choice is a
/// value a DEPLOYMENT decides, and it arrives at boot. So the visitor holds the per-slot table, and
/// its VALUE TYPE is the projection — `<TantivyFulltext as FulltextEngine>::Options` — which is what
/// makes the seat a real position rather than a reservation. It is EMPTY on the launch's own path
/// today: the seat is `()` at this backend, so there is nothing to write into it and no document row
/// invented to pretend otherwise. [`with_knobs`](Self::with_knobs) is the door a hand-driven walk
/// fills it through.
///
/// # It records what it MADE
///
/// [`made`](Self::made) is the corpora this walk created, in walk order — which is how a deployment,
/// or a test, states that the walk ran at all. It is the only observation the visitor keeps.
///
/// # Under `runtime`, where the rest of this file is under none
///
/// It is the one item here whose type PARAMETER is a tier's: `R: AsyncResource`, and the
/// `Shared<R>` it holds, are the shareable-resource layer's and ride that word. The engine itself —
/// the connection, the slot handles, the writer, the term codec — names none of it, so a build
/// taking the full-text backend without the drive layer gets every door and not this walk. What the
/// walk is FOR is a launch, and a build with no launch has nothing to run one with.
#[cfg(feature = "runtime")]
#[derive(Debug, Clone)]
pub struct TantivySlotMaker<R: crate::AsyncResource> {
  mount: crate::Shared<R>,
  knobs: HashMap<Utf8Bytes, <TantivyFulltext as crate::FulltextEngine>::Options>,
  made: Vec<Utf8Bytes>,
}

#[cfg(feature = "runtime")]
impl<R: crate::AsyncResource> TantivySlotMaker<R> {
  /// A maker over `mount`, with no per-slot knobs and nothing made yet.
  #[inline]
  #[must_use]
  pub fn new(mount: crate::Shared<R>) -> Self {
    Self {
      mount,
      knobs: HashMap::new(),
      made: Vec::new(),
    }
  }

  /// The knobs this deployment names for the corpus `slot`.
  ///
  /// The value's type is the engine's own [`Options`](crate::FulltextEngine::Options), so a caller
  /// writes whatever that backend takes and nothing here interprets it.
  #[inline]
  #[must_use]
  pub fn with_knobs(
    mut self,
    slot: impl Into<Utf8Bytes>,
    knobs: <TantivyFulltext as crate::FulltextEngine>::Options,
  ) -> Self {
    self.knobs.insert(slot.into(), knobs);
    self
  }

  /// The corpora this walk created, in walk order.
  #[inline]
  #[must_use]
  pub fn made(&self) -> &[Utf8Bytes] {
    &self.made
  }
}

/// The BLOCKING face, because opening a tantivy index is two syscalls and no await — the same
/// measurement that puts this store on [`FulltextStore`] rather than on its awaited twin.
///
/// The `Db` is the RESOURCE and not the engine, which is the grain the whole layer turns on: two
/// deployments' stores are two resource types and therefore two habitats, so a declaration electing
/// into one of them is `E0277` at the other. An engine-keyed habitat would have collapsed them into
/// one and made a second tantivy mount unaddressable.
#[cfg(feature = "runtime")]
impl<R> crate::TypeVisitor for TantivySlotMaker<R>
where
  R: crate::AsyncResource
    + crate::Habitat<Blueprint = &'static [crate::SlotSchema]>
    + crate::FulltextMount<Handle = TantivyFulltext>,
{
  type Db = R;
  type Error = TantivyFulltextError;

  fn next_type<E: crate::Describe<R>>(&mut self) -> Result<(), Self::Error> {
    let store = crate::FulltextMount::connection(self.mount.get());
    for schema in <E as crate::Describe<R>>::BLUEPRINT {
      let slot = Utf8Bytes::from_static(schema.slot().as_ref());
      store.create_slot(schema, self.knobs.get(&slot))?;
      self.made.push(slot);
    }
    Ok(())
  }
}

#[cfg(test)]
mod face_tests;
#[cfg(test)]
mod lane_tests;
#[cfg(test)]
mod pipeline_tests;
#[cfg(all(test, feature = "runtime"))]
mod slot_maker_tests;
#[cfg(test)]
mod stored_tests;
#[cfg(test)]
mod subset_tests;
#[cfg(test)]
mod tests;