rete-core 0.7.7

Core format types for the Rete cloud-native RDF graph file.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
//! The **quad index** (SPEC.md §6.5): every named-graph quad stored once, as the
//! fourth column of graph-leading permutations (`G+SPO`, `G+POS`, `G+OSP`, and
//! `G+SOP`, `G+PSO`, `G+OPS` when the file carries six), cut into ~64 KiB tiles
//! that many graphs share, behind a sorted graph directory.
//!
//! It replaces the per-graph layout of the NAMED_GRAPHS section (kind 5), where
//! every graph carried its IRI as raw text and a full permutation container with
//! one zstd frame per tile, chained with no directory: on the OpenCitations
//! sample that was ~650 B per ~10-quad graph and a sequential walk to reach any
//! one of them. Here a graph costs a few bytes of segment header per order, and
//! a reader resolves it by binary search: dictionary (IRI → id), then each
//! order's tile directory.
//!
//! The query engine never sees the shared tiles. [`QuadNamed::graph_at`] hands
//! out a **view**: an ordinary remote-style [`GraphIndex`] over one graph's slice
//! of the tiles, whose tile loader cuts that graph's segment out of the shared
//! (cached, decompressed) tile and re-encodes it as a §6.1 block. So routing,
//! synopsis pruning, merge joins and every `Rete` API work unchanged.
//!
//! One [`QuadTiler`] decides tile boundaries for both builders (in-RAM here,
//! external in `extbuild`), so their outputs are byte-identical.

use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, RwLock};

use crate::chunk_cache::{CacheEntry, ChunkCache};
use crate::dictionary::Dictionary;
use crate::file::{compress, ByteRange, FileError, CODEC_NONE};
use crate::index::{
    DeferredTiles, GraphIndex, GroupSizer, IndexPermutation, PermSet, ALL_PERMS, NUM_PERMS,
};
use crate::quad7::{self, NUM_SLOTS};
use crate::reader::RangeReader;
use crate::triples::{Triple, TripleBlockBuilder};
use crate::varint::{read_uvarint, write_uvarint};

/// Magic of the QUAD_INDEX section and of the seal in the index container.
pub(crate) const QUAD_MAGIC: [u8; 4] = *b"RQIX";
/// Layout version of the section (and the seal).
pub(crate) const QUAD_VERSION: u8 = 1;
/// Layout version of the section as the writers hand it to the `0x06`/`0x07`
/// assembler (never in a released file): the order mask is any set that holds
/// `G+SPO`, not the file's permutation set. A `0x07` writer needs only `G+SPO`:
/// the other orders are derived from it, so the builders do not write the
/// graph-leading ones at all.
pub(crate) const QUAD_VERSION_SUBSET: u8 = 2;
/// Seal: magic, version, 16-byte blake3 digest of the QUAD_INDEX section.
pub(crate) const SEAL_LEN: usize = 4 + 1 + 16;
/// Graphs per graph-directory block.
pub(crate) const DIR_BLOCK_GRAPHS: u64 = 1024;
/// Graphs per graph-directory block in a `0x07` file. The block index is part of
/// the root, so it grows with the graph count: at 1,024 graphs a block it was
/// 42,200 entries and most of the nanopubs' 100 KB root. A block of 8,192 graphs
/// is about 4 KB stored (the ids are close to consecutive), the cost of the one
/// block a graph lookup reads, and the index is a quarter of the root it was.
pub(crate) const DIR_BLOCK_GRAPHS_07: u64 = 8192;
/// Bytes charged against the tile budget for one segment header (Δg, zigzag
/// first a, body length, a-group count). An estimate: only determinism matters,
/// so both builders cut at the same rows.
const SEGMENT_OVERHEAD: usize = 8;
/// Upper bound on the preamble: 8 fixed bytes, four varints, at most
/// `2 + 2·6` part lengths.
const PREAMBLE_MAX: u64 = 8 + 4 * 10 + 14 * 10;
/// Ceiling of the sequential read-ahead over tiles or directory blocks.
const READ_AHEAD_MAX: usize = 64;
/// Entries per lazily-allocated slab of per-graph cells.
const ENTRY_SLAB: usize = 1024;
/// Largest span of all orders' tile directories fetched together on first use
/// (one request instead of one per order).
const DIRS_TOGETHER_MAX: u64 = 4 << 20;

/// A quad in one graph-leading order: `(g, a, b, c)`, `(a, b, c)` being the
/// permuted `(s, p, o)`.
pub(crate) type QuadRow = (u32, u32, u32, u32);

/// The orders a quad index may carry: exactly the file's default-graph set,
/// and only one of the two the CLI writes. Three plus the seal is four
/// container sections and six plus the seal is seven; a five-order set would
/// make seven-minus-one = six, which a 0.3.0–0.3.3 reader would accept (see
/// `docs/compatibility.md`, "named graphs in the quad index").
pub(crate) fn check_perms(perms: PermSet) -> Result<(), FileError> {
    if perms == PermSet::ALL || perms == PermSet::CORE {
        Ok(())
    } else {
        Err(FileError::Container(
            "the quad index needs the 3- or 6-permutation set",
        ))
    }
}

pub(crate) fn zigzag(v: i64) -> u64 {
    ((v << 1) ^ (v >> 63)) as u64
}

pub(crate) fn unzigzag(u: u64) -> i64 {
    ((u >> 1) as i64) ^ -((u & 1) as i64)
}

/// Read one varint at `*pos`, advancing it; `None` when truncated.
fn rd64(bytes: &[u8], pos: &mut usize) -> Option<u64> {
    let (v, n) = read_uvarint(bytes.get(*pos..)?)?;
    *pos += n;
    Some(v)
}

/// [`rd64`] for a value that must fit an id.
fn rd32(bytes: &[u8], pos: &mut usize) -> Option<u32> {
    u32::try_from(rd64(bytes, pos)?).ok()
}

// ---------------------------------------------------------------------------
// Writing
// ---------------------------------------------------------------------------

/// Streaming tile cutter over rows sorted by `(g, a, b, c)` and deduplicated.
///
/// Whole `(g, a)` groups are packed until the estimated encoded size would pass
/// the budget; a group larger than the budget on its own is cut mid-group into
/// consecutive tiles, the mega-group rule of `index::build_tiles`. A graph may
/// run on into the next tile, where it opens a new segment. Holds one tile plus
/// one group slice, so memory is bounded by the budget whatever the input.
pub(crate) struct QuadTiler {
    budget: usize,
    tile: Vec<QuadRow>,
    tile_size: usize,
    group: Vec<QuadRow>,
    sizer: GroupSizer,
    gextra: usize,
    gtotal: usize,
    /// `(g, a)` of the last group packed into the current tile.
    prev: Option<(u32, u32)>,
    count: u64,
}

impl QuadTiler {
    /// A tiler at the index tile budget in force (`--tile-kib`,
    /// `crate::write_opts`; 64 KiB by default), like the default graph's tiles.
    pub(crate) fn new() -> Self {
        Self::with_budget(crate::write_opts::tile_budget())
    }

    pub(crate) fn with_budget(budget: usize) -> Self {
        QuadTiler {
            budget: budget.max(1),
            tile: Vec::new(),
            tile_size: 0,
            group: Vec::new(),
            sizer: GroupSizer::start(0, 0),
            gextra: 0,
            gtotal: 0,
            prev: None,
            count: 0,
        }
    }

    /// Push the next row (strictly ascending); `emit` receives each finished
    /// tile's rows.
    pub(crate) fn push(&mut self, q: QuadRow, emit: &mut dyn FnMut(Vec<QuadRow>)) {
        self.count += 1;
        if let Some(&(g0, a0, _, _)) = self.group.first() {
            if (q.0, q.1) != (g0, a0) {
                self.close_group(emit);
            }
        }
        if self.group.is_empty() {
            let (base, seg) = match self.prev {
                Some((pg, pa)) if pg == q.0 && !self.tile.is_empty() => (pa, 0),
                _ => (q.1, SEGMENT_OVERHEAD),
            };
            self.sizer = GroupSizer::start(q.1, base);
            self.gextra = seg;
        }
        self.group.push(q);
        self.gtotal = self.sizer.push(q.2, q.3) + self.gextra;
        if self.gtotal > self.budget {
            // Mega-group cut: everything buffered plus the slice measured so
            // far becomes one tile; the group goes on in a fresh one.
            self.tile.append(&mut self.group);
            self.flush(emit);
            self.gtotal = 0;
        }
    }

    fn close_group(&mut self, emit: &mut dyn FnMut(Vec<QuadRow>)) {
        let Some(&(g, a, _, _)) = self.group.first() else {
            return;
        };
        if !self.tile.is_empty() && self.tile_size + self.gtotal > self.budget {
            self.flush(emit);
        }
        self.tile_size += self.gtotal;
        self.prev = Some((g, a));
        self.tile.append(&mut self.group);
        self.gtotal = 0;
    }

    fn flush(&mut self, emit: &mut dyn FnMut(Vec<QuadRow>)) {
        if !self.tile.is_empty() {
            emit(std::mem::take(&mut self.tile));
        }
        self.tile_size = 0;
        self.prev = None;
    }

    /// Close the last group and tile.
    pub(crate) fn finish(mut self, emit: &mut dyn FnMut(Vec<QuadRow>)) -> u64 {
        self.close_group(emit);
        self.flush(emit);
        self.count
    }
}

/// One tile, encoded and packed: its key range, the synopsis of its two
/// non-leading columns, and its stored bytes (`raw` = not compressed).
pub(crate) struct EncodedTile {
    first: (u32, u32),
    last: (u32, u32),
    syn: (u32, u32, u32, u32),
    pub(crate) bytes: Vec<u8>,
    raw: bool,
}

/// Compress `body` with `codec`, keeping it raw when that does not shrink it.
pub(crate) fn pack(codec: u8, body: Vec<u8>) -> (Vec<u8>, bool) {
    if codec == CODEC_NONE {
        return (body, true);
    }
    let c = compress(codec, &body);
    if c.len() < body.len() {
        (c, false)
    } else {
        (body, true)
    }
}

/// Which trailing column of a graph-leading order holds the **subject**:
/// `(b, c)`. Within one graph the subjects are a handful of ids (OpenCitations:
/// a record's snapshots) that recur across every a-group, so in that column the
/// first value of a run is coded relative to the previous run's first value
/// (zigzag) instead of from 0 — measured on the M=1200 sample, it shrinks the
/// four orders with a trailing subject by 46–49% (G+POS 30.5 → 16.3 MB). The
/// object column is left alone: the same rule makes G+SPO 64% larger.
pub(crate) fn subject_columns(perm: IndexPermutation) -> (bool, bool) {
    let r = perm.roles();
    (r[1] == 0, r[2] == 0)
}

/// Encode one graph's rows of a tile (sorted `(a, b, c)`, first a carried in
/// the segment header): `num_a`, then the §6.1 groups with the first group's
/// `Δa` omitted — and, in the subject column ([`subject_columns`]), the first
/// value of each run as `zigzag(v − previous run's first v)`, 0-based per
/// segment.
fn encode_segment_body(rows: &[QuadRow], (zz_b, zz_c): (bool, bool), out: &mut Vec<u8>) {
    let mut num_a = 0u64;
    let mut i = 0;
    while i < rows.len() {
        let a = rows[i].1;
        while i < rows.len() && rows[i].1 == a {
            i += 1;
        }
        num_a += 1;
    }
    write_uvarint(out, num_a);
    let mut prev_a = rows[0].1;
    let (mut base_b, mut base_c) = (0i64, 0i64);
    let mut i = 0;
    let mut first = true;
    while i < rows.len() {
        let a = rows[i].1;
        let mut j = i;
        while j < rows.len() && rows[j].1 == a {
            j += 1;
        }
        if !first {
            write_uvarint(out, (a - prev_a) as u64);
        }
        first = false;
        prev_a = a;
        let group = &rows[i..j];
        let mut num_b = 0u64;
        let mut k = 0;
        while k < group.len() {
            let b = group[k].2;
            while k < group.len() && group[k].2 == b {
                k += 1;
            }
            num_b += 1;
        }
        write_uvarint(out, num_b);
        let mut prev_b = 0u32;
        let mut k = 0;
        while k < group.len() {
            let b = group[k].2;
            let mut l = k;
            while l < group.len() && group[l].2 == b {
                l += 1;
            }
            if zz_b && k == 0 {
                write_uvarint(out, zigzag(b as i64 - base_b));
                base_b = b as i64;
            } else {
                write_uvarint(out, (b - prev_b) as u64);
            }
            prev_b = b;
            write_uvarint(out, (l - k) as u64);
            let mut prev_c = 0u32;
            for (n, r) in group[k..l].iter().enumerate() {
                if zz_c && n == 0 {
                    write_uvarint(out, zigzag(r.3 as i64 - base_c));
                    base_c = r.3 as i64;
                } else {
                    write_uvarint(out, (r.3 - prev_c) as u64);
                }
                prev_c = r.3;
            }
            k = l;
        }
        i = j;
    }
}

/// Encode and pack one tile's rows (sorted, deduplicated, non-empty) of the
/// graph-leading order `perm`.
pub(crate) fn encode_tile(rows: &[QuadRow], codec: u8, perm: IndexPermutation) -> EncodedTile {
    let cols = subject_columns(perm);
    debug_assert!(!rows.is_empty());
    let mut segments = 0u64;
    let mut i = 0;
    while i < rows.len() {
        let g = rows[i].0;
        while i < rows.len() && rows[i].0 == g {
            i += 1;
        }
        segments += 1;
    }
    let mut out = Vec::new();
    write_uvarint(&mut out, segments);
    let mut prev_g = rows[0].0;
    let mut prev_fa = 0u32;
    let mut body = Vec::new();
    let mut i = 0;
    while i < rows.len() {
        let g = rows[i].0;
        let mut j = i;
        while j < rows.len() && rows[j].0 == g {
            j += 1;
        }
        write_uvarint(&mut out, (g - prev_g) as u64);
        prev_g = g;
        let fa = rows[i].1;
        write_uvarint(&mut out, zigzag(fa as i64 - prev_fa as i64));
        prev_fa = fa;
        body.clear();
        encode_segment_body(&rows[i..j], cols, &mut body);
        write_uvarint(&mut out, body.len() as u64);
        out.extend_from_slice(&body);
        i = j;
    }
    let (mut min_b, mut max_b, mut min_c, mut max_c) = (u32::MAX, 0u32, u32::MAX, 0u32);
    for r in rows {
        min_b = min_b.min(r.2);
        max_b = max_b.max(r.2);
        min_c = min_c.min(r.3);
        max_c = max_c.max(r.3);
    }
    let first = (rows[0].0, rows[0].1);
    let last = (rows[rows.len() - 1].0, rows[rows.len() - 1].1);
    let (bytes, raw) = pack(codec, out);
    EncodedTile {
        first,
        last,
        syn: (min_b, max_b, min_c, max_c),
        bytes,
        raw,
    }
}

/// Encode a batch of tiles, in parallel when the `parallel` feature is on
/// (order preserved, so the output is identical either way).
pub(crate) fn encode_tiles(
    batch: &[Vec<QuadRow>],
    codec: u8,
    perm: IndexPermutation,
) -> Vec<EncodedTile> {
    #[cfg(feature = "parallel")]
    {
        use rayon::prelude::*;
        batch
            .par_iter()
            .map(|t| encode_tile(t, codec, perm))
            .collect()
    }
    #[cfg(not(feature = "parallel"))]
    {
        batch.iter().map(|t| encode_tile(t, codec, perm)).collect()
    }
}

/// Accumulates one order's tile directory while its payloads are written
/// elsewhere (a `Vec` in RAM, a spill file in the external build).
#[derive(Default)]
pub(crate) struct PermDirWriter {
    entries: Vec<u8>,
    num_tiles: u64,
    prev_first_g: u32,
    payload_len: u64,
}

impl PermDirWriter {
    pub(crate) fn add(&mut self, t: &EncodedTile) {
        let e = &mut self.entries;
        write_uvarint(e, (t.first.0 - self.prev_first_g) as u64);
        write_uvarint(e, t.first.1 as u64);
        write_uvarint(e, (t.last.0 - t.first.0) as u64);
        write_uvarint(e, t.last.1 as u64);
        write_uvarint(e, ((t.bytes.len() as u64) << 1) | t.raw as u64);
        let (min_b, max_b, min_c, max_c) = t.syn;
        write_uvarint(e, min_b as u64);
        write_uvarint(e, (max_b - min_b) as u64);
        write_uvarint(e, min_c as u64);
        write_uvarint(e, (max_c - min_c) as u64);
        self.prev_first_g = t.first.0;
        self.num_tiles += 1;
        self.payload_len += t.bytes.len() as u64;
    }

    /// Bytes of the tiles' payloads written so far (the external builder
    /// spills them; it does not exist on wasm32).
    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
    pub(crate) fn payload_len(&self) -> u64 {
        self.payload_len
    }

    /// The finished directory part.
    pub(crate) fn finish(self) -> Vec<u8> {
        let mut out = Vec::with_capacity(self.entries.len() + 10);
        write_uvarint(&mut out, self.num_tiles);
        out.extend_from_slice(&self.entries);
        out
    }
}

/// Accumulates the graph directory: `(graph id, quad count)` in ascending id
/// order, cut into blocks of [`DIR_BLOCK_GRAPHS`]. Block bodies go to `sink`;
/// the small block index stays in RAM.
pub(crate) struct GraphDirWriter {
    codec: u8,
    block_graphs: u64,
    block: Vec<(u32, u64)>,
    index: Vec<u8>,
    num_blocks: u64,
    prev_first_g: u32,
    blocks_len: u64,
    graphs: u64,
}

impl GraphDirWriter {
    pub(crate) fn new(codec: u8) -> Self {
        Self::with_block_graphs(codec, DIR_BLOCK_GRAPHS)
    }

    /// A writer cutting blocks of `block_graphs` graphs.
    pub(crate) fn with_block_graphs(codec: u8, block_graphs: u64) -> Self {
        GraphDirWriter {
            codec,
            block_graphs,
            block: Vec::with_capacity(block_graphs as usize),
            index: Vec::new(),
            num_blocks: 0,
            prev_first_g: 0,
            blocks_len: 0,
            graphs: 0,
        }
    }

    pub(crate) fn push(
        &mut self,
        g: u32,
        count: u64,
        sink: &mut dyn std::io::Write,
    ) -> std::io::Result<()> {
        self.block.push((g, count));
        self.graphs += 1;
        if self.block.len() as u64 == self.block_graphs {
            self.flush_block(sink)?;
        }
        Ok(())
    }

    fn flush_block(&mut self, sink: &mut dyn std::io::Write) -> std::io::Result<()> {
        let Some(&(first, _)) = self.block.first() else {
            return Ok(());
        };
        let mut body = Vec::with_capacity(self.block.len() * 3);
        let mut prev = first;
        for &(g, n) in &self.block {
            write_uvarint(&mut body, (g - prev) as u64);
            write_uvarint(&mut body, n);
            prev = g;
        }
        let (bytes, raw) = pack(self.codec, body);
        write_uvarint(&mut self.index, (first - self.prev_first_g) as u64);
        write_uvarint(&mut self.index, ((bytes.len() as u64) << 1) | raw as u64);
        self.prev_first_g = first;
        self.num_blocks += 1;
        self.blocks_len += bytes.len() as u64;
        sink.write_all(&bytes)?;
        self.block.clear();
        Ok(())
    }

    /// Flush the last block; returns `(block index part, blocks part length,
    /// graph count)`.
    pub(crate) fn finish(
        mut self,
        sink: &mut dyn std::io::Write,
    ) -> std::io::Result<(Vec<u8>, u64, u64)> {
        self.flush_block(sink)?;
        let mut out = Vec::with_capacity(self.index.len() + 10);
        write_uvarint(&mut out, self.num_blocks);
        out.extend_from_slice(&self.index);
        Ok((out, self.blocks_len, self.graphs))
    }
}

/// The section's preamble: magic, version, order mask, counts and the part
/// table (`part_lens` in part order — see SPEC.md §6.5), for an order mask and
/// a layout version.
pub(crate) fn encode_preamble_mask(
    mask: u8,
    version: u8,
    graph_count: u64,
    quad_count: u64,
    part_lens: &[u64],
) -> Vec<u8> {
    let mut out = Vec::with_capacity(64);
    out.extend_from_slice(&QUAD_MAGIC);
    out.push(version);
    out.push(mask);
    out.extend_from_slice(&[0, 0]);
    write_uvarint(&mut out, graph_count);
    write_uvarint(&mut out, quad_count);
    write_uvarint(&mut out, DIR_BLOCK_GRAPHS);
    write_uvarint(&mut out, part_lens.len() as u64);
    for &l in part_lens {
        write_uvarint(&mut out, l);
    }
    out
}

/// A finished in-RAM QUAD_INDEX section.
pub(crate) struct EncodedQuadIndex {
    pub(crate) bytes: Vec<u8>,
    pub(crate) graph_count: u64,
    pub(crate) quad_count: u64,
}

#[cfg(feature = "parallel")]
fn sort_rows(v: &mut [QuadRow]) {
    use rayon::slice::ParallelSliceMut;
    v.par_sort_unstable();
}
#[cfg(not(feature = "parallel"))]
fn sort_rows(v: &mut [QuadRow]) {
    v.sort_unstable();
}

/// Tiles per encode batch: bounds the rows held outside the source vector.
const ENCODE_BATCH: usize = 256;

/// Encode a batch of finished tiles into `dir` + `payload`, emptying it.
fn drain_tiles(
    pending: &mut Vec<Vec<QuadRow>>,
    codec: u8,
    perm: IndexPermutation,
    dir: &mut PermDirWriter,
    payload: &mut Vec<u8>,
) {
    for t in encode_tiles(pending, codec, perm) {
        dir.add(&t);
        payload.extend_from_slice(&t.bytes);
    }
    pending.clear();
}

/// Tile one order's sorted rows into `payload`, returning its directory part.
fn tile_order(
    rows: &[QuadRow],
    codec: u8,
    perm: IndexPermutation,
    payload: &mut Vec<u8>,
) -> Vec<u8> {
    let mut dir = PermDirWriter::default();
    let mut pending: Vec<Vec<QuadRow>> = Vec::new();
    let mut tiler = QuadTiler::new();
    for &r in rows {
        tiler.push(r, &mut |t| pending.push(t));
        if pending.len() >= ENCODE_BATCH {
            drain_tiles(&mut pending, codec, perm, &mut dir, payload);
        }
    }
    tiler.finish(&mut |t| pending.push(t));
    drain_tiles(&mut pending, codec, perm, &mut dir, payload);
    dir.finish()
}

/// Build the QUAD_INDEX section from named-graph quads `(g, s, p, o)` (graph =
/// the graph name's subject id), for the orders in `perms`.
pub(crate) fn encode_quad_index(
    quads: Vec<[u32; 4]>,
    perms: PermSet,
    codec: u8,
) -> Result<EncodedQuadIndex, FileError> {
    check_perms(perms)?;
    encode_quad_orders(quads, perms.bits(), QUAD_VERSION, codec)
}

/// [`encode_quad_index`] for the writers of `0x07`: the section carries `G+SPO`
/// alone ([`QUAD_VERSION_SUBSET`]); the assembler derives the other orders.
pub(crate) fn encode_quad_gspo(
    quads: Vec<[u32; 4]>,
    codec: u8,
) -> Result<EncodedQuadIndex, FileError> {
    encode_quad_orders(quads, 1, QUAD_VERSION_SUBSET, codec)
}

fn encode_quad_orders(
    quads: Vec<[u32; 4]>,
    mask: u8,
    version: u8,
    codec: u8,
) -> Result<EncodedQuadIndex, FileError> {
    // G+SPO rows are the input itself, sorted and deduplicated — every other
    // order is permuted from that (smaller) set.
    let mut spo: Vec<QuadRow> = quads
        .into_iter()
        .map(|q| (q[0], q[1], q[2], q[3]))
        .collect();
    sort_rows(&mut spo);
    spo.dedup();
    let quad_count = spo.len() as u64;

    // The graph directory: distinct graphs with their deduplicated counts.
    let mut gdir = GraphDirWriter::new(codec);
    let mut gblocks: Vec<u8> = Vec::new();
    let mut i = 0;
    while i < spo.len() {
        let g = spo[i].0;
        let mut j = i;
        while j < spo.len() && spo[j].0 == g {
            j += 1;
        }
        gdir.push(g, (j - i) as u64, &mut gblocks)
            .map_err(FileError::Io)?;
        i = j;
    }
    let (gindex, gblocks_len, graph_count) = gdir.finish(&mut gblocks).map_err(FileError::Io)?;
    debug_assert_eq!(gblocks_len as usize, gblocks.len());

    let n_orders = mask.count_ones() as usize;
    let mut dirs: Vec<Vec<u8>> = Vec::with_capacity(n_orders);
    let mut payloads: Vec<Vec<u8>> = Vec::with_capacity(n_orders);
    for perm in ALL_PERMS
        .into_iter()
        .filter(|p| mask & (1 << p.section_index()) != 0)
    {
        let mut payload = Vec::new();
        let dir = if perm == IndexPermutation::Spo {
            tile_order(&spo, codec, perm, &mut payload)
        } else {
            let mut rows: Vec<QuadRow> = spo
                .iter()
                .map(|&(g, s, p, o)| {
                    let (a, b, c) = perm.forward((s, p, o));
                    (g, a, b, c)
                })
                .collect();
            sort_rows(&mut rows);
            tile_order(&rows, codec, perm, &mut payload)
        };
        dirs.push(dir);
        payloads.push(payload);
    }

    let mut part_lens = vec![gindex.len() as u64];
    part_lens.extend(dirs.iter().map(|d| d.len() as u64));
    part_lens.push(gblocks.len() as u64);
    part_lens.extend(payloads.iter().map(|p| p.len() as u64));
    let mut bytes = encode_preamble_mask(mask, version, graph_count, quad_count, &part_lens);
    bytes.extend_from_slice(&gindex);
    for d in &dirs {
        bytes.extend_from_slice(d);
    }
    bytes.extend_from_slice(&gblocks);
    for p in &payloads {
        bytes.extend_from_slice(p);
    }
    Ok(EncodedQuadIndex {
        bytes,
        graph_count,
        quad_count,
    })
}

/// The 16-byte digest a seal carries.
pub(crate) fn digest(bytes: &[u8]) -> [u8; 16] {
    let mut out = [0u8; 16];
    out.copy_from_slice(&blake3::hash(bytes).as_bytes()[..16]);
    out
}

/// The seal section appended to the index container of a quad-index file.
pub(crate) fn encode_seal(section_digest: [u8; 16]) -> Vec<u8> {
    let mut out = Vec::with_capacity(SEAL_LEN);
    out.extend_from_slice(&QUAD_MAGIC);
    out.push(QUAD_VERSION);
    out.extend_from_slice(&section_digest);
    out
}

/// Parse a seal, returning the digest it carries.
pub(crate) fn parse_seal(bytes: &[u8]) -> Result<[u8; 16], FileError> {
    if bytes.len() != SEAL_LEN || bytes[0..4] != QUAD_MAGIC {
        return Err(FileError::Container("malformed quad-index seal"));
    }
    if bytes[4] != QUAD_VERSION {
        return Err(FileError::Container(
            "unsupported quad-index version: this file needs a newer rete",
        ));
    }
    let mut d = [0u8; 16];
    d.copy_from_slice(&bytes[5..]);
    Ok(d)
}

// ---------------------------------------------------------------------------
// Reading
// ---------------------------------------------------------------------------

/// The rank of `perm` among the orders of `mask`: its position among the
/// section's order parts.
fn rank_in(mask: u8, perm: IndexPermutation) -> Option<usize> {
    let bit = 1u8 << perm.section_index();
    (mask & bit != 0).then(|| (mask & (bit - 1)).count_ones() as usize)
}

/// The parsed preamble: counts and the absolute ranges of every part.
#[derive(Debug, Clone)]
struct Preamble {
    /// The orders the section carries (bits of the permutation section index).
    mask: u8,
    graph_count: u64,
    quad_count: u64,
    block_graphs: u64,
    /// Absolute byte ranges, in part order.
    parts: Vec<ByteRange>,
}

/// Parse the preamble of a section at absolute `base` of length `len` from its
/// first bytes `head`. Every field is untrusted.
fn parse_preamble(head: &[u8], base: u64, len: u64, perms: PermSet) -> Result<Preamble, FileError> {
    let bad = |why| Err(FileError::Container(why));
    if head.len() < 8 || head[0..4] != QUAD_MAGIC {
        return bad("malformed quad-index section");
    }
    let mask = match head[4] {
        QUAD_VERSION if head[5] == perms.bits() => head[5],
        QUAD_VERSION => {
            return bad("quad-index order mask does not match the header permutation mask")
        }
        QUAD_VERSION_SUBSET if head[5] & 1 != 0 && head[5] & !0b11_1111 == 0 => head[5],
        QUAD_VERSION_SUBSET => return bad("malformed quad-index order mask"),
        _ => return bad("unsupported quad-index version: this file needs a newer rete"),
    };
    let mut pos = 8usize;
    let mut take = || -> Result<u64, FileError> {
        let (v, n) = read_uvarint(head.get(pos..).unwrap_or(&[]))
            .ok_or(FileError::Container("truncated quad-index preamble"))?;
        pos += n;
        Ok(v)
    };
    let graph_count = take()?;
    let quad_count = take()?;
    let block_graphs = take()?;
    let part_count = take()?;
    let n = mask.count_ones() as u64;
    if part_count != 2 + 2 * n {
        return bad("quad-index part count does not match its orders");
    }
    if block_graphs == 0 || graph_count > quad_count {
        return bad("malformed quad-index counts");
    }
    let mut lens = Vec::with_capacity(part_count as usize);
    for _ in 0..part_count {
        lens.push(take()?);
    }
    let mut at = pos as u64;
    let mut parts = Vec::with_capacity(lens.len());
    for l in lens {
        let end = at
            .checked_add(l)
            .filter(|&e| e <= len)
            .ok_or(FileError::Container("quad-index part overruns its section"))?;
        parts.push(ByteRange {
            offset: base + at,
            len: l,
        });
        at = end;
    }
    Ok(Preamble {
        mask,
        graph_count,
        quad_count,
        block_graphs,
        parts,
    })
}

/// A decoded directory block: `(graph id, quad count)` per graph.
type DirBlock = Arc<[(u32, u64)]>;

/// A decoded directory block, filled on first touch.
type BlockCell = OnceLock<DirBlock>;

/// The directory blocks decoded most recently, for a file with too many graphs
/// to keep them all: at most `cap` of them, the oldest dropped first.
///
/// It used to be the last read-ahead window alone, which is all a walk in
/// graph order needs. A join that looks up the graph of each row does not come
/// in graph order (and on several threads comes from several places at once):
/// nearly every lookup then read and decoded a block again, 68 of the 70 s of
/// a ten-million-row OPTIONAL over the nanopublications.
#[derive(Default)]
struct RecentBlocks {
    map: std::collections::HashMap<usize, DirBlock>,
    order: std::collections::VecDeque<usize>,
}

impl RecentBlocks {
    fn put(&mut self, b: usize, block: DirBlock, cap: usize) {
        if self.map.insert(b, block).is_none() {
            self.order.push_back(b);
        }
        while self.order.len() > cap.max(1) {
            if let Some(old) = self.order.pop_front() {
                self.map.remove(&old);
            }
        }
    }
}

/// A decoded graph-directory block, and the bytes of the extra ranges that were
/// read in the same batch (none when the block was resident).
type BlockAndExtra = (Arc<[(u32, u64)]>, Vec<Vec<u8>>);

/// Past this many graphs the directory blocks are not all kept (see `QuadCore::block`).
const BLOCK_MEMO_MAX_GRAPHS: u64 = 1 << 21;

/// A lazily-allocated slab of per-graph cells.
type EntrySlab = OnceLock<Box<[QuadEntry]>>;

/// One graph-directory block reference.
#[derive(Debug, Clone, Copy)]
struct BlockRef {
    first_g: u32,
    range: ByteRange,
    raw: bool,
}

/// One tile of a graph-leading order, as its directory describes it.
#[derive(Debug, Clone, Copy)]
struct QTile {
    first_g: u32,
    first_a: u32,
    last_g: u32,
    last_a: u32,
    range: ByteRange,
    raw: bool,
    syn: (u32, u32, u32, u32),
}

/// Sequential read-ahead state of one stream (an order's tiles, or the
/// directory blocks): a miss right after the previous fetch doubles the window.
#[derive(Default, Clone, Copy)]
struct Ramp {
    next: usize,
    window: usize,
}

impl Ramp {
    fn window_for(&mut self, i: usize, exhaustive: bool) -> usize {
        if exhaustive {
            self.window = READ_AHEAD_MAX;
        } else if i == self.next && self.window > 0 {
            self.window = (self.window * 2).min(READ_AHEAD_MAX);
        } else {
            self.window = 1;
        }
        self.window
    }
}

/// The shared, graph-independent state of an open quad index. Views hold an
/// `Arc` of it in their tile loaders.
struct QuadCore {
    reader: Arc<dyn RangeReader + Send + Sync>,
    section: ByteRange,
    codec: u8,
    perms: PermSet,
    read_concurrency: usize,
    pre: OnceLock<Preamble>,
    blocks_index: OnceLock<Arc<[BlockRef]>>,
    blocks: OnceLock<Box<[BlockCell]>>,
    /// The directory blocks decoded most recently, for a file with more than
    /// [`BLOCK_MEMO_MAX_GRAPHS`] graphs ([`RecentBlocks`]). Read-locked by a
    /// lookup, so lookups on several threads do not queue.
    recent: RwLock<RecentBlocks>,
    /// The graph count past which blocks are not all memoised.
    memo_max_graphs: u64,
    dirs: [OnceLock<Arc<[QTile]>>; NUM_SLOTS],
    /// Decompressed tiles, keyed `(order section index, tile)`, shared by every
    /// view: one decompression serves all the graphs a tile holds.
    tiles: ChunkCache,
    /// `[0..6)` the orders' tile streams, `[6]` the directory blocks.
    ramps: Mutex<[Ramp; NUM_SLOTS + 1]>,
    failed: AtomicBool,
    /// A `0x06` file: the preamble and block index come from the root, the
    /// orders' tile directories from leaf blocks (SPEC.md §4.4).
    v06: Option<Arc<V06Quad>>,
}

/// The `0x06` view of a quad index: everything the `0x05` preamble and `P0`
/// said, from the root, plus where each order's leaves and tiles are.
pub(crate) struct V06Quad {
    pre: Preamble,
    blocks: Vec<BlockRef>,
    /// Per section index, each leaf of that order.
    orders: [Vec<V06Leaf>; NUM_SLOTS],
    /// The decoded leaves, kept for the life of the open.
    leaf_cells: [Vec<OnceLock<Arc<[QTile]>>>; NUM_SLOTS],
    /// The orders the root declares, one bit per slot (`quad7`).
    mask: u16,
    /// A `0x07` file: a leaf lists no tile offsets (order-major).
    contiguous: bool,
    /// Absolute offset of QUAD_DATA (tile offsets in leaves are relative to it).
    data_base: u64,
    /// Codec of the leaf blocks.
    leaf_codec: u8,
    /// Decompression bounds: a quad tile, and a leaf or graph-directory block.
    pub(crate) tile_max: u64,
    pub(crate) leaf_max: u64,
    /// The class runs of a clustered order (SPOG, `0x07`), per slot.
    clusters: [Option<QCluster>; NUM_SLOTS],
    /// Mean stored bytes of one tile of each order, from the root (a cost hint).
    tile_bytes: [u64; NUM_SLOTS],
}

/// The class runs of a clustered quad order: its tiles are consecutive runs,
/// each sorted by `(a, b, c, g)`; a subject's rows are all in the run of its
/// primary class (SPEC.md section 6.6).
pub(crate) struct QCluster {
    /// Tile ranges, class ids, the last-hit hint and the placed-subject memo.
    pub(crate) runs: crate::index::ClusterRuns,
    /// The leaves of each run, as `(first leaf, end leaf)`: no leaf spans two runs.
    run_leaves: Vec<(usize, usize)>,
}

/// One leaf of an order's tile directory, as the root lists it.
#[derive(Clone, Copy)]
struct V06Leaf {
    /// Absolute range of the stored leaf.
    range: ByteRange,
    /// Tiles in the leaf.
    n: usize,
    /// Absolute-in-`QUAD_DATA` offset of the leaf's first tile.
    toff: u64,
    /// Index of the leaf's first tile in the whole order.
    first_tile: usize,
    /// Graph of the first tile's first row and of the last tile's last row.
    first_g: u32,
    last_g: u32,
}

impl V06Quad {
    /// From the decoded root: `leaves_base` / `data_base` are the absolute
    /// offsets of QUAD_LEAVES and QUAD_DATA.
    pub(crate) fn new(
        root: &crate::v06::QuadRoot,
        leaves_base: u64,
        data_base: u64,
        leaf_codec: u8,
        contiguous: bool,
    ) -> Result<Self, FileError> {
        let mut pos = 0usize;
        let b = &root.p0;
        let mut take = || -> Option<u64> {
            let (v, n) = read_uvarint(b.get(pos..)?)?;
            pos += n;
            Some(v)
        };
        let num = take().ok_or(FileError::Container("0x06 quad P0 truncated"))?;
        if num != root.graph_count.div_ceil(root.block_graphs.max(1)) {
            return Err(FileError::Container("0x06 quad P0 block count mismatch"));
        }
        let mut blocks = Vec::with_capacity((num as usize).min(b.len()));
        let mut first_g = 0u32;
        let mut at = 0u64;
        for i in 0..num {
            let d = take().and_then(|d| u32::try_from(d).ok());
            let packed = take();
            let (Some(d), Some(packed)) = (d, packed) else {
                return Err(FileError::Container("0x06 quad P0 truncated"));
            };
            if i > 0 && d == 0 {
                return Err(FileError::Container("0x06 quad blocks do not ascend"));
            }
            first_g = first_g
                .checked_add(d)
                .ok_or(FileError::Container("0x06 quad P0 overflow"))?;
            let clen = packed >> 1;
            let end = at
                .checked_add(clen)
                .filter(|&e| e <= root.gdir_len)
                .ok_or(FileError::Container("0x06 quad block overruns"))?;
            blocks.push(BlockRef {
                first_g,
                range: ByteRange {
                    offset: leaves_base + at,
                    len: clen,
                },
                raw: packed & 1 == 1,
            });
            at = end;
        }
        let mut orders: [Vec<V06Leaf>; NUM_SLOTS] = Default::default();
        let mut leaf_cells: [Vec<OnceLock<Arc<[QTile]>>>; NUM_SLOTS] = Default::default();
        let mut mask = 0u16;
        for o in &root.orders {
            mask |= 1 << o.si;
            orders[o.si] = o
                .leaves
                .iter()
                .map(|(l, first, last, toff)| V06Leaf {
                    range: ByteRange {
                        offset: leaves_base + l.off,
                        len: l.len,
                    },
                    n: l.n,
                    toff: *toff,
                    first_tile: l.first,
                    first_g: first.0,
                    last_g: last.0,
                })
                .collect();
            leaf_cells[o.si] = (0..o.leaves.len()).map(|_| OnceLock::new()).collect();
        }
        // Mean stored tile of each order: the span from its first leaf's first tile
        // to its last leaf's first, over the tiles between them (order-major).
        let mut tile_bytes = [48u64 << 10; NUM_SLOTS];
        for o in &root.orders {
            if let (Some(first), Some(last)) = (o.leaves.first(), o.leaves.last()) {
                if last.0.first > 0 && last.3 > first.3 {
                    tile_bytes[o.si] = ((last.3 - first.3) / last.0.first as u64).max(1);
                }
            }
        }
        Ok(V06Quad {
            pre: Preamble {
                mask: 0,
                graph_count: root.graph_count,
                quad_count: root.quad_count,
                block_graphs: root.block_graphs.max(1),
                parts: Vec::new(),
            },
            blocks,
            orders,
            leaf_cells,
            mask,
            contiguous,
            data_base,
            leaf_codec,
            tile_max: u64::MAX,
            leaf_max: u64::MAX,
            clusters: Default::default(),
            tile_bytes,
        })
    }

    /// Mark the quad orders the cluster root lists as clustered: every run is
    /// whole leaves and the runs cover the order's tiles.
    pub(crate) fn with_clusters(
        mut self,
        orders: &[crate::v06::ClusterOrder],
    ) -> Result<Self, FileError> {
        let bad = |w: &'static str| FileError::Container(w);
        for c in orders.iter().filter(|c| c.si >= quad7::FIRST_LAST_SLOT) {
            let leaves = self
                .orders
                .get(c.si)
                .filter(|l| !l.is_empty())
                .ok_or(bad("0x07 cluster root names a quad order the file lacks"))?;
            let total: usize = leaves.iter().map(|l| l.n).sum();
            if c.run_tiles.iter().sum::<usize>() != total {
                return Err(bad("0x07 cluster runs do not cover the quad tiles"));
            }
            let mut run_leaves = Vec::with_capacity(c.run_tiles.len());
            let mut at = 0usize;
            for &n in &c.run_tiles {
                let l0 = leaves.partition_point(|l| l.first_tile < at);
                let l1 = leaves.partition_point(|l| l.first_tile < at + n);
                // A leaf holds the tiles of one run.
                if leaves[l0..l1]
                    .last()
                    .is_some_and(|l| l.first_tile + l.n > at + n)
                {
                    return Err(bad("0x07 a quad directory leaf spans two cluster runs"));
                }
                run_leaves.push((l0, l1));
                at += n;
            }
            self.clusters[c.si] = Some(QCluster {
                runs: crate::index::ClusterRuns::new(c.classes.clone(), &c.run_tiles),
                run_leaves,
            });
        }
        Ok(self)
    }
}

impl QuadCore {
    fn fail(&self) {
        self.failed.store(true, Ordering::Relaxed);
    }

    /// The scan of `pat` over the order in slot `slot` (see [`QuadNamed::scan`]).
    fn scan_slot(
        self: &Arc<Self>,
        pat: (Option<u32>, Option<u32>, Option<u32>),
        slot: usize,
    ) -> Option<QuadScan> {
        let perm = quad7::perm_of(slot);
        let last = quad7::is_last(slot);
        let abc = perm.order_pattern(pat);
        let (dir, base) = match abc[0] {
            Some(a) if last && self.is_clustered(slot) => {
                // Subject `a` is in the one run of its class.
                match self.resolve_run(slot, a)? {
                    Some(run) => self.dir_in_run(slot, run, a)?,
                    None => (Arc::from(Vec::new()), 0),
                }
            }
            Some(a) if last => self.dir_for_graph(slot, a)?,
            _ => (self.dir(slot)?, 0),
        };
        let (next_tile, end_tile) = if last {
            // The tiles whose `(a, b)` key range can hold the bound prefix.
            let (lo, hi) = match (abc[0], abc[1]) {
                (Some(a), Some(b)) => ((a, b), (a, b)),
                (Some(a), None) => ((a, 0), (a, u32::MAX)),
                _ => ((0, 0), (u32::MAX, u32::MAX)),
            };
            let from = dir.partition_point(|t| (t.last_g, t.last_a) < lo);
            let to = dir.partition_point(|t| (t.first_g, t.first_a) <= hi);
            (base + from, base + to.max(from))
        } else {
            (base, base + dir.len())
        };
        Some(QuadScan {
            core: Arc::clone(self),
            dir,
            base,
            perm,
            si: slot,
            last,
            abc,
            cols: subject_columns(perm),
            next_tile,
            end_tile,
            ahead: 0,
            buf: Vec::new().into_iter(),
        })
    }

    fn pre(&self) -> Option<&Preamble> {
        if let Some(v) = &self.v06 {
            return Some(&v.pre);
        }
        if let Some(p) = self.pre.get() {
            return Some(p);
        }
        let head_len = self.section.len.min(PREAMBLE_MAX);
        let parsed = self
            .reader
            .read_at(self.section.offset, head_len)
            .map_err(FileError::Io)
            .and_then(|h| parse_preamble(&h, self.section.offset, self.section.len, self.perms));
        match parsed {
            Ok(p) => {
                let _ = self.pre.set(p);
                self.pre.get()
            }
            Err(_) => {
                self.fail();
                None
            }
        }
    }

    fn read_part(&self, k: usize) -> Option<Vec<u8>> {
        let r = *self.pre()?.parts.get(k)?;
        match self.reader.read_at(r.offset, r.len) {
            Ok(b) => Some(b),
            Err(_) => {
                self.fail();
                None
            }
        }
    }

    /// The orders this index carries, one bit per slot (`quad7`).
    fn mask(&self) -> u16 {
        match &self.v06 {
            Some(v) => v.mask,
            None => self.pre().map_or(self.perms.bits(), |p| p.mask) as u16,
        }
    }

    fn blocks_index(&self) -> Option<&Arc<[BlockRef]>> {
        if let Some(b) = self.blocks_index.get() {
            return Some(b);
        }
        if let Some(v) = &self.v06 {
            let n = v.blocks.len();
            // The cells first: a thread that finds the index set takes the
            // cells for granted (see below).
            let _ = self
                .blocks
                .set((0..n).map(|_| OnceLock::new()).collect::<Vec<_>>().into());
            let _ = self.blocks_index.set(Arc::from(v.blocks.clone()));
            return self.blocks_index.get();
        }
        let pre = self.pre()?.clone();
        let bytes = self.read_part(0)?;
        let blocks_part = pre.parts[1 + pre.mask.count_ones() as usize];
        let parsed = (|| -> Option<Vec<BlockRef>> {
            let mut pos = 0usize;
            let mut take = || -> Option<u64> {
                let (v, n) = read_uvarint(bytes.get(pos..)?)?;
                pos += n;
                Some(v)
            };
            let num = take()?;
            if num != pre.graph_count.div_ceil(pre.block_graphs) {
                return None;
            }
            let mut out = Vec::with_capacity((num as usize).min(bytes.len()));
            let mut first_g = 0u32;
            let mut at = 0u64;
            for i in 0..num {
                let d = u32::try_from(take()?).ok()?;
                if i > 0 && d == 0 {
                    return None; // blocks ascend strictly
                }
                first_g = first_g.checked_add(d)?;
                let packed = take()?;
                let clen = packed >> 1;
                let end = at.checked_add(clen).filter(|&e| e <= blocks_part.len)?;
                out.push(BlockRef {
                    first_g,
                    range: ByteRange {
                        offset: blocks_part.offset + at,
                        len: clen,
                    },
                    raw: packed & 1 == 1,
                });
                at = end;
            }
            Some(out)
        })();
        match parsed {
            Some(v) => {
                let n = v.len();
                // The cells before the index. Every reader asks for the index
                // and then for the cells; with the index set first, a second
                // thread arriving between the two found no cells, took that
                // for a failed read without recording one, and skipped its
                // graph: a count over every graph came out a few dozen short
                // once in a while on several threads.
                let _ = self
                    .blocks
                    .set((0..n).map(|_| OnceLock::new()).collect::<Vec<_>>().into());
                let _ = self.blocks_index.set(Arc::from(v));
                self.blocks_index.get()
            }
            None => {
                self.fail();
                None
            }
        }
    }

    fn decode_block(
        &self,
        b: usize,
        r: &BlockRef,
        stored: &[u8],
        graph_count: u64,
        block_graphs: u64,
    ) -> Option<Arc<[(u32, u64)]>> {
        let body = if r.raw {
            stored.to_vec()
        } else {
            let max = self.v06.as_ref().map_or(u64::MAX, |v| v.leaf_max);
            crate::file::decompress_bounded(self.codec, stored, max).ok()?
        };
        let start = (b as u64).checked_mul(block_graphs)?;
        let n = graph_count.checked_sub(start)?.min(block_graphs) as usize;
        let mut out = Vec::with_capacity(n.min(body.len()));
        let mut pos = 0usize;
        let mut g = r.first_g;
        for i in 0..n {
            let (d, k) = read_uvarint(body.get(pos..)?)?;
            pos += k;
            if i > 0 && d == 0 {
                return None;
            }
            g = g.checked_add(u32::try_from(d).ok()?)?;
            let (c, k) = read_uvarint(body.get(pos..)?)?;
            pos += k;
            out.push((g, c));
        }
        Some(Arc::from(out))
    }

    /// Directory block `b` (decoded), with read-ahead over the blocks after it.
    ///
    /// Blocks are memoised for the life of the open, 16 bytes per graph, up to
    /// [`BLOCK_MEMO_MAX_GRAPHS`] graphs. Past that a walk over every graph
    /// would hold a directory proportional to the file (690 MB at 43 M graphs),
    /// so the blocks are kept only as the last read-ahead window and a block
    /// outside it is read again.
    fn block(&self, b: usize, exhaustive: bool) -> Option<Arc<[(u32, u64)]>> {
        self.block_with(b, exhaustive, &[]).map(|(v, _)| v)
    }

    /// [`block`](Self::block), and when the block has to be read, the ranges
    /// `extra` in the same batch (one round trip for both): their bytes come
    /// back in order, or none when the block was resident.
    fn block_with(
        &self,
        b: usize,
        exhaustive: bool,
        extra: &[(u64, u64)],
    ) -> Option<BlockAndExtra> {
        let index = self.blocks_index()?.clone();
        let cells = self.blocks.get()?;
        let pre = self.pre()?.clone();
        let bounded = pre.graph_count > self.memo_max_graphs;
        if bounded {
            if let Some(v) = self.recent.read().unwrap().map.get(&b) {
                return Some((v.clone(), Vec::new()));
            }
        } else if let Some(v) = cells.get(b)?.get() {
            return Some((v.clone(), Vec::new()));
        }
        let w = {
            let mut ramps = self.ramps.lock().unwrap();
            let w = ramps[NUM_SLOTS].window_for(b, exhaustive);
            let end = (b + w).min(index.len());
            ramps[NUM_SLOTS].next = end;
            end - b
        };
        let end = b + w;
        let span_start = index[b].range.offset;
        let span_end = index[end - 1].range.end();
        let (span, extra_bytes) = if extra.is_empty() {
            match self.reader.read_at(span_start, span_end - span_start) {
                Ok(s) => (s, Vec::new()),
                Err(_) => {
                    self.fail();
                    return None;
                }
            }
        } else {
            let mut ranges = vec![(span_start, span_end - span_start)];
            ranges.extend_from_slice(extra);
            match self.reader.read_many(&ranges) {
                Ok(mut blobs) if blobs.len() == ranges.len() => {
                    let span = blobs.remove(0);
                    (span, blobs)
                }
                _ => {
                    self.fail();
                    return None;
                }
            }
        };
        let mut window: Vec<(usize, DirBlock)> = Vec::new();
        for (i, r) in index.iter().enumerate().take(end).skip(b) {
            if !bounded && cells[i].get().is_some() {
                continue;
            }
            let lo = (r.range.offset - span_start) as usize;
            let stored = span.get(lo..lo + r.range.len as usize)?;
            match self.decode_block(i, r, stored, pre.graph_count, pre.block_graphs) {
                Some(v) if bounded => window.push((i, v)),
                Some(v) => {
                    let _ = cells[i].set(v);
                }
                None => {
                    self.fail();
                    return None;
                }
            }
        }
        if bounded {
            let first = window.first().map(|(_, v)| v.clone());
            // As many blocks as a file under the threshold keeps in all, and
            // never fewer than one read-ahead window.
            let cap =
                ((self.memo_max_graphs / pre.block_graphs.max(1)) as usize).max(READ_AHEAD_MAX);
            let mut recent = self.recent.write().unwrap();
            for (i, v) in window {
                recent.put(i, v, cap);
            }
            return first.map(|v| (v, extra_bytes));
        }
        cells[b].get().cloned().map(|v| (v, extra_bytes))
    }

    /// The graph at ordinal `i`: `(graph id, quad count)`.
    fn graph_at(&self, i: usize, exhaustive: bool) -> Option<(u32, u64)> {
        let bg = self.pre()?.block_graphs as usize;
        let block = self.block(i / bg, exhaustive)?;
        block.get(i % bg).copied()
    }

    /// The ordinal of graph id `g`, or `None` when the file has no such graph.
    fn ordinal_of(&self, g: u32) -> Option<usize> {
        self.ordinal_of_with(g, &[]).map(|(i, _)| i)
    }

    /// [`ordinal_of`](Self::ordinal_of), with `extra` ranges read in the same
    /// batch as the directory block when that has to be read (see
    /// [`block_with`](Self::block_with)).
    fn ordinal_of_with(&self, g: u32, extra: &[(u64, u64)]) -> Option<(usize, Vec<Vec<u8>>)> {
        let index = self.blocks_index()?.clone();
        let bi = index.partition_point(|r| r.first_g <= g);
        if bi == 0 {
            return None;
        }
        let (block, bytes) = self.block_with(bi - 1, false, extra)?;
        let pos = block.binary_search_by_key(&g, |&(id, _)| id).ok()?;
        Some(((bi - 1) * self.pre()?.block_graphs as usize + pos, bytes))
    }

    /// [`ordinal_of`](Self::ordinal_of) for a graph about to be viewed. Neither
    /// the graph's directory block nor the leaf of a tile directory that holds
    /// it depends on the other (the leaf is routed by the graph id, which the
    /// caller has), so a `0x06` file with a leafed directory reads both in one
    /// round trip, where it read the block and then the leaf. The leaf is the
    /// first order's, the one a scan that binds the subject or nothing takes;
    /// a view that takes another order reads its own leaf as before, and has
    /// read one small leaf too many.
    fn ordinal_of_for_view(&self, g: u32) -> Option<usize> {
        let (Some(v), Some(si)) = (
            &self.v06,
            self.perms.iter().next().map(|p| p.section_index()),
        ) else {
            return self.ordinal_of(g);
        };
        let leaves = &v.orders[si];
        if leaves.len() <= 1 || self.dirs[si].get().is_some() {
            return self.ordinal_of(g);
        }
        let lo = leaves.partition_point(|l| l.last_g < g);
        let hi = leaves.partition_point(|l| l.first_g <= g);
        let missing: Vec<usize> = (lo..hi)
            .filter(|&li| v.leaf_cells[si][li].get().is_none())
            .collect();
        if missing.is_empty() {
            return self.ordinal_of(g);
        }
        let ranges: Vec<(u64, u64)> = missing
            .iter()
            .map(|&li| (leaves[li].range.offset, leaves[li].range.len))
            .collect();
        let (ordinal, blobs) = self.ordinal_of_with(g, &ranges)?;
        if blobs.len() == missing.len() {
            // A leaf that does not decode is recorded as a failed read, the
            // same as when the view asks for it.
            let _ = self.install_leaves(v, si, &missing, blobs);
        }
        Some(ordinal)
    }

    /// The tile directory of the order in section slot `si`. A view needs
    /// every order's directory, and they are adjacent parts, so the first miss
    /// reads all the missing ones in one request when together they are small
    /// ([`DIRS_TOGETHER_MAX`]); a larger file reads each on its own.
    fn dir(&self, si: usize) -> Option<Arc<[QTile]>> {
        if let Some(d) = self.dirs[si].get() {
            return Some(d.clone());
        }
        if let Some(v) = &self.v06 {
            return self.dir_v06(v, si);
        }
        let pre = self.pre()?.clone();
        let n = pre.mask.count_ones() as usize;
        let first = pre.parts[1];
        let last = pre.parts[n];
        let together = last.end() - first.offset <= DIRS_TOGETHER_MAX;
        let want: Vec<IndexPermutation> = if together {
            ALL_PERMS
                .into_iter()
                .filter(|p| pre.mask & (1 << p.section_index()) != 0)
                .filter(|p| self.dirs[p.section_index()].get().is_none())
                .collect()
        } else {
            vec![ALL_PERMS[si]]
        };
        let span = ByteRange {
            offset: if together {
                first.offset
            } else {
                pre.parts[1 + rank_in(pre.mask, want[0])?].offset
            },
            len: if together {
                last.end() - first.offset
            } else {
                pre.parts[1 + rank_in(pre.mask, want[0])?].len
            },
        };
        let bytes = match self.reader.read_at(span.offset, span.len) {
            Ok(b) => b,
            Err(_) => {
                self.fail();
                return None;
            }
        };
        for perm in want {
            let k = rank_in(pre.mask, perm)?;
            let part = pre.parts[1 + k];
            let lo = (part.offset - span.offset) as usize;
            let parsed = bytes
                .get(lo..lo + part.len as usize)
                .and_then(|b| parse_tile_dir(b, pre.parts[2 + n + k]));
            match parsed {
                Some(v) => {
                    let _ = self.dirs[perm.section_index()].set(Arc::from(v));
                }
                None => {
                    self.fail();
                    return None;
                }
            }
        }
        self.dirs[si].get().cloned()
    }

    /// Fault the leaves `lis` of a `0x06` order's tile directory that are not
    /// resident, in one batch, decoded and kept.
    fn fault_leaves(&self, v: &V06Quad, si: usize, lis: &[usize]) -> Option<()> {
        let missing: Vec<usize> = lis
            .iter()
            .copied()
            .filter(|&li| v.leaf_cells[si][li].get().is_none())
            .collect();
        if missing.is_empty() {
            return Some(());
        }
        let ranges: Vec<(u64, u64)> = missing
            .iter()
            .map(|&li| (v.orders[si][li].range.offset, v.orders[si][li].range.len))
            .collect();
        let blobs = match self.reader.read_many(&ranges) {
            Ok(b) if b.len() == ranges.len() => b,
            _ => {
                self.fail();
                return None;
            }
        };
        self.install_leaves(v, si, &missing, blobs)
    }

    /// Decode the stored leaves `blobs` of order `si` (`missing[k]` is the
    /// leaf of `blobs[k]`) and keep them.
    fn install_leaves(
        &self,
        v: &V06Quad,
        si: usize,
        missing: &[usize],
        blobs: Vec<Vec<u8>>,
    ) -> Option<()> {
        for (&li, stored) in missing.iter().zip(blobs) {
            let leaf = &v.orders[si][li];
            let parsed = crate::file::decompress_bounded(v.leaf_codec, &stored, v.leaf_max)
                .ok()
                .and_then(|raw| {
                    crate::v06::decode_qtile_leaf(&raw, leaf.n, leaf.toff, v.contiguous).ok()
                });
            let Some(ents) = parsed else {
                self.fail();
                return None;
            };
            let tiles: Vec<QTile> = ents
                .into_iter()
                .map(|e| QTile {
                    first_g: e.first.0,
                    first_a: e.first.1,
                    last_g: e.last.0,
                    last_a: e.last.1,
                    range: ByteRange {
                        offset: v.data_base + e.off,
                        len: e.clen,
                    },
                    raw: e.raw,
                    syn: e.syn,
                })
                .collect();
            let _ = v.leaf_cells[si][li].set(Arc::from(tiles));
        }
        Some(())
    }

    /// A `0x06` order's whole directory: every leaf read in one batch (adjacent,
    /// so usually one request), decoded and kept.
    fn dir_v06(&self, v: &V06Quad, si: usize) -> Option<Arc<[QTile]>> {
        let all: Vec<usize> = (0..v.orders[si].len()).collect();
        self.fault_leaves(v, si, &all)?;
        let mut out = Vec::new();
        for cell in &v.leaf_cells[si] {
            out.extend_from_slice(cell.get()?);
        }
        let _ = self.dirs[si].set(Arc::from(out));
        self.dirs[si].get().cloned()
    }

    /// The tiles of order `si` that can hold graph `g`, as `(tiles, index of
    /// the first one in the whole order)`: a slice of the directory, not
    /// necessarily only those tiles. A `0x06` order whose directory is in
    /// several leaves reads the leaves whose graph range holds `g` (the root
    /// lists each leaf's range), one leaf for a graph inside one; one leaf, or a
    /// directory already resident, is the whole directory.
    fn dir_for_graph(&self, si: usize, g: u32) -> Option<(Arc<[QTile]>, usize)> {
        if let Some(d) = self.dirs[si].get() {
            return Some((d.clone(), 0));
        }
        let Some(v) = &self.v06 else {
            return Some((self.dir(si)?, 0));
        };
        let leaves = &v.orders[si];
        if leaves.len() <= 1 {
            return Some((self.dir(si)?, 0));
        }
        let lo = leaves.partition_point(|l| l.last_g < g);
        let hi = leaves.partition_point(|l| l.first_g <= g);
        if lo >= hi {
            return Some((Arc::from(Vec::new()), 0));
        }
        let lis: Vec<usize> = (lo..hi).collect();
        self.fault_leaves(v, si, &lis)?;
        if lis.len() == 1 {
            return Some((v.leaf_cells[si][lo].get()?.clone(), leaves[lo].first_tile));
        }
        let mut out = Vec::new();
        for &li in &lis {
            out.extend_from_slice(v.leaf_cells[si][li].get()?);
        }
        Some((Arc::from(out), leaves[lo].first_tile))
    }

    fn unpack(&self, t: &QTile, stored: &[u8]) -> Option<Arc<[u8]>> {
        if t.raw {
            Some(Arc::from(stored))
        } else {
            let max = self.v06.as_ref().map_or(u64::MAX, |v| v.tile_max);
            crate::file::decompress_bounded(self.codec, stored, max)
                .ok()
                .map(Arc::from)
        }
    }

    /// Fault the tiles `want` (ascending) of order slot `si` into the shared
    /// cache, coalescing adjacent ones into single reads.
    ///
    /// `dir` may be a slice of the order's directory starting at tile `base`;
    /// `want` and the cache keys are tile indices of the whole order.
    fn fault(&self, si: usize, dir: &[QTile], base: usize, want: &[usize]) -> Option<()> {
        let missing: Vec<usize> = want
            .iter()
            .copied()
            .filter(|&ti| !self.tiles.contains((si as u8, ti as u32)))
            .collect();
        if missing.is_empty() {
            return Some(());
        }
        let tiles: Vec<(usize, QTile)> = missing
            .iter()
            .map(|&ti| Some((ti, *dir.get(ti.checked_sub(base)?)?)))
            .collect::<Option<_>>()?;
        self.fault_tiles(si, &tiles)
    }

    /// Fault the tiles `tiles` (`(index in the order, entry)`, ascending by
    /// offset) of order slot `si` into the shared cache, coalescing adjacent
    /// ones into single reads. The tiles may come from several places of the
    /// directory (the runs of a clustered order): one batch whatever they are.
    fn fault_tiles(&self, si: usize, tiles: &[(usize, QTile)]) -> Option<()> {
        self.fault_tiles_with(si, tiles, false)
    }

    /// [`Self::fault_tiles`]; `scattered` for the candidate tiles of a subject
    /// probe, which lie far apart: the reader then gets the exact ranges
    /// ([`RangeReader::read_many_scattered`]), not blocks rounded out around
    /// them.
    fn fault_tiles_with(&self, si: usize, tiles: &[(usize, QTile)], scattered: bool) -> Option<()> {
        let mut spans: Vec<(u64, u64)> = Vec::new();
        let mut members: Vec<Vec<(usize, QTile)>> = Vec::new();
        for &(ti, t) in tiles {
            let r = t.range;
            match spans.last_mut() {
                Some(last) if last.0 + last.1 == r.offset => {
                    last.1 += r.len;
                    members.last_mut()?.push((ti, t));
                }
                _ => {
                    spans.push((r.offset, r.len));
                    members.push(vec![(ti, t)]);
                }
            }
        }
        let got = if scattered {
            self.reader.read_many_scattered(&spans)
        } else {
            self.reader.read_many(&spans)
        };
        let blobs = match got {
            Ok(b) if b.len() == spans.len() => b,
            _ => {
                self.fail();
                return None;
            }
        };
        for ((start, _), (blob, tis)) in spans.iter().zip(blobs.iter().zip(&members)) {
            for (ti, t) in tis {
                let lo = (t.range.offset - start) as usize;
                let stored = blob.get(lo..lo + t.range.len as usize)?;
                match self.unpack(t, stored) {
                    Some(body) => {
                        self.tiles.insert((si as u8, *ti as u32), body);
                    }
                    None => {
                        self.fail();
                        return None;
                    }
                }
            }
        }
        Some(())
    }

    /// Tile `ti` of order slot `si`, decompressed, faulting it (and, when the
    /// access is sequential, the tiles after it) on a miss.
    fn tile(&self, si: usize, dir: &[QTile], base: usize, ti: usize) -> Option<Arc<CacheEntry>> {
        self.tile_capped(si, dir, base, ti, usize::MAX)
    }

    /// Graph `g`'s segment of tile `ti` of graph-leading order `si` (already
    /// in hand as `entry`), through the tile's segment index: built on the
    /// first lookup, kept and evicted with the tile. See [`segment_of`].
    fn segment<'e>(
        &self,
        si: usize,
        ti: usize,
        entry: &'e Arc<CacheEntry>,
        first_g: u32,
        g: u32,
    ) -> Option<Option<(u32, &'e [u8])>> {
        let (segs, built) = entry.segments(|tile| segment_index(tile, first_g));
        let segs = segs?;
        if built {
            let bytes = std::mem::size_of_val(segs) as u64;
            self.tiles.charge_extra((si as u8, ti as u32), entry, bytes);
        }
        segment_of(entry.body(), segs, g)
    }

    /// [`tile`](Self::tile) whose read-ahead stops before tile `cap` (a scan that
    /// knows where its range ends does not read past it).
    fn tile_capped(
        &self,
        si: usize,
        dir: &[QTile],
        base: usize,
        ti: usize,
        cap: usize,
    ) -> Option<Arc<CacheEntry>> {
        if let Some(e) = self.tiles.get((si as u8, ti as u32)) {
            return Some(e);
        }
        let end = {
            let mut ramps = self.ramps.lock().unwrap();
            let w = ramps[si].window_for(ti, false);
            let end = (ti + w).min(base + dir.len()).min(cap.max(ti + 1));
            ramps[si].next = end;
            end
        };
        let want: Vec<usize> = (ti..end).collect();
        self.fault(si, dir, base, &want)?;
        // Inserted a moment ago; a cache cap smaller than one tile can have
        // evicted it already, in which case fetch it alone.
        if let Some(e) = self.tiles.get((si as u8, ti as u32)) {
            return Some(e);
        }
        let t = &dir[ti - base];
        let stored = match self.reader.read_at(t.range.offset, t.range.len) {
            Ok(b) => b,
            Err(_) => {
                self.fail();
                return None;
            }
        };
        let body = self.unpack(t, &stored)?;
        Some(self.tiles.insert((si as u8, ti as u32), body))
    }

    /// The ids of the graphs holding at least one quad whose subject is in
    /// `subjects`, ascending: one sequential pass over the `G+SPO` tiles (the
    /// subject is the column after the graph there), in read-ahead windows of
    /// [`READ_AHEAD_MAX`] tiles. A segment whose first subject is wanted
    /// answers without decoding its body. Tiles already in the shared cache
    /// are used as they are; the others are decoded and dropped, so the pass
    /// does not flood the cache. `None` on a failed read or a malformed tile
    /// (the failure is recorded, as for every lazy read).
    fn graphs_with_subjects(&self, subjects: &std::collections::BTreeSet<u32>) -> Option<Vec<u32>> {
        let perm = IndexPermutation::Spo;
        if self.mask() & 1 == 0 {
            return None;
        }
        let si = perm.section_index();
        let dir = self.dir(si)?;
        let cols = subject_columns(perm);
        let mut out: Vec<u32> = Vec::new();
        let mut rows: Vec<Triple> = Vec::new();
        let mut scan = |t: &QTile, body: &[u8]| -> Option<()> {
            let mut ok = true;
            walk_segments(body, t.first_g, |g, first_a, seg| {
                // A graph cut across tiles opens one segment in each.
                if out.last() == Some(&g) {
                    return true;
                }
                if subjects.contains(&first_a) {
                    out.push(g);
                    return true;
                }
                rows.clear();
                ok = decode_segment_body(seg, first_a, cols, &mut rows).is_some();
                if ok && rows.iter().any(|(a, _, _)| subjects.contains(a)) {
                    out.push(g);
                }
                ok
            })?;
            ok.then_some(())
        };
        let mut ti = 0;
        while ti < dir.len() {
            let end = (ti + READ_AHEAD_MAX).min(dir.len());
            let mut spans: Vec<(u64, u64)> = Vec::new();
            let mut members: Vec<Vec<usize>> = Vec::new();
            let mut cached: Vec<Option<Arc<CacheEntry>>> = Vec::with_capacity(end - ti);
            for (k, t) in dir[ti..end].iter().enumerate() {
                let hit = self.tiles.get((si as u8, (ti + k) as u32));
                if hit.is_none() {
                    match spans.last_mut() {
                        Some(last) if last.0 + last.1 == t.range.offset => {
                            last.1 += t.range.len;
                            members.last_mut()?.push(ti + k);
                        }
                        _ => {
                            spans.push((t.range.offset, t.range.len));
                            members.push(vec![ti + k]);
                        }
                    }
                }
                cached.push(hit);
            }
            let mut bodies: Vec<Option<Arc<[u8]>>> = vec![None; end - ti];
            if !spans.is_empty() {
                let blobs = match self.reader.read_many(&spans) {
                    Ok(b) if b.len() == spans.len() => b,
                    _ => {
                        self.fail();
                        return None;
                    }
                };
                for ((start, _), (blob, tis)) in spans.iter().zip(blobs.iter().zip(&members)) {
                    for &k in tis {
                        let t = &dir[k];
                        let lo = (t.range.offset - start) as usize;
                        let body = blob
                            .get(lo..lo + t.range.len as usize)
                            .and_then(|stored| self.unpack(t, stored));
                        match body {
                            Some(b) => bodies[k - ti] = Some(b),
                            None => {
                                self.fail();
                                return None;
                            }
                        }
                    }
                }
            }
            for k in ti..end {
                let r = match (&cached[k - ti], &bodies[k - ti]) {
                    (Some(e), _) => scan(&dir[k], e.body()),
                    (None, Some(b)) => scan(&dir[k], b),
                    (None, None) => None,
                };
                if r.is_none() {
                    self.fail();
                    return None;
                }
            }
            ti = end;
        }
        Some(out)
    }

    /// A view of graph `g`: a remote-style [`GraphIndex`] over its slice of
    /// every order's tiles. Reads no tile, and no tile directory until an order
    /// is used: each order's slice is built on first use (an `0x06` order's
    /// directory is one leaf of about a megabyte at 40 M graphs, so a lookup
    /// that routes to one order reads one, not six).
    ///
    /// A `0x07` file stores one graph-leading order, GSPO, so the view's other
    /// orders come from somewhere else ([`ViewSrc`]): a graph of at most
    /// [`crate::write_opts::quad_view_synth_max`] quads has them built from its GSPO slice (one tile
    /// per order, made on first use); a bigger one reads POS and OSP out of the
    /// graph-last POSG and OSPG tiles, keeping the rows of the graph, so a
    /// lookup on a predicate or an object costs that term's tiles and not the
    /// whole graph.
    fn view(self: &Arc<Self>, g: u32, quads: u64, tile_cap: u64) -> Option<GraphIndex> {
        let mask = self.mask();
        let big = quads > crate::write_opts::quad_view_synth_max();
        // The orders of the view that the file has no graph-leading tiles for.
        let lacks = ALL_PERMS
            .iter()
            .any(|p| self.perms.contains(*p) && mask & (1 << p.section_index()) == 0);
        let mut src: [ViewSrc; NUM_PERMS] = [ViewSrc::Slice; NUM_PERMS];
        let mut view_perms = self.perms;
        if lacks {
            // A `0x07` file (or a build's image): GSPO is the one graph-leading
            // order.
            if big {
                view_perms = PermSet::CORE;
            }
            for perm in ALL_PERMS {
                let si = perm.section_index();
                if mask & (1 << si) != 0 {
                    continue;
                }
                let last = quad7::last_slot(perm);
                // A clustered SPOG is sorted by subject only within a run: a view
                // cannot take its tiles as one ascending list.
                src[si] = if big && si < 3 && mask & (1 << last) != 0 && !self.is_clustered(last) {
                    ViewSrc::Filter(last)
                } else {
                    ViewSrc::Synth
                };
            }
        }
        let st = Arc::new(ViewState {
            core: Arc::clone(self),
            g,
            src,
            slices: Default::default(),
            rows: OnceLock::new(),
        });
        let mut lists: [Option<Arc<DeferredTiles>>; NUM_PERMS] = Default::default();
        for perm in view_perms.iter() {
            let si = perm.section_index();
            let st = Arc::clone(&st);
            // Without the directory, the mean tile (64 KiB budget) per quad is
            // all the planner can assume; it is only a cost hint.
            let approx = quads.saturating_mul(4);
            lists[si] = Some(Arc::new(DeferredTiles::new(
                approx,
                Box::new(move || st.tiles(si)),
            )));
        }
        let loader: crate::index::TileLoader = {
            let st = Arc::clone(&st);
            Box::new(move |si, ti| {
                let b = st.block(si, ti);
                if b.is_none() {
                    st.core.fail();
                }
                b
            })
        };
        let bulk: crate::index::TileBulkLoader = {
            let st = Arc::clone(&st);
            Box::new(move |si, tis| st.blocks(si, tis))
        };
        let mut index =
            GraphIndex::from_remote_deferred(lists, view_perms, loader).with_bulk_loader(bulk);
        index.set_size_hint(quads);
        index.set_read_concurrency(self.read_concurrency);
        if tile_cap != u64::MAX {
            index.set_cache_cap(tile_cap);
        }
        Some(index)
    }
}

/// Where one order of a graph's view gets its tiles.
#[derive(Clone, Copy)]
enum ViewSrc {
    /// The graph's slice of the file's own `G+X` tiles.
    Slice,
    /// Built from the graph's GSPO slice: one tile.
    Synth,
    /// The tiles of this graph-last order (slot) that may hold the graph,
    /// reduced to its rows.
    Filter(usize),
}

/// The tiles of one order that a view holds: the directory, the index of its
/// first entry in the whole order, and the physical index of each view tile.
type Slice = (Arc<[QTile]>, usize, Vec<usize>);

/// The cell of `slices` that holds the graph's GSPO slice for the orders that
/// are built from it.
const GSPO_CELL: usize = NUM_PERMS;

/// The shared state behind one view's loaders.
struct ViewState {
    core: Arc<QuadCore>,
    g: u32,
    src: [ViewSrc; NUM_PERMS],
    slices: [OnceLock<Slice>; NUM_PERMS + 1],
    /// The graph's rows `(s, p, o)`, for [`ViewSrc::Synth`].
    rows: OnceLock<Option<Arc<Vec<Triple>>>>,
}

impl ViewState {
    /// The graph's slice of graph-leading order `slot`, kept in `cell`.
    fn graph_slice(&self, slot: usize, cell: usize) -> Option<&Slice> {
        if let Some(s) = self.slices[cell].get() {
            return Some(s);
        }
        let (dir, base) = self.core.dir_for_graph(slot, self.g)?;
        let g = self.g;
        let lo = dir.partition_point(|t| t.last_g < g);
        let hi = dir.partition_point(|t| t.first_g <= g);
        let phys: Vec<usize> = (lo..hi).map(|ti| base + ti).collect();
        let _ = self.slices[cell].set((dir, base, phys));
        self.slices[cell].get()
    }

    /// The view's tile descriptors of order `si`.
    fn tiles(&self, si: usize) -> Option<Vec<crate::index::Tile>> {
        let g = self.g;
        match self.src[si] {
            ViewSrc::Slice => {
                let (dir, base, phys) = self.graph_slice(si, si)?;
                Some(
                    phys.iter()
                        .map(|&p| {
                            let t = &dir[p - base];
                            let min_a = if t.first_g == g { t.first_a } else { 0 };
                            let max_a = if t.last_g == g { t.last_a } else { u32::MAX };
                            crate::index::Tile::remote_with_len(
                                min_a,
                                max_a,
                                Some(t.syn),
                                t.range.len.min(u32::MAX as u64) as u32,
                            )
                        })
                        .collect(),
                )
            }
            ViewSrc::Synth => {
                let (dir, base, phys) = self.graph_slice(0, GSPO_CELL)?;
                if phys.is_empty() {
                    return Some(Vec::new());
                }
                let len: u64 = phys.iter().map(|&p| dir[p - base].range.len).sum();
                Some(vec![crate::index::Tile::remote_with_len(
                    0,
                    u32::MAX,
                    None,
                    len.min(u32::MAX as u64) as u32,
                )])
            }
            ViewSrc::Filter(slot) => {
                let dir = self.core.dir(slot)?;
                let mut tiles = Vec::new();
                let mut phys = Vec::new();
                for (ti, t) in dir.iter().enumerate() {
                    // syn = (min c, max c, min g, max g)
                    if t.syn.2 <= g && g <= t.syn.3 {
                        tiles.push(crate::index::Tile::remote_with_len(
                            t.first_g,
                            t.last_g,
                            Some((0, u32::MAX, t.syn.0, t.syn.1)),
                            t.range.len.min(u32::MAX as u64) as u32,
                        ));
                        phys.push(ti);
                    }
                }
                let _ = self.slices[si].set((dir, 0, phys));
                Some(tiles)
            }
        }
    }

    /// The graph's rows, from its GSPO slice, decoded once.
    fn graph_rows(&self) -> Option<Arc<Vec<Triple>>> {
        self.rows
            .get_or_init(|| {
                let (dir, base, phys) = self.graph_slice(0, GSPO_CELL)?;
                let mut rows: Vec<Triple> = Vec::new();
                for &p in phys {
                    let entry = self.core.tile(0, dir, *base, p)?;
                    let seg = self
                        .core
                        .segment(0, p, &entry, dir[p - base].first_g, self.g)?;
                    if let Some((first_a, body)) = seg {
                        // A fresh vector per segment: the decoder bounds its row
                        // count by the segment's bytes.
                        let mut seg: Vec<Triple> = Vec::new();
                        decode_segment_body(body, first_a, (false, false), &mut seg)?;
                        rows.extend(seg);
                    }
                }
                Some(Arc::new(rows))
            })
            .clone()
    }

    /// Tile `ti` of view order `si` as a §6.1 block.
    fn block(&self, si: usize, ti: usize) -> Option<Vec<u8>> {
        match self.src[si] {
            ViewSrc::Slice => {
                let (dir, base, phys) = self.slices[si].get()?;
                let p = *phys.get(ti)?;
                let entry = self.core.tile(si, dir, *base, p)?;
                let seg = self
                    .core
                    .segment(si, p, &entry, dir[p - base].first_g, self.g)?;
                segment_block(seg, ALL_PERMS[si])
            }
            ViewSrc::Synth => {
                if ti != 0 {
                    return None;
                }
                let rows = self.graph_rows()?;
                let perm = ALL_PERMS[si];
                let mut b = TripleBlockBuilder::new();
                for &t in rows.iter() {
                    b.push(perm.forward(t));
                }
                Some(b.build())
            }
            ViewSrc::Filter(slot) => {
                let (dir, base, phys) = self.slices[si].get()?;
                let p = *phys.get(ti)?;
                let entry = self.core.tile(slot, dir, *base, p)?;
                let scol = quad7::subject_col(quad7::perm_of(slot));
                let mut rows = Vec::new();
                quad7::decode_tile(entry.body(), scol, &mut rows)?;
                let mut b = TripleBlockBuilder::new();
                for r in rows.iter().filter(|r| r.3 == self.g) {
                    b.push((r.0, r.1, r.2));
                }
                Some(b.build())
            }
        }
    }

    /// Tiles `tis` of view order `si`, faulted in one batch where the order
    /// reads real tiles.
    fn blocks(&self, si: usize, tis: &[usize]) -> Option<Vec<Vec<u8>>> {
        let slot = match self.src[si] {
            ViewSrc::Slice => Some(si),
            ViewSrc::Filter(slot) => Some(slot),
            ViewSrc::Synth => None,
        };
        if let Some(slot) = slot {
            let (dir, base, phys) = self.slices[si].get()?;
            let want: Vec<usize> = tis
                .iter()
                .map(|&ti| phys.get(ti).copied())
                .collect::<Option<_>>()?;
            self.core.fault(slot, dir, *base, &want)?;
        }
        tis.iter().map(|&ti| self.block(si, ti)).collect()
    }
}

/// Lift a `0x05` quad-index section into the parts a `0x06` file is
/// assembled from (`v06::parts`): counts, `P0`, the graph-directory blocks'
/// range and every order's tiles with their absolute input ranges.
pub(crate) fn v05_parts(
    reader: &dyn RangeReader,
    section: ByteRange,
    perms: PermSet,
) -> Result<crate::v06::parts::QuadPart, FileError> {
    let head = reader.read_at(section.offset, section.len.min(PREAMBLE_MAX))?;
    let pre = parse_preamble(&head, section.offset, section.len, perms)?;
    let n = pre.mask.count_ones() as usize;
    let p0 = pre.parts[0];
    let p0_bytes = reader.read_at(p0.offset, p0.len)?;
    let gdir = pre.parts[1 + n];
    let mut orders = Vec::with_capacity(n);
    let order_perms = ALL_PERMS
        .into_iter()
        .filter(|p| pre.mask & (1 << p.section_index()) != 0);
    for (k, perm) in order_perms.enumerate() {
        let part = pre.parts[1 + k];
        let bytes = reader.read_at(part.offset, part.len)?;
        let tiles = parse_tile_dir(&bytes, pre.parts[2 + n + k])
            .ok_or(FileError::Container("malformed quad-index tile directory"))?;
        orders.push((
            perm.section_index(),
            tiles
                .iter()
                .map(|t| crate::v06::QTileEnt {
                    first: (t.first_g, t.first_a),
                    last: (t.last_g, t.last_a),
                    clen: t.range.len,
                    raw: t.raw,
                    syn: t.syn,
                    off: t.range.offset,
                })
                .collect(),
        ));
    }
    Ok(crate::v06::parts::QuadPart {
        graph_count: pre.graph_count,
        quad_count: pre.quad_count,
        block_graphs: pre.block_graphs,
        p0: p0_bytes,
        gdir,
        orders,
    })
}

/// Parse one order's tile directory part; tile ranges are resolved against
/// `payload`, the order's payload part. Every field is untrusted.
fn parse_tile_dir(b: &[u8], payload: ByteRange) -> Option<Vec<QTile>> {
    let mut pos = 0usize;
    let num = rd64(b, &mut pos)?;
    let mut out = Vec::with_capacity((num as usize).min(b.len()));
    let mut first_g = 0u32;
    let mut at = 0u64;
    let mut prev_key = (0u32, 0u32);
    for i in 0..num {
        first_g = first_g.checked_add(rd32(b, &mut pos)?)?;
        let first_a = rd32(b, &mut pos)?;
        let last_g = first_g.checked_add(rd32(b, &mut pos)?)?;
        let last_a = rd32(b, &mut pos)?;
        let packed = rd64(b, &mut pos)?;
        let min_b = rd32(b, &mut pos)?;
        let max_b = min_b.checked_add(rd32(b, &mut pos)?)?;
        let min_c = rd32(b, &mut pos)?;
        let max_c = min_c.checked_add(rd32(b, &mut pos)?)?;
        // Keys ascend (equal only across a mega-group cut).
        if (first_g, first_a) > (last_g, last_a) || (i > 0 && (first_g, first_a) < prev_key) {
            return None;
        }
        prev_key = (last_g, last_a);
        let clen = packed >> 1;
        let end = at.checked_add(clen).filter(|&e| e <= payload.len)?;
        out.push(QTile {
            first_g,
            first_a,
            last_g,
            last_a,
            range: ByteRange {
                offset: payload.offset + at,
                len: clen,
            },
            raw: packed & 1 == 1,
            syn: (min_b, max_b, min_c, max_c),
        });
        at = end;
    }
    Some(out)
}

/// Decode a segment body (see [`encode_segment_body`]) into `(a, b, c)` rows.
/// Bounds-safe: `None` on any malformed varint or overrun.
fn decode_segment_body(
    body: &[u8],
    first_a: u32,
    (zz_b, zz_c): (bool, bool),
    out: &mut Vec<Triple>,
) -> Option<()> {
    let mut pos = 0usize;
    // A zigzag-coded run start: `base + unzigzag(v)`, kept inside `u32`.
    let rebase = |base: &mut i64, v: u64| -> Option<u32> {
        let x = base.checked_add(unzigzag(v))?;
        *base = x;
        u32::try_from(x).ok()
    };
    let (mut base_b, mut base_c) = (0i64, 0i64);
    let num_a = rd32(body, &mut pos)?;
    let mut a = first_a;
    for i in 0..num_a {
        if i > 0 {
            a = a.checked_add(rd32(body, &mut pos)?)?;
        }
        let num_b = rd32(body, &mut pos)?;
        let mut b = 0u32;
        for j in 0..num_b {
            b = if zz_b && j == 0 {
                rebase(&mut base_b, rd64(body, &mut pos)?)?
            } else {
                b.checked_add(rd32(body, &mut pos)?)?
            };
            let num_c = rd32(body, &mut pos)?;
            let mut c = 0u32;
            for k in 0..num_c {
                c = if zz_c && k == 0 {
                    rebase(&mut base_c, rd64(body, &mut pos)?)?
                } else {
                    c.checked_add(rd32(body, &mut pos)?)?
                };
                if out.len() >= body.len() {
                    return None; // every row costs at least one byte
                }
                out.push((a, b, c));
            }
        }
    }
    Some(())
}

/// Walk a decompressed tile's segments, calling `f(g, first_a, body)` for each
/// until it returns `false`. `None` on a malformed tile.
fn walk_segments(
    tile: &[u8],
    first_g: u32,
    mut f: impl FnMut(u32, u32, &[u8]) -> bool,
) -> Option<()> {
    let mut pos = 0usize;
    let take = |pos: &mut usize| -> Option<u64> {
        let (v, n) = read_uvarint(tile.get(*pos..)?)?;
        *pos += n;
        Some(v)
    };
    let n = take(&mut pos)?;
    let mut g = first_g;
    let mut fa: i64 = 0;
    for _ in 0..n {
        g = g.checked_add(u32::try_from(take(&mut pos)?).ok()?)?;
        fa = fa.checked_add(unzigzag(take(&mut pos)?))?;
        let first_a = u32::try_from(fa).ok()?;
        let len = usize::try_from(take(&mut pos)?).ok()?;
        let body = tile.get(pos..pos.checked_add(len)?)?;
        pos += len;
        if !f(g, first_a, body) {
            break;
        }
    }
    Some(())
}

/// Where each segment of a decompressed tile is: the index a lookup of one
/// graph searches instead of walking the tile's segment headers. A tile of
/// small graphs holds thousands of them, and a join that looks up one graph
/// per row walked half a tile of headers for each row. `None` on a malformed
/// tile. The graph ids ascend (they are stored as unsigned deltas).
fn segment_index(tile: &[u8], first_g: u32) -> Option<Vec<crate::chunk_cache::TileSeg>> {
    let mut out = Vec::new();
    let mut ok = true;
    let start = tile.as_ptr() as usize;
    walk_segments(tile, first_g, |g, first_a, body| {
        let off = u32::try_from(body.as_ptr() as usize - start);
        let len = u32::try_from(body.len());
        match (off, len) {
            (Ok(off), Ok(len)) => out.push((g, first_a, off, len)),
            _ => ok = false,
        }
        ok
    })?;
    ok.then_some(out)
}

/// Graph `g`'s segment of a tile, as `(first a, body)`: the first one, as a
/// walk of the tile finds it. `Some(None)`: the tile holds none of the graph.
/// `None`: a malformed tile.
fn segment_of<'t>(
    tile: &'t [u8],
    segs: &[crate::chunk_cache::TileSeg],
    g: u32,
) -> Option<Option<(u32, &'t [u8])>> {
    let i = segs.partition_point(|s| s.0 < g);
    match segs.get(i) {
        Some(&(sg, first_a, off, len)) if sg == g => {
            let (off, len) = (off as usize, len as usize);
            Some(Some((first_a, tile.get(off..off.checked_add(len)?)?)))
        }
        _ => Some(None),
    }
}

/// A graph's segment of a tile (`(first a, body)`, or `None` when the tile
/// holds none of the graph) as a §6.1 block. `None` on a malformed segment.
fn segment_block(seg: Option<(u32, &[u8])>, perm: IndexPermutation) -> Option<Vec<u8>> {
    let cols = subject_columns(perm);
    let mut rows: Vec<Triple> = Vec::new();
    if let Some((first_a, body)) = seg {
        decode_segment_body(body, first_a, cols, &mut rows)?;
    }
    let mut b = TripleBlockBuilder::new();
    for t in rows {
        b.push(t);
    }
    Some(b.build())
}

/// Every row of a decompressed graph-leading tile as `(g, a, b, c)`.
pub(crate) fn tile_rows(tile: &[u8], first_g: u32, perm: IndexPermutation) -> Option<Vec<QuadRow>> {
    let cols = subject_columns(perm);
    let mut out = Vec::new();
    let mut ok = true;
    walk_segments(tile, first_g, |g, first_a, body| {
        let mut rows = Vec::new();
        ok &= decode_segment_body(body, first_a, cols, &mut rows).is_some();
        out.extend(rows.into_iter().map(|(a, b, c)| (g, a, b, c)));
        ok
    })?;
    ok.then_some(out)
}

/// One graph's lazily-filled cells.
#[derive(Default)]
struct QuadEntry {
    name: OnceLock<String>,
    view: OnceLock<Box<GraphIndex>>,
}

mod probe;

/// The named graphs of a quad-index file, opened over a [`RangeReader`]:
/// nothing is read at open. The graph count costs the preamble (one small
/// read), a name one directory block plus one dictionary chunk, a graph's
/// index its orders' tile directories, and a scan the tiles it touches.
///
/// Failure contract (as for lazy tiles and chunks): a failed read or a
/// malformed record sets a sticky flag, the accessor returns `None`, nothing
/// failed is memoised.
pub(crate) struct QuadNamed {
    core: Arc<QuadCore>,
    entries: OnceLock<Box<[EntrySlab]>>,
    tile_cap: AtomicU64,
}

impl QuadNamed {
    pub(crate) fn new(
        reader: Arc<dyn RangeReader + Send + Sync>,
        section: ByteRange,
        codec: u8,
        perms: PermSet,
        read_concurrency: usize,
    ) -> Self {
        QuadNamed {
            core: Arc::new(QuadCore {
                reader,
                section,
                codec,
                perms,
                read_concurrency,
                pre: OnceLock::new(),
                blocks_index: OnceLock::new(),
                blocks: OnceLock::new(),
                recent: RwLock::new(RecentBlocks::default()),
                memo_max_graphs: BLOCK_MEMO_MAX_GRAPHS,
                dirs: Default::default(),
                tiles: ChunkCache::unlimited(),
                ramps: Mutex::new(Default::default()),
                failed: AtomicBool::new(false),
                v06: None,
            }),
            entries: OnceLock::new(),
            tile_cap: AtomicU64::new(u64::MAX),
        }
    }

    /// The named graphs of a `0x06` file.
    pub(crate) fn new_v06(
        reader: Arc<dyn RangeReader + Send + Sync>,
        v06: V06Quad,
        codec: u8,
        perms: PermSet,
        read_concurrency: usize,
    ) -> Self {
        let mut q = Self::new(
            reader,
            ByteRange { offset: 0, len: 0 },
            codec,
            perms,
            read_concurrency,
        );
        if let Some(core) = Arc::get_mut(&mut q.core) {
            core.v06 = Some(Arc::new(v06));
        }
        q
    }

    /// Over an owned copy of the section's bytes (the resident opens).
    pub(crate) fn resident(bytes: Vec<u8>, codec: u8, perms: PermSet) -> Self {
        let len = bytes.len() as u64;
        Self::new(
            Arc::new(OwnedReader(Arc::from(bytes))),
            ByteRange { offset: 0, len },
            codec,
            perms,
            1,
        )
    }

    pub(crate) fn count(&self) -> usize {
        self.core.pre().map(|p| p.graph_count as usize).unwrap_or(0)
    }

    /// Deduplicated quads across every named graph (from the preamble).
    pub(crate) fn quad_count(&self) -> u64 {
        self.core.pre().map(|p| p.quad_count).unwrap_or(0)
    }

    fn entry(&self, i: usize) -> Option<&QuadEntry> {
        let n = self.count();
        if i >= n {
            return None;
        }
        let table = self.entries.get_or_init(|| {
            (0..n.div_ceil(ENTRY_SLAB))
                .map(|_| OnceLock::new())
                .collect::<Vec<_>>()
                .into()
        });
        let slab = table.get(i / ENTRY_SLAB)?.get_or_init(|| {
            let len = ENTRY_SLAB.min(n - (i / ENTRY_SLAB) * ENTRY_SLAB);
            (0..len).map(|_| QuadEntry::default()).collect()
        });
        slab.get(i % ENTRY_SLAB)
    }

    /// The `i`-th graph's quad count, from the directory (no tile read).
    pub(crate) fn quad_count_at(&self, i: usize) -> Option<u64> {
        self.core.graph_at(i, false).map(|(_, n)| n)
    }

    pub(crate) fn name_at(&self, dict: &Dictionary, i: usize, exhaustive: bool) -> Option<&str> {
        let e = self.entry(i)?;
        if let Some(n) = e.name.get() {
            return Some(n.as_str());
        }
        let (g, _) = self.core.graph_at(i, exhaustive)?;
        match dict.subject_term(g) {
            Some(name) => {
                let _ = e.name.set(name);
                e.name.get().map(|s| s.as_str())
            }
            None => {
                // The directory names a graph id the dictionary does not hold.
                self.core.fail();
                None
            }
        }
    }

    pub(crate) fn graph_at(
        &self,
        dict: &Dictionary,
        i: usize,
        exhaustive: bool,
    ) -> Option<(&str, &GraphIndex)> {
        let name = self.name_at(dict, i, exhaustive)?;
        let e = self.entry(i)?;
        if e.view.get().is_none() {
            let (g, n) = self.core.graph_at(i, exhaustive)?;
            let cap = self.tile_cap.load(Ordering::Relaxed);
            let view = self.core.view(g, n, cap)?;
            let _ = e.view.set(Box::new(view));
        }
        Some((name, e.view.get()?.as_ref()))
    }

    /// The `i`-th graph as an **owned, unmemoised** view, when it holds at most
    /// `max_quads` quads (from the directory) — for a walk over many graphs
    /// (`GRAPH ?g`), which then holds one small view at a time instead of one
    /// per graph. The view shares the decompressed-tile cache, so consecutive
    /// graphs of one tile still cost one decompression. `None` for a larger
    /// graph (use [`graph_at`](Self::graph_at)) or on a failed read.
    pub(crate) fn transient_view(&self, i: usize, max_quads: u64) -> Option<GraphIndex> {
        let (g, n) = self.core.graph_at(i, false)?;
        if n > max_quads {
            return None;
        }
        self.core.view(g, n, self.tile_cap.load(Ordering::Relaxed))
    }

    /// The ordinals (ascending) of the graphs holding a quad whose subject is
    /// one of `subjects` (subject ids) — what a `GRAPH ?g` walk restricted to
    /// those subjects has to visit. One pass over the `G+SPO` tiles plus the
    /// directory blocks of the graphs found, never a view per graph. `None` on
    /// a failed read.
    pub(crate) fn graphs_with_subjects(
        &self,
        subjects: &std::collections::BTreeSet<u32>,
    ) -> Option<Vec<usize>> {
        self.core
            .graphs_with_subjects(subjects)?
            .into_iter()
            .map(|g| self.core.ordinal_of(g))
            .collect()
    }

    /// The `i`-th graph's name **without memoising it**, for a walk over many
    /// graphs: [`name_at`](Self::name_at) keeps every name it returns for the
    /// life of the open, which over 43 M graphs is gigabytes. A name already
    /// memoised is cloned from its cell.
    pub(crate) fn name_owned(
        &self,
        dict: &Dictionary,
        i: usize,
        exhaustive: bool,
    ) -> Option<String> {
        // Look at the cell only where its slab exists: creating the slab of
        // every graph the walk passes would be 48 bytes per graph again.
        let memo = self
            .entries
            .get()
            .and_then(|t| t.get(i / ENTRY_SLAB)?.get())
            .and_then(|slab| slab.get(i % ENTRY_SLAB)?.name.get());
        if let Some(n) = memo {
            return Some(n.clone());
        }
        let (g, _) = self.core.graph_at(i, exhaustive)?;
        match dict.subject_term(g) {
            Some(name) => Some(name),
            None => {
                self.core.fail();
                None
            }
        }
    }

    /// The ordinal of the graph named `iri` (dictionary lookup, then directory
    /// binary search), or `None` when the file has no such graph.
    pub(crate) fn ordinal_of_iri(&self, dict: &Dictionary, iri: &str) -> Option<usize> {
        self.ordinal_of_name(dict, iri)
    }

    /// The dictionary node that names graph `i` (the directory holds its
    /// subject id): no term is decoded.
    pub(crate) fn node_at(&self, dict: &Dictionary, i: usize, exhaustive: bool) -> Option<u32> {
        let (g, _) = self.core.graph_at(i, exhaustive)?;
        Some(dict.subject_node(g))
    }

    /// The ordinal of the graph whose name is the dictionary node `node` (the
    /// directory is keyed by subject id): no term is decoded, no lookup made.
    pub(crate) fn ordinal_of_node(&self, dict: &Dictionary, node: u32) -> Option<usize> {
        self.core.ordinal_of_for_view(dict.node_subject_id(node)?)
    }

    /// A streaming scan of every quad matching a triple pattern, over all
    /// graphs: see [`QuadScan`]. `None` when the section is unreadable.
    ///
    /// The order is the one whose leading columns the pattern binds the
    /// longest. A `0x07` file has the graph-last SPOG, POSG and OSPG for that
    /// (`<s>` is a SPOG prefix, `<p>` and `<p> <o>` POSG, `<o>` and `<o> <s>`
    /// OSPG, `<s> <p>` SPOG); the graph-leading GSPO only takes a pattern with
    /// nothing bound, which it answers in graph order. A `0x05`/`0x06` file's
    /// graph-leading orders cover the eight shapes by synopsis pruning.
    pub(crate) fn scan(&self, pat: (Option<u32>, Option<u32>, Option<u32>)) -> Option<QuadScan> {
        let mask = self.core.mask();
        let any_last = mask & quad7::LAST_MASK != 0;
        let slot = (0..NUM_SLOTS)
            .filter(|s| mask & (1 << s) != 0)
            .max_by_key(|&s| {
                let lead = quad7::perm_of(s)
                    .order_pattern(pat)
                    .iter()
                    .take_while(|c| c.is_some())
                    .count();
                // A graph-leading order cannot be seeked on its first column
                // when a graph-last one exists.
                let score = if !quad7::is_last(s) && any_last {
                    0
                } else {
                    lead
                };
                (
                    score,
                    u8::from(score > 0 && quad7::is_last(s)),
                    std::cmp::Reverse(s),
                )
            })?;
        self.core.scan_slot(pat, slot)
    }

    /// The ordinal of the graph with subject id `g`, or `None` when the file
    /// lists no such graph.
    pub(crate) fn ordinal_of_id(&self, g: u32) -> Option<usize> {
        self.core.ordinal_of(g)
    }

    fn ordinal_of_name(&self, dict: &Dictionary, iri: &str) -> Option<usize> {
        let g = dict.subject_id(iri)?;
        self.core.ordinal_of_for_view(g)
    }

    /// The index of the graph named `iri`: dictionary lookup, then directory
    /// binary search — never a walk. `None` when the file has no such graph.
    pub(crate) fn find(&self, dict: &Dictionary, iri: &str) -> Option<&GraphIndex> {
        let i = self.ordinal_of_name(dict, iri)?;
        self.graph_at(dict, i, false).map(|(_, g)| g)
    }

    /// Drop graph `iri`'s view (and its decoded blocks); it re-opens lazily.
    pub(crate) fn release(&mut self, dict: &Dictionary, iri: &str) {
        let Some(i) = self.ordinal_of_name(dict, iri) else {
            return;
        };
        let Some(table) = self.entries.get_mut() else {
            return;
        };
        if let Some(slab) = table.get_mut(i / ENTRY_SLAB).and_then(|s| s.get_mut()) {
            if let Some(e) = slab.get_mut(i % ENTRY_SLAB) {
                e.view.take();
            }
        }
    }

    pub(crate) fn for_each_opened(&self, mut f: impl FnMut(&GraphIndex)) {
        if let Some(table) = self.entries.get() {
            for slab in table.iter().filter_map(|s| s.get()) {
                for e in slab.iter() {
                    if let Some(v) = e.view.get() {
                        f(v);
                    }
                }
            }
        }
    }

    pub(crate) fn load_incomplete(&self) -> bool {
        if self.core.failed.load(Ordering::Relaxed) {
            return true;
        }
        let mut bad = false;
        self.for_each_opened(|g| bad |= g.load_incomplete());
        bad
    }

    pub(crate) fn reset_load_failures(&self) {
        self.core.failed.store(false, Ordering::Relaxed);
        self.for_each_opened(|g| g.reset_load_failure());
    }

    /// Cap the shared tile cache and every view's block cache (both re-fault
    /// through loaders, so any cap is sound).
    pub(crate) fn set_tile_cap(&self, cap: u64) {
        self.tile_cap.store(cap, Ordering::Relaxed);
        self.core.tiles.set_cap(cap);
        self.for_each_opened(|g| g.set_cache_cap(cap));
    }

    /// Heap held outside the caches: the routing parts read so far, the
    /// per-graph cells, and the open views' directories.
    pub(crate) fn directory_bytes(&self) -> u64 {
        let c = &self.core;
        let mut bytes = 0u64;
        if let Some(b) = c.blocks_index.get() {
            bytes += (b.len() * std::mem::size_of::<BlockRef>()) as u64;
        }
        if let Some(cells) = c.blocks.get() {
            for v in cells.iter().filter_map(|c| c.get()) {
                bytes += (v.len() * 16) as u64;
            }
        }
        for d in c.dirs.iter().filter_map(|d| d.get()) {
            bytes += (d.len() * std::mem::size_of::<QTile>()) as u64;
        }
        if let Some(table) = self.entries.get() {
            for slab in table.iter().filter_map(|s| s.get()) {
                bytes += (slab.len() * std::mem::size_of::<QuadEntry>()) as u64;
                for e in slab.iter() {
                    if let Some(n) = e.name.get() {
                        bytes += n.capacity() as u64;
                    }
                    if let Some(v) = e.view.get() {
                        bytes += v.directory_bytes();
                    }
                }
            }
        }
        bytes
    }
}

/// A streaming scan of the quads matching a triple pattern over **every**
/// graph of a quad index, yielding `(graph id, (s, p, o))`.
///
/// It walks one order's tiles and decodes one at a time, so memory is a tile
/// and its matches, never proportional to the number of graphs or quads.
///
/// - A graph-leading order (`0x05`, `0x06`, and GSPO of `0x07`) skips the tiles
///   whose directory entry (graph and first-column range, column synopsis)
///   cannot hold a match; with the graph unbound that is a pass over what the
///   synopses cannot rule out. Rows come in graph order.
/// - A graph-last order (`0x07`: SPOG, POSG, OSPG) is **seeked**: the pattern's
///   leading bound columns are a prefix of the order, so the tiles holding it
///   are the run whose `(a, b)` key range contains the prefix, found by binary
///   search on the directory (and, for a big file, on the leaves the root
///   lists), then read in one batch. Rows come in `(a, b, c, g)` order, not
///   graph order ([`graph_ordered`](Self::graph_ordered)).
pub(crate) struct QuadScan {
    core: Arc<QuadCore>,
    /// The order's directory, or the slice of it that can hold the pattern.
    dir: Arc<[QTile]>,
    /// Index in the whole order of `dir[0]`.
    base: usize,
    perm: IndexPermutation,
    /// The order's slot (`quad7`).
    si: usize,
    last: bool,
    /// The pattern's bound values in this order's column order.
    abc: [Option<u32>; 3],
    cols: (bool, bool),
    /// Next tile to look at, and the end of the range (both absolute).
    next_tile: usize,
    end_tile: usize,
    /// How many tiles a restricted scan faults at once, itself (0: the
    /// order's shared read-ahead, which follows one sequential reader).
    ahead: usize,
    buf: std::vec::IntoIter<(u32, Triple)>,
}

impl QuadScan {
    /// Does the scan yield rows in graph order? (A graph-leading order does.)
    pub(crate) fn graph_ordered(&self) -> bool {
        !self.last
    }

    /// The tiles this scan still has to look at, as `[start, end)` in the
    /// order's directory.
    pub(crate) fn tile_range(&self) -> (usize, usize) {
        (self.next_tile, self.end_tile)
    }

    /// Keep only the tiles `[lo, hi)` of [`tile_range`](Self::tile_range). A
    /// row lies in one tile, so scans over disjoint slices that cover the
    /// range yield every row of the whole scan exactly once, in its order.
    pub(crate) fn restrict(&mut self, lo: usize, hi: usize) {
        let lo = lo.clamp(self.next_tile, self.end_tile);
        self.end_tile = hi.clamp(lo, self.end_tile);
        self.next_tile = lo;
        // Several restricted scans run at once, each over its own range: the
        // order's one read-ahead window would follow none of them, and every
        // tile would be its own read. Each batches its own tiles instead.
        self.ahead = READ_AHEAD_MAX;
    }

    fn tile_may_match(&self, t: &QTile) -> bool {
        let (x, y, z, w) = t.syn;
        if self.last {
            // (min c, max c, min g, max g); the leading keys were used to cut
            // the range.
            return !self.abc[2].is_some_and(|c| c < x || c > y);
        }
        let (min_b, max_b, min_c, max_c) = (x, y, z, w);
        if self.abc[1].is_some_and(|b| b < min_b || b > max_b) {
            return false;
        }
        if self.abc[2].is_some_and(|c| c < min_c || c > max_c) {
            return false;
        }
        // Inside one graph the first column ascends from `first_a` to `last_a`.
        if t.first_g == t.last_g && self.abc[0].is_some_and(|a| a < t.first_a || a > t.last_a) {
            return false;
        }
        true
    }

    /// Decode the next tile that holds a match into `buf`; `false` at the end
    /// (or on a failed read, which the core has recorded).
    fn fill(&mut self) -> bool {
        while self.next_tile < self.end_tile {
            let ti = self.next_tile;
            self.next_tile += 1;
            let t = self.dir[ti - self.base];
            if !self.tile_may_match(&t) {
                continue;
            }
            if self.ahead > 0 && !self.core.tiles.contains((self.si as u8, ti as u32)) {
                let end = (ti + self.ahead).min(self.end_tile);
                let want: Vec<usize> = (ti..end)
                    .filter(|&k| self.tile_may_match(&self.dir[k - self.base]))
                    .collect();
                // A failed batch leaves the tiles to the read below.
                let _ = self.core.fault(self.si, &self.dir, self.base, &want);
            }
            let Some(entry) =
                self.core
                    .tile_capped(self.si, &self.dir, self.base, ti, self.end_tile)
            else {
                self.next_tile = self.end_tile;
                return false;
            };
            let [wa, wb, wc] = self.abc;
            let mut out: Vec<(u32, Triple)> = Vec::new();
            let ok = if self.last {
                let mut rows: Vec<quad7::Row4> = Vec::new();
                let scol = quad7::subject_col(self.perm);
                let ok = quad7::decode_tile(entry.body(), scol, &mut rows).is_some();
                for r in &rows {
                    if wa.is_none_or(|x| x == r.0)
                        && wb.is_none_or(|x| x == r.1)
                        && wc.is_none_or(|x| x == r.2)
                    {
                        out.push(quad7::quad_of(self.perm, r));
                    }
                }
                ok
            } else {
                let mut rows: Vec<Triple> = Vec::new();
                let mut ok = true;
                let walked = walk_segments(entry.body(), t.first_g, |g, first_a, seg| {
                    // Every row of a segment has a first column of at least `first_a`.
                    if wa.is_some_and(|a| a < first_a) {
                        return true;
                    }
                    rows.clear();
                    if decode_segment_body(seg, first_a, self.cols, &mut rows).is_none() {
                        ok = false;
                        return false;
                    }
                    for &(a, b, c) in &rows {
                        if wa.is_none_or(|x| x == a)
                            && wb.is_none_or(|x| x == b)
                            && wc.is_none_or(|x| x == c)
                        {
                            out.push((g, self.perm.back((a, b, c))));
                        }
                    }
                    true
                });
                walked.is_some() && ok
            };
            if !ok {
                self.core.fail();
                self.next_tile = self.end_tile;
                return false;
            }
            if !out.is_empty() {
                self.buf = out.into_iter();
                return true;
            }
        }
        false
    }
}

impl QuadScan {
    /// The permutation whose order the scan walks.
    pub(crate) fn perm(&self) -> IndexPermutation {
        self.perm
    }

    /// Are the rows globally sorted by `(a, b, c, g)`? A clustered order with
    /// no bound leading column is sorted only within each class run.
    pub(crate) fn globally_ordered(&self) -> bool {
        self.last && !(self.core.is_clustered(self.si) && self.abc[0].is_none())
    }

    /// The `(a, b, c)` of the first or last row of tile `ti` (absolute, within
    /// this scan's directory), whatever the pattern: a bound between tiles.
    fn edge_key(&self, ti: usize, first: bool) -> Option<(u32, u32, u32)> {
        if ti < self.base || ti >= self.base + self.dir.len() {
            return None;
        }
        let entry = self
            .core
            .tile_capped(self.si, &self.dir, self.base, ti, ti + 1)?;
        let mut rows: Vec<quad7::Row4> = Vec::new();
        quad7::decode_tile(entry.body(), quad7::subject_col(self.perm), &mut rows)?;
        let r = if first { rows.first() } else { rows.last() }?;
        Some((r.0, r.1, r.2))
    }

    /// The first row's `(a, b, c)` of tile `ti`.
    pub(crate) fn first_key(&self, ti: usize) -> Option<(u32, u32, u32)> {
        self.edge_key(ti, true)
    }

    /// The last row's `(a, b, c)` of tile `ti`.
    pub(crate) fn last_key(&self, ti: usize) -> Option<(u32, u32, u32)> {
        self.edge_key(ti, false)
    }

    /// What the scan would read, from the directory alone: the tiles in its
    /// range, those the synopses admit, their stored bytes, the stored bytes
    /// of the range, and the order's tile count.
    pub(crate) fn plan(&self) -> QuadPlan {
        let mut p = QuadPlan {
            routed: self.end_tile.saturating_sub(self.next_tile),
            ..QuadPlan::default()
        };
        for ti in self.next_tile..self.end_tile {
            let t = &self.dir[ti - self.base];
            p.routed_bytes += t.range.len;
            if self.tile_may_match(t) {
                p.admitted += 1;
                p.admitted_bytes += t.range.len;
            }
        }
        p.order_tiles = self.core.order_tiles(self.si).max(1);
        p.quads = self.core.pre().map_or(0, |p| p.quad_count);
        p
    }
}

/// See [`QuadScan::plan`].
#[derive(Default, Clone, Copy)]
pub(crate) struct QuadPlan {
    pub(crate) routed: usize,
    pub(crate) admitted: usize,
    pub(crate) routed_bytes: u64,
    pub(crate) admitted_bytes: u64,
    pub(crate) order_tiles: usize,
    pub(crate) quads: u64,
}

/// A handle on the quad index that does not borrow its file: what a union
/// default graph scans. Only made for an index with all three graph-last
/// orders (SPOG, POSG, OSPG), which a scan over every graph walks with the
/// graph as the last column, so one triple's quads are adjacent.
#[derive(Clone)]
pub(crate) struct QuadSrc(Arc<QuadCore>);

impl QuadSrc {
    /// A scan of `pat` in the graph-last order over `perm` (SPO, POS or OSP).
    pub(crate) fn scan(
        &self,
        pat: (Option<u32>, Option<u32>, Option<u32>),
        perm: IndexPermutation,
    ) -> Option<QuadScan> {
        self.0.scan_slot(pat, quad7::last_slot(perm))
    }

    /// Do reads cost a round trip each?
    pub(crate) fn is_remote(&self) -> bool {
        !self.0.reader.is_local()
    }

    pub(crate) fn read_concurrency(&self) -> usize {
        self.0.read_concurrency
    }
}

impl QuadNamed {
    /// The union-scan handle, when the index has the three graph-last orders.
    pub(crate) fn union_src(&self) -> Option<QuadSrc> {
        (self.core.mask() & quad7::LAST_MASK == quad7::LAST_MASK)
            .then(|| QuadSrc(Arc::clone(&self.core)))
    }
}

impl QuadCore {
    /// How many tiles order slot `si` has, from what is already known (a
    /// resident directory, or the leaves the root lists); 0 when unknown.
    fn order_tiles(&self, si: usize) -> usize {
        if let Some(d) = self.dirs[si].get() {
            return d.len();
        }
        match &self.v06 {
            Some(v) => v.orders[si].iter().map(|l| l.n).sum(),
            None => 0,
        }
    }
}

impl Iterator for QuadScan {
    type Item = (u32, Triple);

    fn next(&mut self) -> Option<(u32, Triple)> {
        loop {
            if let Some(q) = self.buf.next() {
                return Some(q);
            }
            if !self.fill() {
                return None;
            }
        }
    }
}

/// A [`RangeReader`] over an owned buffer.
struct OwnedReader(Arc<[u8]>);

impl RangeReader for OwnedReader {
    fn is_local(&self) -> bool {
        true
    }

    fn len(&self) -> u64 {
        self.0.len() as u64
    }

    fn read_at(&self, offset: u64, len: u64) -> std::io::Result<Vec<u8>> {
        let start = usize::try_from(offset).map_err(std::io::Error::other)?;
        let end = start
            .checked_add(usize::try_from(len).map_err(std::io::Error::other)?)
            .filter(|&e| e <= self.0.len())
            .ok_or_else(|| {
                std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "read past the section")
            })?;
        Ok(self.0[start..end].to_vec())
    }
}

/// Structural check of a QUAD_INDEX section held in RAM: preamble, directory,
/// every tile decodes and its rows lie inside the directory's key range, and
/// the counts agree. `verify` uses the digest; this is for tests and `rete
/// verify --deep`-style checks.
#[cfg(test)]
pub(crate) fn check_section(bytes: &[u8], perms: PermSet, codec: u8) -> Result<u64, String> {
    let q = QuadNamed::resident(bytes.to_vec(), codec, perms);
    let pre = q.core.pre().ok_or("preamble")?.clone();
    let n = pre.graph_count as usize;
    let mut total = 0u64;
    for i in 0..n {
        total += q.core.graph_at(i, true).ok_or("graph")?.1;
    }
    if total != pre.quad_count {
        return Err(format!("directory counts {total} != {}", pre.quad_count));
    }
    for perm in perms.iter() {
        let si = perm.section_index();
        let dir = q.core.dir(si).ok_or("dir")?;
        let mut seen = 0u64;
        for (ti, t) in dir.iter().enumerate() {
            let e = q.core.tile(si, &dir, 0, ti).ok_or("tile")?;
            let rows = tile_rows(e.body(), t.first_g, perm).ok_or("rows")?;
            if rows.first().map(|r| (r.0, r.1)) != Some((t.first_g, t.first_a))
                || rows.last().map(|r| (r.0, r.1)) != Some((t.last_g, t.last_a))
            {
                return Err(format!("{} tile {ti} key range", perm.name()));
            }
            seen += rows.len() as u64;
        }
        if seen != pre.quad_count {
            return Err(format!("{} holds {seen} rows", perm.name()));
        }
    }
    Ok(pre.quad_count)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::file::writer_codec;

    fn quads(graphs: u32, per: u32) -> Vec<[u32; 4]> {
        let mut out = Vec::new();
        for g in 1..=graphs {
            for k in 0..per {
                let s = g * 3 + (k % 3);
                let p = 1 + (k % 4);
                let o = 1 + (g * 7 + k * 13) % 500;
                out.push([g * 2, s, p, o]);
            }
        }
        out
    }

    #[test]
    fn zigzag_round_trips() {
        for v in [0i64, 1, -1, 2, -2, 1 << 40, -(1 << 40), i64::from(u32::MAX)] {
            assert_eq!(unzigzag(zigzag(v)), v);
        }
    }

    #[test]
    fn section_round_trips_every_order() {
        for perms in [PermSet::ALL, PermSet::CORE] {
            let q = quads(3000, 9);
            let enc = encode_quad_index(q.clone(), perms, writer_codec()).unwrap();
            assert_eq!(enc.graph_count, 3000);
            assert_eq!(
                check_section(&enc.bytes, perms, writer_codec()),
                Ok(enc.quad_count)
            );
            let mut want = q;
            want.sort_unstable();
            want.dedup();
            assert_eq!(enc.quad_count, want.len() as u64);
        }
    }

    #[test]
    fn tiles_are_shared_and_a_view_sees_only_its_graph() {
        let q = quads(5000, 10);
        let enc = encode_quad_index(q.clone(), PermSet::ALL, writer_codec()).unwrap();
        let named = QuadNamed::resident(enc.bytes, writer_codec(), PermSet::ALL);
        let dir = named.core.dir(0).unwrap();
        assert!(
            dir.len() < 100,
            "5000 small graphs must share tiles, got {} tiles",
            dir.len()
        );
        for g in [2u32, 4000, 10000] {
            let i = named.core.ordinal_of(g).unwrap();
            assert_eq!(named.core.graph_at(i, false).unwrap(), (g, 10));
            let view = named.core.view(g, 0, u64::MAX).unwrap();
            let mut got = view.match_pattern((None, None, None));
            got.sort_unstable();
            let mut want: Vec<Triple> = q
                .iter()
                .filter(|r| r[0] == g)
                .map(|r| (r[1], r[2], r[3]))
                .collect();
            want.sort_unstable();
            want.dedup();
            assert_eq!(got, want, "graph {g}");
            // Every pattern shape routes inside the view like a plain index.
            let plain = crate::GraphIndexBuilder::from_triples(want.clone()).build();
            let (s, p, o) = want[0];
            for pat in [
                (Some(s), None, None),
                (None, Some(p), None),
                (None, None, Some(o)),
                (Some(s), Some(p), None),
                (None, Some(p), Some(o)),
                (Some(s), None, Some(o)),
                (Some(s), Some(p), Some(o)),
            ] {
                let mut a = view.match_pattern(pat);
                let mut b = plain.match_pattern(pat);
                a.sort_unstable();
                b.sort_unstable();
                assert_eq!(a, b, "graph {g} pattern {pat:?}");
            }
            assert!(!view.load_incomplete());
        }
        assert_eq!(named.core.ordinal_of(3), None, "odd ids are not graphs");
        assert_eq!(named.core.ordinal_of(u32::MAX), None);
    }

    #[test]
    fn a_big_graph_spans_tiles_and_mega_groups_split() {
        // One graph of 60k quads with a single predicate (a mega-group in POS)
        // between two small ones.
        let mut q = Vec::new();
        for k in 0..60_000u32 {
            q.push([10, 1 + k, 7, 1 + (k * 31) % 9973]);
        }
        q.push([5, 1, 1, 1]);
        q.push([20, 2, 2, 2]);
        let enc = encode_quad_index(q.clone(), PermSet::ALL, writer_codec()).unwrap();
        check_section(&enc.bytes, PermSet::ALL, writer_codec()).unwrap();
        let named = QuadNamed::resident(enc.bytes, writer_codec(), PermSet::ALL);
        let view = named.core.view(10, 0, u64::MAX).unwrap();
        let pos = crate::IndexPermutation::Pos.section_index();
        assert!(view.tile_sections()[pos].len() > 1, "the graph spans tiles");
        let hits = view.match_pattern((None, Some(7), None));
        assert_eq!(hits.len(), 60_000);
        assert_eq!(view.match_pattern((Some(1), None, None)).len(), 1);
        let small = named.core.view(20, 0, u64::MAX).unwrap();
        assert_eq!(small.match_pattern((None, None, None)), vec![(2, 2, 2)]);
    }

    #[test]
    fn tiler_output_is_independent_of_how_rows_arrive() {
        // The external builder feeds the tiler from a merge, the in-RAM one from
        // a slice: identical rows must give identical tiles.
        let mut rows: Vec<QuadRow> = quads(800, 30)
            .into_iter()
            .map(|q| (q[0], q[1], q[2], q[3]))
            .collect();
        rows.sort_unstable();
        rows.dedup();
        let run = |budget: usize| {
            let mut tiles = Vec::new();
            let mut t = QuadTiler::with_budget(budget);
            for &r in &rows {
                t.push(r, &mut |x| tiles.push(x));
            }
            t.finish(&mut |x| tiles.push(x));
            tiles
        };
        let a = run(512);
        assert!(a.len() > 10);
        assert_eq!(a.concat(), rows, "tiles partition the rows in order");
        assert_eq!(a, run(512));
    }

    #[test]
    fn incompressible_tiles_are_stored_raw() {
        // One tiny graph: the zstd frame would be larger than the tile.
        let enc = encode_quad_index(vec![[1, 2, 3, 4]], PermSet::CORE, writer_codec()).unwrap();
        let named = QuadNamed::resident(enc.bytes, writer_codec(), PermSet::CORE);
        let dir = named.core.dir(0).unwrap();
        assert!(dir[0].raw, "a 10-byte tile is not worth a zstd frame");
        let view = named.core.view(1, 0, u64::MAX).unwrap();
        assert_eq!(view.match_pattern((None, None, None)), vec![(2, 3, 4)]);
    }

    #[test]
    fn corrupt_sections_fail_cleanly() {
        let enc = encode_quad_index(quads(200, 5), PermSet::ALL, writer_codec()).unwrap();
        let codec = writer_codec();
        for cut in [0usize, 4, 9, enc.bytes.len() / 2, enc.bytes.len() - 1] {
            let named = QuadNamed::resident(enc.bytes[..cut].to_vec(), codec, PermSet::ALL);
            let _ = named.count();
            let _ = named
                .core
                .view(2, 0, u64::MAX)
                .map(|v| v.match_pattern((None, None, None)));
        }
        // Flip bytes everywhere: never a panic, and any failure is reported.
        for i in (0..enc.bytes.len()).step_by(97) {
            let mut b = enc.bytes.clone();
            b[i] ^= 0x5a;
            let named = QuadNamed::resident(b, codec, PermSet::ALL);
            for k in 0..named.count().min(300) {
                if let Some((g, _)) = named.core.graph_at(k, false) {
                    if let Some(v) = named.core.view(g, 0, u64::MAX) {
                        let _ = v.match_pattern((None, None, None));
                    }
                }
            }
        }
        // A mask that disagrees with the header is refused.
        let named = QuadNamed::resident(enc.bytes.clone(), codec, PermSet::CORE);
        assert_eq!(named.count(), 0);
        assert!(named.load_incomplete());
    }

    #[test]
    fn seal_round_trips_and_refuses_garbage() {
        let d = digest(b"abc");
        assert_eq!(parse_seal(&encode_seal(d)).unwrap(), d);
        assert!(parse_seal(b"RQIX").is_err());
        let mut s = encode_seal(d);
        s[4] = 2;
        assert!(parse_seal(&s).is_err());
    }

    #[test]
    fn the_subject_column_is_the_one_coded_across_runs() {
        use IndexPermutation::*;
        for (perm, cols) in [
            (Spo, (false, false)),
            (Sop, (false, false)),
            (Pos, (false, true)),
            (Ops, (false, true)),
            (Osp, (true, false)),
            (Pso, (true, false)),
        ] {
            assert_eq!(subject_columns(perm), cols, "{}", perm.name());
        }
        // A segment whose subjects repeat across groups round-trips, and the
        // cross-run deltas make it smaller than coding each run from 0.
        let rows: Vec<QuadRow> = (0..40u32)
            .map(|k| (7, 100 + k, 5_000_000 + k * 977, 9_000_000 + k % 3))
            .collect();
        let (mut with, mut without) = (Vec::new(), Vec::new());
        encode_segment_body(&rows, (false, true), &mut with);
        encode_segment_body(&rows, (false, false), &mut without);
        assert!(with.len() < without.len());
        let mut back = Vec::new();
        decode_segment_body(&with, rows[0].1, (false, true), &mut back).unwrap();
        let want: Vec<Triple> = rows.iter().map(|r| (r.1, r.2, r.3)).collect();
        assert_eq!(back, want);
    }

    #[test]
    fn five_permutations_are_refused() {
        let five = PermSet::from_bits(0b0001_1111).unwrap();
        assert!(encode_quad_index(vec![[1, 1, 1, 1]], five, CODEC_NONE).is_err());
    }

    /// Every pattern shape, over every order set: the scan yields exactly the
    /// quads a filter over the input keeps, in graph order, and prunes tiles.
    #[test]
    fn a_quad_scan_finds_exactly_the_matching_quads() {
        let q = quads(5000, 10);
        let mut all: Vec<(u32, Triple)> = q.iter().map(|r| (r[0], (r[1], r[2], r[3]))).collect();
        all.sort_unstable();
        all.dedup();
        for perms in [PermSet::ALL, PermSet::CORE] {
            let enc = encode_quad_index(q.clone(), perms, writer_codec()).unwrap();
            let named = QuadNamed::resident(enc.bytes, writer_codec(), perms);
            let (_, (s, p, o)) = all[1234];
            for pat in [
                (None, None, None),
                (Some(s), None, None),
                (None, Some(p), None),
                (None, None, Some(o)),
                (Some(s), Some(p), None),
                (None, Some(p), Some(o)),
                (Some(s), None, Some(o)),
                (Some(s), Some(p), Some(o)),
                (Some(u32::MAX), None, None),
                (None, Some(999), None),
            ] {
                let want: Vec<(u32, Triple)> = all
                    .iter()
                    .copied()
                    .filter(|(_, (a, b, c))| {
                        pat.0.is_none_or(|x| x == *a)
                            && pat.1.is_none_or(|x| x == *b)
                            && pat.2.is_none_or(|x| x == *c)
                    })
                    .collect();
                let got: Vec<(u32, Triple)> = named.scan(pat).unwrap().collect();
                let graphs: Vec<u32> = got.iter().map(|r| r.0).collect();
                assert!(graphs.is_sorted(), "graph order for {pat:?}");
                let mut got = got;
                got.sort_unstable();
                assert_eq!(got, want, "{pat:?} over {} orders", perms.len());
            }
            assert!(!named.load_incomplete());
        }
    }

    /// Past the memo threshold the directory blocks are not all kept, and
    /// every lookup still answers the same.
    #[test]
    fn a_bounded_block_memo_answers_like_the_full_one() {
        let q = quads(6000, 3);
        let enc = encode_quad_index(q, PermSet::ALL, writer_codec()).unwrap();
        let full = QuadNamed::resident(enc.bytes.clone(), writer_codec(), PermSet::ALL);
        let mut bounded = QuadNamed::resident(enc.bytes, writer_codec(), PermSet::ALL);
        Arc::get_mut(&mut bounded.core).unwrap().memo_max_graphs = 0;
        assert_eq!(bounded.count(), full.count());
        for i in (0..full.count()).chain((0..full.count()).rev().step_by(97)) {
            assert_eq!(
                bounded.core.graph_at(i, false),
                full.core.graph_at(i, false),
                "ordinal {i}"
            );
        }
        for g in [2u32, 5000, 12000] {
            assert_eq!(bounded.core.ordinal_of(g), full.core.ordinal_of(g));
        }
        let kept = bounded
            .core
            .blocks
            .get()
            .unwrap()
            .iter()
            .filter(|c| c.get().is_some())
            .count();
        assert_eq!(kept, 0, "a bounded walk memoises no block");
        assert!(full
            .core
            .blocks
            .get()
            .unwrap()
            .iter()
            .any(|c| c.get().is_some()));
    }
}