rete-core 0.4.2

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
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
//! **External (chunked, memory-bounded) build**: assemble an arbitrarily large
//! single `.rete` file inside a caller-chosen memory budget by spilling sorted
//! intermediate artifacts to disk and merging them, instead of holding the whole
//! dictionary + id-triples + permutations in RAM (SPEC-compatible output;
//! byte-identical to [`crate::ingest::assemble_dataset_streaming_algo`] with the
//! pyramid disabled, text index included or not).
//!
//! ## How the budget bounds memory
//!
//! The input is consumed **once** and cut into K *chunks*, sealed whenever the
//! buffered quads' estimated resident bytes reach half the budget, or the
//! quads and the chunk's dictionary together reach 85% of it — so the budget
//! directly decides K (the "number of iterations"). Each chunk is assembled
//! with the ordinary in-RAM machinery (its own small dictionary, observed as
//! the quads arrive), then reduced to disk artifacts and dropped:
//!
//! ```text
//! input ─┬─ chunk 0: dict₀ → {shared,subj,obj,pred}₀ term files + triples₀ (local ids,
//!        │                    one sorted run)
//!        ├─ chunk 1: …          (+ graph₀ name file + quads₀ when named graphs exist)
//!        └─ chunk K: …          (+ c<i>.ocnt object counts with --frequent-objects)
//! top-N:  (`--frequent-objects N` only) k-way walk of the chunks' node terms
//!           → the N most frequent object-only terms (see "Frequent objects")
//! merge:  k-way term merge over all chunks
//!           → global front-coded dict sections (streamed to disk)
//!           → per-chunk id remap tables (local id → global id), appended to
//!             disk as the merge reaches each local id (`extbuild_remap`)
//!           → k-way merge of the graph-name files → global graph ordinals
//! remap:  one chunk's remap tables loaded at a time: its default triples,
//!           remapped to global ids, go straight into the first permutation's
//!           sorted runs; its named quads into (g, s, p, o) runs
//! index:  per permutation: k-way merge of its runs (dedup) → streaming tiler →
//!           independently compressed tiles on disk, and → the NEXT
//!           permutation's runs (the permutations are chained, see "Spill")
//! named:  the (g, s, p, o) runs merged — so every graph is one CONTIGUOUS RUN —
//!           then one index container per graph, in graph-name order, appended
//!           to a single spill file
//! text:   (`--text-index` only) each chunk's literal words → c<i>.tok, remapped
//!           with the same tables → global.tok, external sort by (token,
//!           subject) → the TEXT_INDEX section (`crate::text_index_spill`)
//! write:  header | metadata | dict | index | text index | named graphs |
//!           footer, hashed incrementally; each spilled section is deleted as
//!           soon as it is in the output
//! labels: (`--label-index`) the remap tees (object, slot, subject) ids; once
//!           the file is written its own dictionary names them, and the
//!           LABEL_INDEX and SCHEMA sections are appended (`extbuild_sections`)
//! card:   (the CLI: `build --memory-budget-mb --card…`, `merge`) the full card is
//!           derived by streaming the finished file's sorted sections and
//!           appended after them (`crate::recard::plan_card_append`); this
//!           module then writes no metadata at all
//! ```
//!
//! ## Spill
//!
//! Every spill file is compressed (`extbuild_spill`, G23): the statements as
//! sorted runs of delta-varint id tuples, the term files front-coded, the rest
//! as plain byte streams, all in zstd blocks at a fast level. On the
//! OpenCitations Meta sample the chunk statements take 1.6 B per statement
//! instead of 12, a sort run about 2 B, the term files 16% of their raw size.
//!
//! The permutations are **chained**: the remap writes the first permutation's
//! sorted runs directly (there is no `global.tri`), and each permutation's
//! merge, which reads its runs segment by segment and deletes each segment once
//! read, writes the next permutation's runs as it goes. So the statements are
//! on disk once at any time — up to 0.4.1 the permutation phase held a raw
//! `global.tri` plus one permutation's raw runs, 24 B per statement before any
//! index byte. The finished sections are copied into the output and deleted one
//! by one, so the write does not hold the index twice either.
//!
//! The merge deletes each chunk's term files once it has read them, the remap
//! each chunk's statements and remap tables once rewritten. Up to 0.4.1 the
//! peak was at the end of the dictionary merge; now it is usually in the last
//! permutations, where the finished sections — the index itself — are most of
//! it. Nothing of the label pass is on disk before the file is written.
//!
//! A build killed in the permutation phase can still be finished from its
//! spill (the `resume_from_spill` harness): every finished permutation's tiles
//! hold all the statements, sorted, so the chain restarts from the last one.
//! A kill in the first permutation cannot be: its runs are consumed as they
//! are merged, where up to 0.4.1 a raw `global.tri` survived to the end.
//!
//! Peak RAM ≈ max(one chunk's working set, the merge's read and write buffers,
//! one chunk's remap tables, one sort run, one named graph's index) — all
//! sized from `memory_budget`, never from the dataset:
//!
//! - a chunk is sealed when its quads reach half the budget, or earlier when
//!   its quads plus its dictionary — charged at twice the term bytes plus
//!   96 B per entry, what building it takes — reach 85% (G24: a term-dense
//!   stretch, two new terms per statement, used to take the chunk phase a
//!   quarter past the budget); its remap tables, 4 B per local id, are at
//!   most a quarter of the half (`extbuild_remap`);
//! - the merge reads every chunk's term files at once, one 64 KiB decoded
//!   block of each, and appends to every chunk's remap files at once, with
//!   buffers that shrink as the chunk count grows: a sixteenth of the budget,
//!   floored at 4 KiB per writer;
//! - a dictionary section's restart offsets (8 B per 16 terms) and chunk
//!   directory are spilled too, and its header streamed from them;
//! - a sort run holds a quarter of the budget in records (the text index's
//!   vectors may grow to half); a merge holds one decoded block per run, and
//!   while it runs, the next permutation's run being filled;
//! - what does grow with the data are the tile directories, about 30 B per
//!   64 KiB tile — tens of MB at billions of statements.
//!
//! Up to 0.4.0 every chunk's remap tables stayed resident from the merge to
//! the end of the remap, 4 B per chunk-local id: 15.0 GB at 1.73 B chunk-local
//! terms, which capped one OpenCitations Meta build at half the graph.
//!
//! ## Named graphs
//!
//! Graph names are **not** dictionary terms (the format stores them verbatim in
//! the named-graphs section), so they get their own per-chunk name file and
//! their own k-way merge, yielding a global **graph ordinal**. That ordinal is
//! the leading column of the named-quad spill, which makes the external sort do
//! the grouping for free: after the merge, each graph's triples arrive together
//! and its index is built from that run alone. One dictionary, one extra spill,
//! no per-graph files.
//!
//! The default graph keeps its own triple runs and its own sort, untouched —
//! so an input with no named graphs runs exactly the code (and the record
//! widths) it ran before this existed.
//!
//! ## Quad index (`GraphLayout::Quad`)
//!
//! Graph names **are** dictionary terms there (subject role), so the chunker
//! observes each name into its chunk dictionary and spills a named quad as
//! `(local subject id of g, s, p, o)`: no name file, no graph-ordinal merge;
//! the remap phase maps `g` like `s`. Then, per graph-leading order, one
//! external sort of `(g, a, b, c)` records (chained like the default graph's),
//! a k-way merge with dedup,
//! and the same `quad::QuadTiler` the in-RAM builder uses — so the two write
//! identical bytes. The `G+SPO` pass also emits the graph directory. The
//! section is assembled in a spill file (its digest goes into the index
//! container's seal) and streamed after the index. Peak RAM: one sort run plus
//! one tile batch.
//!
//!
//! ## Frequent objects (`--frequent-objects N`, G3)
//!
//! The in-RAM builder moves the `N` object-only terms carried by the most
//! statements (ties by term order) into the shared section. A chunk cannot
//! decide that: a term's frequency, and whether it is a subject somewhere, are
//! only known over the whole input. So with `N > 0` each chunk counts its
//! objects' statements and spills the counts of its object-only terms beside
//! its term file (`c<i>.ocnt`); before the merge, one more k-way walk over
//! the chunks' term files sums them, drops every term some chunk has as a
//! subject, and keeps the best `N` in a bounded heap. The merge then files
//! those terms in the shared section, in term order, as the in-RAM builder
//! does — so the file is the same bytes. The walk costs one more read of the
//! node term files and holds `N` terms.
//!
//! Limits (clear errors, not silent degradation): no community pyramid.
//! SPARQL/joins/verify are unaffected (they never require the pyramid). The
//! full-text index is supported, in any scope, and its section is byte-identical
//! to the in-RAM build's.

#![cfg(not(target_arch = "wasm32"))]

use std::collections::BinaryHeap;
use std::fs::File;
use std::io::{BufReader, BufWriter, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};

use crate::build_progress::{self as progress, Stat, Ticker, Unit};
use crate::build_trace::{self as trace, note_merge, Phase};
use crate::dict::env_restart_interval;

use crate::extbuild_remap::{
    remap_buf_bytes, role_only_id, shared_id, RemapStore, RemapWriter, Seg, SegCounts,
};
use crate::extbuild_sections::{ExtLabels, ExtSchema};
use crate::extbuild_spill::{
    self as spill, RunFile, RunReader, RunSpiller, TermReader, TermWriter, ZReader, ZWriter,
};
use crate::index::GroupSizer;
use crate::ingest::{BuildStats, GraphLayout, IngestError, RawQuad};
use crate::triples::TripleBlockBuilder;
use crate::varint::write_uvarint;
use crate::DictionaryBuilder;

/// An id-triple in a single permutation's ordering.
type IdTriple = (u32, u32, u32);
/// A tile synopsis: `(min_b, max_b, min_c, max_c)` over the tile's triples.
type Synopsis = (u32, u32, u32, u32);
/// Builds the metadata payload (the Dataset Card) once the counts are known.
/// Return an empty `Vec` for none — byte-identical to a metadata-free build.
pub type MetadataFn = Box<dyn FnOnce(&BuildStats) -> Vec<u8>>;
/// A distinct term with the `(chunk, local id)` pairs that carry it.
type TermCarriers = (String, Vec<(usize, u32)>);
/// One tile's directory entry: `(min_a, max_a, compressed length, synopsis)`.
type TileDirEntry = (u32, u32, u64, Synopsis);
/// One encoded tile: `(min_a, max_a, compressed bytes, synopsis)`.
type EncodedTile = (u32, u32, Vec<u8>, Synopsis);

/// Options for [`build_external`].
pub struct ExternalBuildOptions {
    /// Approximate peak-RAM target in bytes. Controls how many chunks the input
    /// is cut into and how large each external-sort run is. Not a hard cgroup
    /// limit — a working-set target the phases size themselves against.
    pub memory_budget: u64,
    /// Where intermediate spill files live (a `.rete-extbuild-<pid>` directory is
    /// created inside). Defaults to the output file's parent directory — same
    /// filesystem, no surprise `/tmp` exhaustion.
    pub tmp_dir: Option<PathBuf>,
    /// Metadata payload (the Dataset Card), derived after counts are known.
    pub metadata: MetadataFn,
    /// Build-conditions payload ([`crate::header::SectionKind::BuildInfo`]),
    /// written verbatim after the metadata section and **excluded from the
    /// content hash** — per-build facts (timestamp, builder, parameters) that
    /// must not make two builds of identical data hash differently. Empty =
    /// no section (byte-identical to a pre-build-info file).
    pub build_info: Vec<u8>,
    /// Which permutations to sort and write ([`crate::index::PermSet::ALL`] by
    /// default). Each one is a full external sort of every triple plus its own
    /// section on disk, so this is the single biggest lever on both build time
    /// and file size that does not touch the data.
    pub perms: crate::index::PermSet,
    /// Write the LABEL_INDEX section (kind 8). See `extbuild_sections.rs`.
    pub label_index: bool,
    /// Write the SCHEMA section (kind 9). See `extbuild_sections.rs`.
    pub schema: bool,
    /// The schema's type predicate; `rdf:type` when `None`.
    pub type_override: Option<String>,
    /// Build the full-text index over the literals of this scope (`None` = no
    /// TEXT_INDEX section). A second external sort, on the literal words, inside
    /// the same budget; see `text_index_spill`.
    pub text_index: Option<crate::text_index::TextIndexScope>,
    /// How the named graphs are stored ([`GraphLayout::PerGraph`] by default).
    /// [`GraphLayout::Quad`] writes the quad index (SPEC.md §6.5) through its
    /// own external sorts — see "Quad index" in the module docs.
    pub graphs: GraphLayout,
    /// Bytes of `memory_budget` the input stream itself holds while it is
    /// read — `rete merge`'s open shards, their dictionary, tile and block
    /// caches capped to it (G22). The chunk phase, the only one that runs
    /// while the stream is being read, sizes itself to the budget less this;
    /// every later phase has the whole budget. `0` (the default) for a
    /// parser, whose buffers are small.
    pub input_memory: u64,
}

impl Default for ExternalBuildOptions {
    fn default() -> Self {
        Self {
            memory_budget: 4 << 30,
            tmp_dir: None,
            metadata: Box::new(|_| Vec::new()),
            build_info: Vec::new(),
            perms: crate::index::PermSet::ALL,
            label_index: false,
            schema: false,
            type_override: None,
            text_index: None,
            graphs: GraphLayout::PerGraph,
            input_memory: 0,
        }
    }
}

#[cfg(test)]
thread_local! {
    /// `(chunk budget, text-index run bytes)` for tests that drive a small
    /// graph through [`build_external`] as many chunks and many sort runs —
    /// the public budget floor would otherwise make it one of each.
    pub(crate) static TEST_SPLIT: std::cell::Cell<Option<(u64, usize)>> = const { std::cell::Cell::new(None) };
    /// `(triple run, quad run)` lengths, in records, for tests that need many
    /// sort runs through [`build_external`].
    pub(crate) static TEST_RUNS: std::cell::Cell<Option<(usize, usize)>> = const { std::cell::Cell::new(None) };
    /// The chunk working-set cap ([`CHUNK_WORKING_FRACTION`] of the budget),
    /// for tests that make a small graph's dictionary seal its chunks.
    pub(crate) static TEST_WORKING: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
}

#[derive(Debug, thiserror::Error)]
pub enum ExtBuildError {
    #[error("ingest: {0}")]
    Ingest(#[from] IngestError),
    #[error("io: {0}")]
    Io(#[from] std::io::Error),
    #[error("internal: {0}")]
    Internal(&'static str),
}

/// Bytes charged against the budget per triple of a named graph held resident
/// while its index is built: the triple itself (12 B), the six permuted copies
/// `GraphIndexBuilder::build` keeps in flight, and the tiles they turn into.
/// Charged against **half** the budget, so the graph coexists with the merge
/// readers. A graph over the cap spills and takes the same external
/// per-permutation path the default graph always takes.
const NAMED_GRAPH_BYTES_PER_TRIPLE: u64 = 160;

/// Hard ceiling on a resident named graph, whatever the budget says. Mirrors
/// `ingest::LOWMEM_TRIPLE_THRESHOLD`: past it the in-RAM assembler stops
/// building all six permutations at once, and so does this — by spilling the
/// graph rather than by switching builders, which keeps one resident path.
const NAMED_GRAPH_RAM_TRIPLE_CAP: usize = 30_000_000;

/// Fraction of the budget a chunk's buffered raw quads may occupy before the
/// chunk is sealed. The rest covers the chunk's dictionary and its id-encode
/// working set, which [`CHUNK_WORKING_FRACTION`] bounds.
const CHUNK_BUDGET_FRACTION: f64 = 0.5;
/// Fraction of the budget a chunk's whole working set may reach before the
/// chunk is sealed (G24): its buffered quads plus its dictionary at the size
/// [`DictionaryBuilder::build`] briefly takes it to. On most graphs the quads
/// reach [`CHUNK_BUDGET_FRACTION`] first and nothing changes; on a term-dense
/// stretch — two new terms per statement, the OpenCitations Meta
/// `oc:doiLink` tail — the dictionary is the larger half, and up to 0.4.1 a
/// chunk sealed by bytes alone took the build 25% past its budget (14.99 GB
/// under a 16 GB cap at budget 12000; 1,348 MiB at 1,000 on a synthetic).
/// The rest of the budget is the program and the input's buffers.
const CHUNK_WORKING_FRACTION: f64 = 0.85;
/// Bytes charged per distinct dictionary entry (a term once for every role
/// set it is in), on top of twice its length, for a chunk's dictionary: the
/// hash-set slot it is observed into (24 B at most 7/8 full, in a
/// power-of-two table), the allocator's rounding, and what `build` adds while
/// it sorts and front-codes the terms — a `Vec` slot, the section builder's
/// copy of the string and its slot. Measured: 165 B per entry of 37-byte
/// terms, which `2 × 37 + 96` covers.
const DICT_ENTRY_OVERHEAD: u64 = 96;
/// Overhead charged per buffered quad on top of its term byte lengths (String
/// headers, Vec slot, allocator slack) when estimating chunk residency.
const PER_QUAD_OVERHEAD: u64 = 96;
/// Per-tile-batch size for parallel tile compression.
const TILE_COMPRESS_BATCH: usize = 512;

/// Build a `.rete` at `output` from a **single-pass** quad stream within
/// `opts.memory_budget`. Returns the same [`BuildStats`] as the in-RAM paths.
///
/// `stream` is invoked once; it must call the visitor for every quad.
pub fn build_external<S>(
    mut stream: S,
    output: &Path,
    opts: ExternalBuildOptions,
) -> Result<BuildStats, ExtBuildError>
where
    S: FnMut(&mut dyn FnMut(RawQuad) -> Result<(), ExtBuildError>) -> Result<(), ExtBuildError>,
{
    let tmp_parent = opts
        .tmp_dir
        .clone()
        .or_else(|| output.parent().map(|p| p.to_path_buf()))
        .unwrap_or_else(|| PathBuf::from("."));
    let tmp = TmpDir::create(&tmp_parent)?;
    progress::set_spill_dir(Some(&tmp.dir));
    let budget = opts.memory_budget.max(64 << 20); // floor: 64 MiB

    // ---- Phase 1: chunk the input ------------------------------------------
    // The input's own share (a merge's shard readers) is out of the chunks'.
    let chunk_phase = budget.saturating_sub(opts.input_memory).max(32 << 20);
    let chunk_budget = (chunk_phase as f64 * CHUNK_BUDGET_FRACTION) as u64;
    // A text-index sort run holds at most a quarter of the budget in records;
    // its vectors may grow to twice that, which is the half the phase may use.
    let text_run_bytes = (budget / 4) as usize;
    #[cfg(test)]
    let (chunk_budget, text_run_bytes) = TEST_SPLIT
        .with(|c| c.get())
        .unwrap_or((chunk_budget, text_run_bytes));
    let working_cap = (chunk_phase as f64 * CHUNK_WORKING_FRACTION) as u64;
    #[cfg(test)]
    let working_cap = TEST_WORKING.with(|c| c.get()).unwrap_or(working_cap);
    if opts.input_memory > 0 {
        eprintln!(
            "extbuild: budget {} MiB, {} MiB of it for reading the input -> chunk target {} MiB, \
             {} MiB with the chunk's dictionary",
            budget >> 20,
            opts.input_memory >> 20,
            chunk_budget >> 20,
            working_cap >> 20
        );
    } else {
        eprintln!(
            "extbuild: budget {} MiB -> chunk target {} MiB, {} MiB with the chunk's dictionary",
            budget >> 20,
            chunk_budget >> 20,
            working_cap >> 20
        );
    }
    let quad_layout = opts.graphs == GraphLayout::Quad;
    if quad_layout {
        crate::quad::check_perms(opts.perms).map_err(|_| {
            ExtBuildError::Internal("the quad index needs the 3- or 6-permutation set")
        })?;
    }
    let mut text = opts
        .text_index
        .clone()
        .map(crate::text_index_spill::TextSpill::new);
    // `--frequent-objects N` (G3): the chunks count their objects, and the
    // N most frequent object-only terms of the whole input are picked before
    // the merge, which files them in the shared section as the in-RAM
    // builder does.
    let promote = crate::write_opts::frequent_objects();
    let mut chunker = Chunker::new(&tmp, chunk_budget, opts.graphs)
        .with_working_cap(working_cap)
        .with_object_counts(promote > 0);
    chunker.text = text.as_mut();
    // LABEL_INDEX / SCHEMA (kinds 8, 9): the passes live in extbuild_sections;
    // each phase below calls one hook. Both work on global ids from the remap
    // on, so nothing of them is spilled beside the chunk files. A sort run
    // gets an eighth of the budget while the remap runs, a quarter once the
    // file is written.
    let mut ext_labels = opts
        .label_index
        .then(|| ExtLabels::new(&tmp.dir, (budget / 8) as usize));
    let mut ext_schema = opts.schema.then(|| {
        ExtSchema::new(
            &tmp.dir,
            (budget / 8) as usize,
            opts.type_override.as_deref(),
        )
    });
    // The caller's stream knows what bounds the parse (input bytes, or a
    // merge's statements) and sets the phase's total.
    progress::begin(Phase::ParseChunk, None, Unit::None);
    stream(&mut |q: RawQuad| chunker.push(q))?;
    let chunks = chunker.finish()?;
    let statements: u64 = chunks
        .iter()
        .map(|c| c.triple_count + c.quad_count)
        .sum::<u64>();
    progress::set_stat(Stat::Statements, statements);
    let has_named = chunks.iter().any(|c| c.quad_count > 0);
    eprintln!(
        "extbuild: {} chunk(s), {} statement(s) spilled",
        chunks.len(),
        statements
    );
    trace::add("chunks", chunks.len() as u64);
    note_scratch(&tmp);
    trace::lap(Phase::ParseChunk);

    // ---- Phase 2: merge chunk dictionaries into the global dictionary -------
    let promoted = if promote > 0 {
        let carriers = chunks.iter().map(|c| {
            let [shared, subj, obj, _] = c.section_terms;
            shared as u64 + subj as u64 + obj as u64
        });
        progress::begin(Phase::FrequentObjects, Some(carriers.sum()), Unit::Terms);
        let p = select_frequent_objects(&tmp, &chunks, promote)?;
        trace::lap(Phase::FrequentObjects);
        p
    } else {
        Vec::new()
    };
    // Every chunk-local term the merge meets: a shared one in the subject and
    // the object walks both.
    let carriers = chunks.iter().map(|c| {
        let [shared, subj, obj, pred] = c.section_terms;
        2 * shared as u64 + subj as u64 + obj as u64 + pred as u64 + c.graph_terms as u64
    });
    progress::begin(Phase::Dictionary, Some(carriers.sum()), Unit::Terms);
    let schema_preds = crate::extbuild_sections::schema_predicates(opts.type_override.as_deref());
    let (merged, remaps) =
        merge_dictionaries_with(&tmp, &chunks, &schema_preds, budget, &promoted)?;
    drop(promoted);
    if let Some(x) = ext_schema.as_mut() {
        x.set_merge_facts(&merged.schema_facts);
    }
    if let Some(l) = ext_labels.as_mut() {
        l.set_predicates(merged.schema_facts.label_preds.clone());
    }
    note_scratch(&tmp);
    trace::lap(Phase::Dictionary);
    progress::set_stat(Stat::Terms, merged.term_count);
    eprintln!(
        "extbuild: merged dictionary — {} term(s)",
        merged.term_count
    );
    if merged.graph_count > 0 {
        eprintln!("extbuild: {} named graph(s)", merged.graph_count);
    }

    // ---- Phase 3: remap chunk statements into the first sort runs -----------
    // A sort run holds R triples (12 B) or quads (16 B); with the vector's
    // growth slack that is up to twice over, so R·12·2 = budget/2 — and the
    // same for quads. Reusing `run_len` for quads would have quietly spent
    // 4/3 of the intended half-budget on the quad sort.
    let run_len = ((budget / 2) / 24).clamp(1 << 16, u32::MAX as u64) as usize;
    let quad_run_len = ((budget / 2) / 32).clamp(1 << 16, u32::MAX as u64) as usize;
    #[cfg(test)]
    let (run_len, quad_run_len) = TEST_RUNS
        .with(|c| c.get())
        .unwrap_or((run_len, quad_run_len));
    let first = opts
        .perms
        .iter()
        .next()
        .ok_or(ExtBuildError::Internal("no permutation to index"))?;
    if let Some(text) = text.as_mut() {
        text.begin_remap(tmp.path("global.tok"))?;
    }
    progress::begin(Phase::Encode, Some(statements), Unit::Statements);
    // The remap fills the triple and the quad runs at once: half each.
    let (remap_run_len, remap_quad_run_len) = if has_named {
        (run_len / 2, quad_run_len / 2)
    } else {
        (run_len, quad_run_len)
    };
    let (tri_runs, quad_runs) = remap_chunks(
        &tmp,
        &chunks,
        &remaps,
        quad_layout,
        first,
        remap_run_len,
        remap_quad_run_len,
        text.as_mut(),
        ext_schema.as_mut(),
        ext_labels.as_mut(),
    )?;
    note_scratch(&tmp);
    trace::lap(Phase::Encode);

    // ---- Phase 3b: the full-text index (`--text-index`) -----------------------
    let codec = crate::file::writer_codec();
    let text_section = match text {
        Some(t) => {
            progress::begin(Phase::TextIndex, None, Unit::None);
            let s = t.finish(&|name| tmp.path(name), text_run_bytes, codec)?;
            note_scratch(&tmp);
            trace::lap(Phase::TextIndex);
            s
        }
        None => None,
    };

    // ---- Phase 4: the permutations, chained ---------------------------------
    if let Some(x) = ext_schema.as_mut() {
        x.begin_spo()?;
    }
    // Each permutation merges the spilled default triples once (fewer after
    // the first, which drops duplicates): `done` steps to k·N as the k-th ends.
    let spilled: u64 = chunks.iter().map(|c| c.triple_count).sum();
    let perm_count = opts.perms.len() as u64;
    progress::begin(
        Phase::IndexPermutations,
        Some(perm_count * spilled),
        Unit::Records,
    );
    let mut perms_done = 0u64;
    let (perm_sections, default_count) = index_permutations(
        &tmp,
        tri_runs,
        opts.perms,
        run_len,
        codec,
        "",
        // The schema pass reads the deduplicated SPO and POS merge streams.
        &mut |perm, t| match (ext_schema.as_mut(), perm) {
            (Some(x), crate::index::IndexPermutation::Spo) => x.observe_spo(t),
            (Some(x), crate::index::IndexPermutation::Pos) => {
                x.observe_pos(t);
                Ok(())
            }
            _ => Ok(()),
        },
        &mut |perm, n| {
            eprintln!(
                "extbuild: permutation {} indexed ({} unique triple(s))",
                perm.name(),
                n
            );
            trace::lap(Phase::IndexPermutations);
            perms_done += 1;
            progress::set_done(perms_done * spilled);
        },
    )?;
    if let Some(x) = ext_schema.as_mut() {
        x.finish_links()?;
    }

    // ---- Phase 4b: one index container per named graph ----------------------
    // The graph ordinal leads the sort key, so the merge hands back one
    // contiguous run per graph, in graph-name order — exactly the order the
    // named-graphs section stores them in.
    // ---- Phase 4b (quad index): graph-leading orders over the quad runs -----
    if has_named {
        let quads: u64 = chunks.iter().map(|c| c.quad_count).sum();
        let passes = if quad_layout { perm_count } else { 1 };
        progress::begin(Phase::NamedGraphs, Some(passes * quads), Unit::Records);
    }
    let (quad, named) = if !has_named {
        (None, None)
    } else if quad_layout {
        let q = build_quad_section(&tmp, quad_runs, quad_run_len, opts.perms, codec)?;
        eprintln!(
            "extbuild: quad index — {} named graph(s), {} unique quad(s), {} byte(s)",
            q.graph_count, q.quad_count, q.len
        );
        (Some(q), None)
    } else {
        let ram_triples = (((budget / 2) / NAMED_GRAPH_BYTES_PER_TRIPLE).max(1) as usize)
            .min(NAMED_GRAPH_RAM_TRIPLE_CAP);
        let section = build_named_graphs(
            &tmp,
            quad_runs,
            merged
                .graph_names
                .as_deref()
                .ok_or(ExtBuildError::Internal("named quads without graph names"))?,
            merged.graph_count,
            run_len,
            ram_triples,
            opts.perms,
            codec,
        )?;
        eprintln!(
            "extbuild: {} named graph(s) indexed ({} unique quad(s))",
            section.count, section.triples
        );
        (None, Some(section))
    };
    if has_named {
        note_scratch(&tmp);
        trace::lap(Phase::NamedGraphs);
    }
    let named_triples = named.as_ref().map(|n| n.triples).unwrap_or(0)
        + quad.as_ref().map(|q| q.quad_count).unwrap_or(0);
    let named_graphs = named.as_ref().map(|n| n.count).unwrap_or(0)
        + quad.as_ref().map(|q| q.graph_count).unwrap_or(0);
    let quad_count = default_count + named_triples;

    // ---- Phase 5: stream the final file -------------------------------------
    // `statements` is what was INGESTED; `quad_count` is what the permutation
    // merge actually kept after dedup, and it is what the header records. The
    // metadata callback (the Dataset Card) has to see the latter, or a build
    // from input containing duplicates publishes a card that disagrees with its
    // own file. They are equal whenever the input has no duplicates, which is
    // why the gap went unnoticed.
    let mut stats = BuildStats {
        statements: quad_count as usize,
        default_triples: default_count as usize,
        named_graphs: named_graphs as usize,
        terms: merged.term_count as usize,
        pyramid_levels: 0,
    };
    let metadata = (opts.metadata)(&stats);
    if !metadata.is_empty() {
        // A caller that derives its card from the finished file (the CLI's
        // full card, appended after the data) laps the phase itself, later.
        trace::lap(Phase::CardDerive);
    }
    note_scratch(&tmp);
    progress::begin(Phase::Write, None, Unit::None);
    // Each section's spill file is deleted as soon as it is in the output, so
    // the two never stack — neither during the write nor in the label pass.
    write_final_file(
        output,
        &metadata,
        &opts.build_info,
        &merged,
        &perm_sections,
        text_section.as_ref(),
        named.as_ref(),
        quad.as_ref(),
        quad_count,
        codec,
        opts.perms,
        true,
    )?;
    stats.pyramid_levels = 0;
    note_scratch(&tmp);
    trace::lap(Phase::Write);

    // ---- Phase 6: LABEL_INDEX / SCHEMA, appended (outside the content hash) --
    // Both read the strings they name through the written file's dictionary.
    if ext_labels.is_some() || ext_schema.is_some() {
        progress::begin(Phase::LabelsSchema, None, Unit::None);
    }
    let label_section = match ext_labels {
        Some(l) => {
            let s = l
                .finish(output, (budget / 4) as usize, budget / 8, codec)
                .map_err(|e| ExtBuildError::Io(std::io::Error::other(e.to_string())))?;
            note_scratch(&tmp);
            s
        }
        None => None,
    };
    let schema_section = match ext_schema {
        Some(x) => x
            .finish(output)
            .map_err(|e| ExtBuildError::Io(std::io::Error::other(e.to_string())))?,
        None => Vec::new(),
    };
    if label_section.is_some() || !schema_section.is_empty() {
        use crate::file::PayloadPart;
        use crate::header::SectionKind;
        let mut sections: Vec<(SectionKind, Vec<PayloadPart<'_>>)> = Vec::new();
        if let Some(l) = &label_section {
            sections.push((
                SectionKind::LabelIndex,
                vec![
                    PayloadPart::Bytes(&l.digest_and_head),
                    PayloadPart::File(&l.body),
                ],
            ));
            eprintln!("extbuild: label index — {} entries", l.entries);
        }
        if !schema_section.is_empty() {
            sections.push((
                SectionKind::Schema,
                vec![PayloadPart::Bytes(&schema_section)],
            ));
            eprintln!("extbuild: schema section — {} bytes", schema_section.len());
        }
        crate::file::append_sections_to_file(output, &sections)
            .map_err(|e| ExtBuildError::Io(std::io::Error::other(e.to_string())))?;
        trace::lap(Phase::LabelsSchema);
    }
    progress::set_spill_dir(None);
    Ok(stats)
}

/// Raise the `scratch_peak_bytes` counter to what the spill directory holds
/// now. Sampled at phase boundaries (and once each external sort has written
/// its runs, its high-water mark), so it is a lower bound on the true peak.
/// Skipped — no directory walk — when no build trace is recording.
fn note_scratch(tmp: &TmpDir) {
    if !trace::active() {
        return;
    }
    fn walk(dir: &Path) -> u64 {
        let Ok(rd) = std::fs::read_dir(dir) else {
            return 0;
        };
        rd.flatten()
            .map(|e| match e.metadata() {
                Ok(m) if m.is_dir() => walk(&e.path()),
                Ok(m) => m.len(),
                Err(_) => 0,
            })
            .sum()
    }
    trace::max("scratch_peak_bytes", walk(&tmp.dir));
}

// ---------------------------------------------------------------------------
// tmp-dir guard
// ---------------------------------------------------------------------------

struct TmpDir {
    dir: PathBuf,
}

impl TmpDir {
    fn create(parent: &Path) -> Result<Self, std::io::Error> {
        // pid + a process-wide counter: two concurrent external builds in the
        // same process (or parallel tests) must never share a spill directory.
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir = parent.join(format!(".rete-extbuild-{}-{}", std::process::id(), seq));
        std::fs::create_dir_all(&dir)?;
        Ok(TmpDir { dir })
    }
    fn path(&self, name: &str) -> PathBuf {
        self.dir.join(name)
    }
}

impl Drop for TmpDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.dir);
    }
}

// ---------------------------------------------------------------------------
// Phase 1: chunking
// ---------------------------------------------------------------------------

struct ChunkInfo {
    /// default-graph statements in this chunk
    triple_count: u64,
    /// named-graph statements in this chunk
    quad_count: u64,
    /// term counts per section file, in file order (shared, subj, obj, pred)
    section_terms: [u32; 4],
    /// distinct graph names in this chunk (`c<i>.graph` term count)
    graph_terms: u32,
    /// the default-graph statements in chunk-local ids, one sorted run
    tri: RunFile,
    /// the named quads, `(graph, s, p, o)` in chunk-local ids, one sorted run
    /// (empty when the chunk has none)
    qtri: RunFile,
}

impl ChunkInfo {
    /// Local ids per remap segment ([`Seg`]): the section files' term counts,
    /// then the graph names.
    fn seg_counts(&self) -> SegCounts {
        let [shared, subj, obj, pred] = self.section_terms;
        [shared, subj, obj, pred, self.graph_terms]
    }
}

struct Chunker<'a> {
    tmp: &'a TmpDir,
    chunk_budget: u64,
    acc_bytes: u64,
    /// The chunk is also sealed once its quads plus its dictionary's charge
    /// ([`Chunker::dict_charge`]) reach this (G24).
    working_cap: u64,
    /// The chunk's dictionary, observed quad by quad as it is pushed, so its
    /// size is known before it is built.
    db: DictionaryBuilder,
    /// Chunks sealed by [`Chunker::working_cap`] before their quads reached
    /// `chunk_budget`.
    term_sealed: u64,
    /// `--frequent-objects` (G3): count every object's statements and spill
    /// the counts of the chunk's object-only terms (`c<i>.ocnt`), for
    /// [`select_frequent_objects`].
    count_objects: bool,
    quads: Vec<(String, String, String)>,
    /// named-graph statements: `(chunk-local graph id, s, p, o)`. The graph is
    /// interned rather than cloned per quad — fedlex averages ~113 quads per
    /// graph, so storing the name once instead of 113 times is the difference
    /// between the buffer being bounded by distinct graphs and by statements.
    named: Vec<(u32, String, String, String)>,
    /// graph name → chunk-local *insertion* id (ranked at seal)
    graph_ids: std::collections::BTreeMap<String, u32>,
    chunks: Vec<ChunkInfo>,
    has_quoted: bool,
    /// `--text-index`: each sealed chunk spills its literal words here.
    text: Option<&'a mut crate::text_index_spill::TextSpill>,
    /// Quad index: graph names are subject terms of the chunk dictionary and
    /// a named quad's graph id is the name's local subject id.
    quad: bool,
}

impl<'a> Chunker<'a> {
    fn new(tmp: &'a TmpDir, chunk_budget: u64, graphs: GraphLayout) -> Self {
        Chunker {
            tmp,
            chunk_budget,
            acc_bytes: 0,
            working_cap: u64::MAX,
            db: Self::new_builder(false),
            term_sealed: 0,
            count_objects: false,
            quads: Vec::new(),
            named: Vec::new(),
            graph_ids: std::collections::BTreeMap::new(),
            chunks: Vec::new(),
            has_quoted: false,
            text: None,
            quad: graphs == GraphLayout::Quad,
        }
    }

    /// Seal a chunk once its quads and its dictionary together reach `cap`
    /// bytes, whichever of the two limits comes first.
    fn with_working_cap(mut self, cap: u64) -> Self {
        self.working_cap = cap;
        self
    }

    /// Count the objects' statements for `--frequent-objects` (G3).
    fn with_object_counts(mut self, on: bool) -> Self {
        self.count_objects = on;
        self.db = Self::new_builder(on);
        self
    }

    /// A chunk's dictionary is built from role-classified terms only:
    /// frequent-object promotion is decided over the whole input, once every
    /// chunk's counts are in ([`select_frequent_objects`]); a chunk only
    /// counts.
    fn new_builder(count_objects: bool) -> DictionaryBuilder {
        let b = DictionaryBuilder::default();
        if count_objects {
            b.with_object_counts()
        } else {
            b
        }
    }

    /// What the chunk's dictionary costs at its largest, while `build` turns
    /// the observed sets into sections: about twice the term bytes plus
    /// [`DICT_ENTRY_OVERHEAD`] per entry (16 B more for a counted entry's
    /// count, in the map and in the sorted pairs).
    fn dict_charge(&self) -> u64 {
        let (entries, bytes) = self.db.footprint();
        let per_entry = DICT_ENTRY_OVERHEAD + if self.count_objects { 16 } else { 0 };
        2 * bytes + per_entry * entries
    }

    fn push(&mut self, q: RawQuad) -> Result<(), ExtBuildError> {
        let (s, p, o, g) = q;
        self.acc_bytes += (s.len() + p.len() + o.len()) as u64 + PER_QUAD_OVERHEAD;
        // Graph NAMES are not dictionary terms — the format stores them
        // verbatim in the named-graphs section — but the s/p/o of a named
        // quad are, and the in-RAM builder observes them from the same single
        // pass.
        self.db.observe(&s, &p, &o);
        match g {
            None => self.quads.push((s, p, o)),
            Some(graph) => {
                let next = self.graph_ids.len() as u32 + 1;
                let gid = match self.graph_ids.get(&graph) {
                    Some(&id) => id,
                    None => {
                        // first sight in this chunk: the name itself is charged
                        // once, the per-quad cost is the 4-byte id above
                        self.acc_bytes += graph.len() as u64 + PER_QUAD_OVERHEAD;
                        // ...except in the quad index, where it is a subject
                        // term
                        if self.quad {
                            self.db.observe_graph(&graph);
                        }
                        self.graph_ids.insert(graph, next);
                        next
                    }
                };
                self.named.push((gid, s, p, o));
            }
        }
        if self.acc_bytes >= self.chunk_budget {
            self.seal()?;
        } else if self.acc_bytes + self.dict_charge() >= self.working_cap {
            self.term_sealed += 1;
            self.seal()?;
        }
        Ok(())
    }

    /// Build this chunk's private dictionary, spill its four sorted section term
    /// files + local-id triples (+ the graph name file and named quads when the
    /// chunk saw any), then drop everything.
    fn seal(&mut self) -> Result<(), ExtBuildError> {
        if self.quads.is_empty() && self.named.is_empty() {
            return Ok(());
        }
        let ci = self.chunks.len();
        let quads = std::mem::take(&mut self.quads);
        let named = std::mem::take(&mut self.named);
        let graph_ids = std::mem::take(&mut self.graph_ids);
        self.acc_bytes = 0;

        // The terms were observed as the quads were pushed (see `push`).
        let db = std::mem::replace(&mut self.db, Self::new_builder(self.count_objects));
        let (dict, object_counts) = db.build_counted();
        // `--frequent-objects`: the statements carrying each object-only term,
        // in the order of `c<i>.obj`.
        if self.count_objects {
            if object_counts.len() != dict.object_only_count() as usize {
                return Err(ExtBuildError::Internal(
                    "object counts do not match the object-only section",
                ));
            }
            let mut w = ZWriter::create(&self.tmp.path(&format!("c{ci}.ocnt")))?;
            let mut rec = Vec::with_capacity(10);
            for n in object_counts {
                rec.clear();
                write_uvarint(&mut rec, n);
                w.write_all(&rec)?;
            }
            w.finish()?;
        }
        if dict.has_quoted_triples() {
            self.has_quoted = true;
        }
        // `--text-index`: the chunk's literal words, keyed by chunk-local subject
        // ids, while the raw strings and their dictionary are both in hand.
        if let Some(text) = self.text.as_mut() {
            text.spill_chunk(&self.tmp.path(&format!("c{ci}.tok")), &dict, &quads, &named)?;
        }

        // Local id-triples (subject-space id, predicate id, object-space id),
        // spilled as one sorted run: sorted ids delta-encode to a fraction of
        // their 12 bytes, and nothing downstream depends on the input order.
        // Consuming `quads` frees each statement's strings as its ids are
        // taken, so the id vector never stacks on top of them.
        let triple_count = quads.len() as u64;
        let mut ids: Vec<IdTriple> = Vec::with_capacity(quads.len());
        for (s, p, o) in quads {
            ids.push(
                dict.encode(&s, &p, &o)
                    .ok_or(ExtBuildError::Internal("chunk term missing from own dict"))?,
            );
        }
        let tri = spill::spill_sorted_run(&self.tmp.path(&format!("c{ci}.tri")), &mut ids)?;
        drop(ids);

        // Named quads: the chunk-local graph id is the name's RANK in this
        // chunk's sorted name file, so `c<i>.graph` and the ids in `c<i>.qtri`
        // agree and the same k-way machinery that merges terms merges graphs.
        // (Graph names are NT tokens — an IRI or a blank node — so they never
        // contain a raw \n, the same property the term files rely on.)
        let quad_count = named.len() as u64;
        let graphs_seen = graph_ids.len();
        let graph_terms = if self.quad { 0 } else { graph_ids.len() as u32 };
        // The graph column of a named quad: in the quad index the name's
        // local subject id, remapped later exactly like a subject; otherwise
        // the name's RANK in this chunk's sorted name file, so `c<i>.graph`
        // and the ids in `c<i>.qtri` agree and the same k-way machinery that
        // merges terms merges graphs.
        let mut gcol = vec![0u32; graph_ids.len() + 1];
        if !named.is_empty() && self.quad {
            for (name, insertion_id) in &graph_ids {
                gcol[*insertion_id as usize] = dict
                    .subject_id(name)
                    .ok_or(ExtBuildError::Internal("graph name missing from own dict"))?;
            }
        } else if !named.is_empty() {
            let mut gw = TermWriter::create(&self.tmp.path(&format!("c{ci}.graph")))?;
            for (rank, (name, insertion_id)) in graph_ids.iter().enumerate() {
                gcol[*insertion_id as usize] = rank as u32 + 1;
                gw.push(name)?;
            }
            gw.finish()?;
        }
        let mut qids: Vec<IdQuad> = Vec::with_capacity(named.len());
        for (gid, s, p, o) in named {
            let (si, pi, oi) = dict
                .encode(&s, &p, &o)
                .ok_or(ExtBuildError::Internal("chunk term missing from own dict"))?;
            qids.push((gcol[gid as usize], si, pi, oi));
        }
        let qtri = spill::spill_sorted_run(&self.tmp.path(&format!("c{ci}.qtri")), &mut qids)?;
        drop(qids);

        // four sorted section term files, front-coded
        let shared = dict.shared_count();
        let subj_only = dict.subject_only_count();
        let obj_only = dict.object_only_count();
        let preds = {
            let mut n = 1u32;
            while dict.predicate_term(n).is_some() {
                n += 1;
            }
            n - 1
        };
        let write_terms = |name: &str,
                           count: u32,
                           term_of: &dyn Fn(u32) -> Option<String>|
         -> Result<(), ExtBuildError> {
            let mut w = TermWriter::create(&self.tmp.path(name))?;
            for i in 1..=count {
                let t = term_of(i).ok_or(ExtBuildError::Internal("dict id out of range"))?;
                w.push(&t)?;
            }
            w.finish()?;
            Ok(())
        };
        write_terms(&format!("c{ci}.shared"), shared, &|i| dict.subject_term(i))?;
        write_terms(&format!("c{ci}.subj"), subj_only, &|i| {
            dict.subject_term(shared + i)
        })?;
        write_terms(&format!("c{ci}.obj"), obj_only, &|i| {
            dict.object_term(shared + i)
        })?;
        write_terms(&format!("c{ci}.pred"), preds, &|i| dict.predicate_term(i))?;

        progress::set_stat(Stat::Chunks, ci as u64 + 1);
        eprintln!(
            "extbuild: chunk {ci} sealed — {} statement(s), {} term(s), {graphs_seen} graph(s)",
            triple_count + quad_count,
            shared + subj_only + obj_only + preds
        );
        self.chunks.push(ChunkInfo {
            triple_count,
            quad_count,
            section_terms: [shared, subj_only, obj_only, preds],
            graph_terms,
            tri,
            qtri,
        });
        Ok(())
    }

    fn finish(mut self) -> Result<Vec<ChunkInfo>, ExtBuildError> {
        self.seal()?;
        if self.term_sealed > 0 {
            eprintln!(
                "extbuild: {} of {} chunk(s) sealed by their dictionary's size before their quads' \
                 (a term-dense stretch)",
                self.term_sealed,
                self.chunks.len()
            );
            trace::add("chunks_term_sealed", self.term_sealed);
        }
        if self.chunks.is_empty() {
            // an empty input still produces one (empty) chunk so downstream
            // phases have a well-formed shape to merge
            self.chunks.push(ChunkInfo {
                triple_count: 0,
                quad_count: 0,
                section_terms: [0, 0, 0, 0],
                graph_terms: 0,
                tri: spill::write_run::<IdTriple>(&self.tmp.path("c0.tri"), &[])?,
                qtri: spill::write_run::<IdQuad>(&self.tmp.path("c0.qtri"), &[])?,
            });
            for name in ["c0.shared", "c0.subj", "c0.obj", "c0.pred"] {
                File::create(self.tmp.path(name))?;
            }
        }
        Ok(self.chunks)
    }
}

// ---------------------------------------------------------------------------
// Phase 2: global dictionary merge
// ---------------------------------------------------------------------------

struct MergedDict {
    /// The four chunked-encoded dict section payloads, spilled to tmp files
    /// (shared, subjects, objects, predicates — the container order).
    section_files: [SectionFile; 4],
    term_count: u64,
    has_quoted: bool,
    /// Every distinct graph name, ascending, one per line — spilled rather than
    /// resident because fedlex has 497,905 of them. `None` when the input had
    /// no named graphs.
    graph_names: Option<PathBuf>,
    graph_count: u32,
    /// What the SCHEMA pass needs from the merge.
    schema_facts: crate::extbuild_sections::MergeFacts,
}

/// A finished section payload living in a tmp file.
struct SectionFile {
    path: PathBuf,
    len: u64,
}

/// One chunk's contribution to a term-space merge: an iterator over
/// `(term, local_space_id)` in ascending term order. Subject space enumerates
/// shared then subject-only ids interleaved back into term order.
struct SpaceStream {
    a: TermFileReader, // shared section
    b: TermFileReader, // role-only section
    a_base: u32,       // shared ids are 1..=shared
    b_base: u32,       // role-only ids are shared+1..
    a_next: Option<String>,
    b_next: Option<String>,
    a_rank: u32,
    b_rank: u32,
}

impl SpaceStream {
    fn new(a: TermFileReader, b: TermFileReader, shared: u32) -> Result<Self, std::io::Error> {
        let mut s = SpaceStream {
            a,
            b,
            a_base: 0,
            b_base: shared,
            a_next: None,
            b_next: None,
            a_rank: 0,
            b_rank: 0,
        };
        s.a_next = s.a.next()?;
        s.b_next = s.b.next()?;
        Ok(s)
    }

    /// Next `(term, local_space_id)` in ascending term order.
    fn next(&mut self) -> Result<Option<(String, u32)>, std::io::Error> {
        let take_a = match (&self.a_next, &self.b_next) {
            (None, None) => return Ok(None),
            (Some(_), None) => true,
            (None, Some(_)) => false,
            // sections are disjoint, so strict ordering decides
            (Some(x), Some(y)) => x < y,
        };
        if take_a {
            let t = self.a_next.take().unwrap();
            self.a_rank += 1;
            let id = self.a_base + self.a_rank;
            self.a_next = self.a.next()?;
            Ok(Some((t, id)))
        } else {
            let t = self.b_next.take().unwrap();
            self.b_rank += 1;
            let id = self.b_base + self.b_rank;
            self.b_next = self.b.next()?;
            Ok(Some((t, id)))
        }
    }
}

/// Reader over a chunk's sorted, front-coded term file ([`TermWriter`]).
struct TermFileReader(TermReader);

impl TermFileReader {
    fn open(path: &Path) -> Result<Self, std::io::Error> {
        TermReader::open(path).map(TermFileReader)
    }

    /// Deleting the file once it has been read to its end: the dictionary
    /// merge opens every chunk's term files at once and gives a chunk's space
    /// back as soon as the merge is past its last term rather than when every
    /// chunk is done. (A shared-section file is read twice, by the subject and
    /// the object stream; its space comes back when the second one closes.)
    /// Each reader holds one decoded block, [`spill::BYTE_BLOCK`].
    fn open_consuming(path: &Path) -> Result<Self, std::io::Error> {
        TermReader::open_consuming(path).map(TermFileReader)
    }

    fn next(&mut self) -> Result<Option<String>, std::io::Error> {
        self.0.next()
    }
}

/// Heap entry for the k-way term merge (min-heap by term, then chunk index for
/// determinism).
struct HeapEntry {
    term: String,
    chunk: usize,
    local_id: u32,
}
impl PartialEq for HeapEntry {
    fn eq(&self, other: &Self) -> bool {
        self.term == other.term && self.chunk == other.chunk
    }
}
impl Eq for HeapEntry {}
impl PartialOrd for HeapEntry {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for HeapEntry {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // BinaryHeap is a max-heap; invert for ascending term order
        other
            .term
            .cmp(&self.term)
            .then_with(|| other.chunk.cmp(&self.chunk))
    }
}

/// K-way merged view over one term space (subject or object) of every chunk:
/// yields each distinct term once, ascending, with every `(chunk, local_id)`
/// that carries it.
struct KWayTerms {
    heap: BinaryHeap<HeapEntry>,
    streams: Vec<SpaceStream>,
    /// Counts the carriers met, for `--progress`.
    ticker: Ticker,
}

impl KWayTerms {
    fn new(mut streams: Vec<SpaceStream>) -> Result<Self, std::io::Error> {
        note_merge(streams.len());
        let mut heap = BinaryHeap::new();
        for (ci, s) in streams.iter_mut().enumerate() {
            if let Some((term, id)) = s.next()? {
                heap.push(HeapEntry {
                    term,
                    chunk: ci,
                    local_id: id,
                });
            }
        }
        Ok(KWayTerms {
            heap,
            streams,
            ticker: Ticker::new(),
        })
    }

    /// Next distinct term with its (chunk, local_id) carriers.
    fn next(&mut self) -> Result<Option<TermCarriers>, std::io::Error> {
        let first = match self.heap.pop() {
            Some(e) => e,
            None => return Ok(None),
        };
        let term = first.term;
        let mut carriers = vec![(first.chunk, first.local_id)];
        if let Some((t, id)) = self.streams[first.chunk].next()? {
            self.heap.push(HeapEntry {
                term: t,
                chunk: first.chunk,
                local_id: id,
            });
        }
        while let Some(top) = self.heap.peek() {
            if top.term != term {
                break;
            }
            let e = self.heap.pop().unwrap();
            carriers.push((e.chunk, e.local_id));
            if let Some((t, id)) = self.streams[e.chunk].next()? {
                self.heap.push(HeapEntry {
                    term: t,
                    chunk: e.chunk,
                    local_id: id,
                });
            }
        }
        self.ticker.tick(carriers.len() as u64);
        Ok(Some((term, carriers)))
    }
}

#[cfg(test)]
fn merge_dictionaries(
    tmp: &TmpDir,
    chunks: &[ChunkInfo],
) -> Result<(MergedDict, RemapStore), ExtBuildError> {
    merge_dictionaries_with(tmp, chunks, &[], 64 << 20, &[])
}

/// A candidate of [`select_frequent_objects`], ordered **worst first**: fewer
/// statements, then the later term — so a max-heap of them keeps the one to
/// evict on top.
struct Frequent {
    count: u64,
    term: String,
}

impl Frequent {
    /// Whether a term carried by `count` statements comes ahead of this one
    /// in the in-RAM builder's order: more statements, ties by term order
    /// (`DictionaryBuilder::build`).
    fn is_beaten_by(&self, count: u64, term: &str) -> bool {
        count > self.count || (count == self.count && term < self.term.as_str())
    }
}

impl PartialEq for Frequent {
    fn eq(&self, other: &Self) -> bool {
        self.count == other.count && self.term == other.term
    }
}
impl Eq for Frequent {}
impl PartialOrd for Frequent {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for Frequent {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        other
            .count
            .cmp(&self.count)
            .then_with(|| self.term.cmp(&other.term))
    }
}

/// `--frequent-objects n` in the memory-bounded build (G3): the `n` object-only
/// terms of the whole input carried by the most statements, ties by term
/// order — the terms [`DictionaryBuilder::build`] promotes into the shared
/// section, so the merge can file them there and the file is the in-RAM
/// build's. Returned in term order.
///
/// A term's count is the sum of its chunks' counts (`c<i>.ocnt`, one per
/// chunk-local object-only term): every statement was observed in exactly one
/// chunk, duplicates included, as the in-RAM builder observes them. A term
/// object-only in its chunks may still be a subject in another, so the walk
/// over the object-only terms runs beside one over every chunk's subject
/// space, and a term found there is no candidate. One more read of the
/// chunks' node term files, one decoded block per file; `n` terms resident.
fn select_frequent_objects(
    tmp: &TmpDir,
    chunks: &[ChunkInfo],
    n: usize,
) -> Result<Vec<String>, ExtBuildError> {
    let empty = tmp.path("ocnt.empty");
    File::create(&empty)?;
    let mut subj_streams = Vec::with_capacity(chunks.len());
    let mut obj_streams = Vec::with_capacity(chunks.len());
    let mut counts = Vec::with_capacity(chunks.len());
    for (ci, c) in chunks.iter().enumerate() {
        let open = |suffix: &str| TermFileReader::open(&tmp.path(&format!("c{ci}.{suffix}")));
        subj_streams.push(SpaceStream::new(
            open("shared")?,
            open("subj")?,
            c.section_terms[0],
        )?);
        obj_streams.push(SpaceStream::new(
            open("obj")?,
            TermFileReader::open(&empty)?,
            c.section_terms[2],
        )?);
        let path = tmp.path(&format!("c{ci}.ocnt"));
        counts.push(if c.section_terms[2] > 0 {
            Some(ZReader::open_consuming(&path)?)
        } else {
            let _ = std::fs::remove_file(&path);
            None
        });
    }
    // The next local id each chunk's object-only stream must yield: the
    // counts are matched to the terms by position.
    let mut next_local = vec![1u32; chunks.len()];
    let mut subjects = KWayTerms::new(subj_streams)?;
    let mut objects = KWayTerms::new(obj_streams)?;
    let mut subject = subjects.next()?;
    let mut top: BinaryHeap<Frequent> = BinaryHeap::with_capacity(n + 1);
    let mut candidates = 0u64;
    while let Some((term, carriers)) = objects.next()? {
        // Every carrier's count, in order, whether or not the term qualifies:
        // the count files are read in step with the term files.
        let mut count = 0u64;
        for (ci, local) in carriers {
            let r = counts[ci]
                .as_mut()
                .ok_or(ExtBuildError::Internal("object counts missing for a chunk"))?;
            let c = spill::read_stream_varint(r)?.ok_or(ExtBuildError::Internal(
                "object counts end before the object-only terms",
            ))?;
            if local != next_local[ci] {
                return Err(ExtBuildError::Internal(
                    "object-only terms out of step with their counts",
                ));
            }
            next_local[ci] += 1;
            count += c;
        }
        while subject
            .as_ref()
            .is_some_and(|(s, _)| s.as_str() < term.as_str())
        {
            subject = subjects.next()?;
        }
        if subject.as_ref().is_some_and(|(s, _)| *s == term) {
            continue; // a subject somewhere: shared, not object-only
        }
        candidates += 1;
        if top.len() < n {
            top.push(Frequent { count, term });
        } else if top
            .peek()
            .is_some_and(|worst| worst.is_beaten_by(count, &term))
        {
            top.pop();
            top.push(Frequent { count, term });
        }
    }
    for r in counts.iter_mut().flatten() {
        if spill::read_stream_varint(r)?.is_some() {
            return Err(ExtBuildError::Internal(
                "object counts outlast the object-only terms",
            ));
        }
    }
    let _ = std::fs::remove_file(&empty);
    let mut promoted: Vec<Frequent> = top.into_vec();
    promoted.sort_unstable_by(|a, b| a.term.cmp(&b.term));
    let least = promoted.iter().map(|f| f.count).min().unwrap_or(0);
    eprintln!(
        "extbuild: frequent objects — {} of {candidates} object-only term(s) promoted to the \
         shared section (each in at least {least} statement(s))",
        promoted.len()
    );
    Ok(promoted.into_iter().map(|f| f.term).collect())
}

/// [`merge_dictionaries`], also recording what the SCHEMA pass needs: the
/// global ids of `schema_preds`, the shared-term count and the literal
/// prefixes of the shared and object-only sections. `budget` sizes the
/// buffers of the merge's per-chunk readers and remap writers.
///
/// Returns the merged dictionary and every chunk's id remap tables, which are
/// written to disk while the merge reaches each chunk-local id (see
/// [`crate::extbuild_remap`]): within one remap segment of one chunk the
/// merge meets the local ids in increasing order, so each table is a file of
/// sequential appends.
///
/// `promoted` ([`select_frequent_objects`], in term order) are object-only
/// terms filed in the shared section, where their order puts them, as the
/// in-RAM builder files the frequent objects it promotes.
fn merge_dictionaries_with(
    tmp: &TmpDir,
    chunks: &[ChunkInfo],
    schema_preds: &[String],
    budget: u64,
    promoted: &[String],
) -> Result<(MergedDict, RemapStore), ExtBuildError> {
    let k = chunks.len();
    // The next promoted term the object-only merge will meet.
    let mut next_promoted = promoted.iter().peekable();
    let mut schema_facts = crate::extbuild_sections::MergeFacts {
        pred_ids: vec![None; schema_preds.len()],
        ..Default::default()
    };

    // The node merge reads four term files per chunk at once (shared twice,
    // subject-only, object-only), one decoded block of each in memory.
    let counts: Vec<SegCounts> = chunks.iter().map(ChunkInfo::seg_counts).collect();
    let mut remaps = RemapWriter::new(&tmp.dir, &counts, remap_buf_bytes(budget, k));
    // A chunk-local id of the subject or object space at or below this is in
    // the chunk's shared section, the same id in both spaces.
    let shared_of = |ci: usize| chunks[ci].section_terms[0];

    // subject-space + object-space k-way streams
    let mut subj_streams = Vec::with_capacity(k);
    let mut obj_streams = Vec::with_capacity(k);
    for (ci, c) in chunks.iter().enumerate() {
        let open =
            |suffix: &str| TermFileReader::open_consuming(&tmp.path(&format!("c{ci}.{suffix}")));
        // Both readers of the shared file open before either stream reads:
        // a stream deletes its file at the end, and an empty one ends at once.
        let (shared_s, shared_o) = (open("shared")?, open("shared")?);
        subj_streams.push(SpaceStream::new(
            shared_s,
            open("subj")?,
            c.section_terms[0],
        )?);
        obj_streams.push(SpaceStream::new(
            shared_o,
            open("obj")?,
            c.section_terms[0],
        )?);
    }
    let mut subjects = KWayTerms::new(subj_streams)?;
    let mut objects = KWayTerms::new(obj_streams)?;

    // The three node sections are written as raw front-coded bodies first; the
    // final chunked encoding needs term counts, so bodies spill to tmp.
    let mut shared_sec = RawSectionWriter::create(tmp.path("g.shared.raw"))?;
    let mut subj_sec = RawSectionWriter::create(tmp.path("g.subj.raw"))?;
    let mut obj_sec = RawSectionWriter::create(tmp.path("g.obj.raw"))?;
    let mut has_quoted = false;

    let mut ranks = [0u32; 3]; // shared, subj-only, obj-only
    let mut s_item = subjects.next()?;
    let mut o_item = objects.next()?;
    loop {
        enum Class {
            Shared,
            SubjOnly,
            ObjOnly,
        }
        let class = match (&s_item, &o_item) {
            (None, None) => break,
            (Some(_), None) => Class::SubjOnly,
            (None, Some(_)) => Class::ObjOnly,
            (Some((st, _)), Some((ot, _))) => match st.cmp(ot) {
                std::cmp::Ordering::Less => Class::SubjOnly,
                std::cmp::Ordering::Greater => Class::ObjOnly,
                std::cmp::Ordering::Equal => Class::Shared,
            },
        };
        match class {
            Class::Shared => {
                let (term, s_carriers) = s_item.take().unwrap();
                let (_, o_carriers) = o_item.take().unwrap();
                // A shared id is final at once: shared ids lead both spaces.
                let id = shared_id(ranks[0])?;
                for (ci, lid) in s_carriers {
                    match lid.checked_sub(shared_of(ci)) {
                        None | Some(0) => remaps.push(ci, Seg::Shared, lid, id)?,
                        Some(rel) => remaps.push(ci, Seg::SubjOnly, rel, id)?,
                    }
                }
                for (ci, lid) in o_carriers {
                    match lid.checked_sub(shared_of(ci)) {
                        // shared in its chunk too: written from the subject side
                        None | Some(0) => {}
                        Some(rel) => remaps.push(ci, Seg::ObjOnly, rel, id)?,
                    }
                }
                has_quoted |= term.starts_with("<<");
                if term.starts_with('"') {
                    schema_facts.shared_literals += 1;
                }
                shared_sec.push(&term)?;
                ranks[0] += 1;
                s_item = subjects.next()?;
                o_item = objects.next()?;
            }
            Class::SubjOnly => {
                let (term, carriers) = s_item.take().unwrap();
                let id = role_only_id(ranks[1])?;
                for (ci, lid) in carriers {
                    match lid.checked_sub(shared_of(ci)) {
                        Some(rel) if rel > 0 => remaps.push(ci, Seg::SubjOnly, rel, id)?,
                        _ => {
                            return Err(ExtBuildError::Internal(
                                "a chunk-shared term merged as subject-only",
                            ))
                        }
                    }
                }
                has_quoted |= term.starts_with("<<");
                subj_sec.push(&term)?;
                ranks[1] += 1;
                s_item = subjects.next()?;
            }
            Class::ObjOnly => {
                let (term, carriers) = o_item.take().unwrap();
                // A promoted frequent object (G3) takes the next shared id, in
                // term order among the shared terms, and never a subject's.
                let promote = next_promoted.next_if(|p| **p == term).is_some();
                let id = if promote {
                    shared_id(ranks[0])?
                } else {
                    role_only_id(ranks[2])?
                };
                for (ci, lid) in carriers {
                    match lid.checked_sub(shared_of(ci)) {
                        Some(rel) if rel > 0 => remaps.push(ci, Seg::ObjOnly, rel, id)?,
                        _ => {
                            return Err(ExtBuildError::Internal(
                                "a chunk-shared term merged as object-only",
                            ))
                        }
                    }
                }
                has_quoted |= term.starts_with("<<");
                if promote {
                    if term.starts_with('"') {
                        schema_facts.shared_literals += 1;
                    }
                    shared_sec.push(&term)?;
                    ranks[0] += 1;
                } else {
                    if term.starts_with('"') {
                        schema_facts.objonly_literals += 1;
                    }
                    obj_sec.push(&term)?;
                    ranks[2] += 1;
                }
                o_item = objects.next()?;
            }
        }
    }
    if next_promoted.next().is_some() {
        return Err(ExtBuildError::Internal(
            "a promoted frequent object was not met as an object-only term",
        ));
    }
    // The node merge is over: release its readers and write buffers.
    drop((subjects, objects));
    for seg in [Seg::Shared, Seg::SubjOnly, Seg::ObjOnly] {
        remaps.flush(seg)?;
    }
    let (n_shared, n_subj, n_obj) = (ranks[0], ranks[1], ranks[2]);
    if n_shared.checked_add(n_subj.max(n_obj)).is_none() {
        return Err(ExtBuildError::Internal(
            "more than 2^32 subject or object terms: the dictionary is too large for one file",
        ));
    }
    schema_facts.n_shared = n_shared;

    // predicates: plain k-way merge over the pred term files
    let mut pred_sec = RawSectionWriter::create(tmp.path("g.pred.raw"))?;
    {
        let mut streams = Vec::with_capacity(k);
        for (ci, c) in chunks.iter().enumerate() {
            // real pred reader + empty role-only reader => a plain single stream
            let empty = tmp.path(&format!("c{ci}.pred.empty"));
            File::create(&empty)?;
            streams.push(SpaceStream::new(
                TermFileReader::open_consuming(&tmp.path(&format!("c{ci}.pred")))?,
                TermFileReader::open_consuming(&empty)?,
                c.section_terms[3],
            )?);
        }
        let mut kway = KWayTerms::new(streams)?;
        let mut rank = 0u32;
        while let Some((term, carriers)) = kway.next()? {
            for (ci, lid) in carriers {
                remaps.push(ci, Seg::Pred, lid, rank + 1)?; // pred ids are final now
            }
            if let Some(i) = schema_preds.iter().position(|w| *w == term) {
                schema_facts.pred_ids[i] = Some(rank + 1);
            }
            if let Some(slot) = crate::label_index::slot_of_predicate(&term) {
                schema_facts.label_preds.push((rank + 1, slot));
            }
            pred_sec.push(&term)?;
            rank += 1;
        }
    }
    remaps.flush(Seg::Pred)?;

    // graph names: the same k-way merge, into a plain sorted name list rather
    // than a front-coded dict section — the format stores graph names verbatim.
    let mut graph_count = 0u32;
    let graph_names = if chunks.iter().any(|c| c.graph_terms > 0) {
        let path = tmp.path("g.graphs");
        let mut w = TermWriter::create(&path)?;
        let mut streams = Vec::with_capacity(k);
        for (ci, c) in chunks.iter().enumerate() {
            let real = tmp.path(&format!("c{ci}.graph"));
            if !real.exists() {
                File::create(&real)?;
            }
            let empty = tmp.path(&format!("c{ci}.graph.empty"));
            File::create(&empty)?;
            streams.push(SpaceStream::new(
                TermFileReader::open_consuming(&real)?,
                TermFileReader::open_consuming(&empty)?,
                c.graph_terms,
            )?);
        }
        let mut kway = KWayTerms::new(streams)?;
        while let Some((name, carriers)) = kway.next()? {
            graph_count += 1;
            for (ci, lid) in carriers {
                remaps.push(ci, Seg::Graph, lid, graph_count)?;
            }
            w.push(&name)?;
        }
        w.finish()?;
        Some(path)
    } else {
        None
    };
    // Subject- and object-only ids stay provisional until `n_shared` is
    // known: they are fixed up as each chunk's tables are loaded.
    let remaps = remaps.finish(n_shared)?;

    // chunk-encode each raw section (identical to encode_chunked_dict_section)
    let codec = crate::file::writer_codec();
    let section_files = [
        shared_sec.finish_chunked(tmp, "g.shared.sec", codec)?,
        subj_sec.finish_chunked(tmp, "g.subj.sec", codec)?,
        obj_sec.finish_chunked(tmp, "g.obj.sec", codec)?,
        pred_sec.finish_chunked(tmp, "g.pred.sec", codec)?,
    ];
    // chunk term files are no longer needed
    for ci in 0..k {
        for suffix in [
            "shared",
            "subj",
            "obj",
            "pred",
            "pred.empty",
            "graph",
            "graph.empty",
        ] {
            let _ = std::fs::remove_file(tmp.path(&format!("c{ci}.{suffix}")));
        }
    }

    let term_count =
        n_shared as u64 + n_subj as u64 + n_obj as u64 + section_files[3].term_count as u64;

    Ok((
        MergedDict {
            section_files: section_files.map(|s| s.file),
            term_count,
            has_quoted,
            graph_names,
            graph_count,
            schema_facts,
        },
        remaps,
    ))
}

/// A raw front-coded dict-section body being streamed to a tmp file, exactly as
/// [`crate::dict::DictSectionBuilder::build`] would lay it out — plus the
/// restart-offset bookkeeping needed to emit the header and (later) the chunked
/// encoding without ever holding the body in RAM.
///
/// The restart offsets go to disk too (8 B per `restart_interval` terms: a
/// section of a billion terms has 62.5 M of them), and so does the chunk
/// directory [`finish_chunked`](Self::finish_chunked) builds from them, so a
/// section of any size costs this writer one 64 KiB chunk of RAM.
struct RawSectionWriter {
    /// the raw body, compressed on the way to disk (read back in order)
    w: ZWriter,
    path: PathBuf,
    prev: String,
    n: u64,
    body_len: u64,
    /// every restart offset, `u64` little-endian, in order
    restarts: BufWriter<File>,
    restarts_path: PathBuf,
    n_restarts: u64,
    /// the restart offsets' varint bytes, summed: the header's length,
    /// known without reading them back
    restart_varint_bytes: u64,
}

struct FinishedSection {
    file: SectionFile,
    term_count: u32,
}

/// Reads back the `u64` restart offsets a [`RawSectionWriter`] spilled.
struct OffsetReader {
    rd: BufReader<File>,
}

impl OffsetReader {
    fn open(path: &Path) -> Result<Self, std::io::Error> {
        Ok(OffsetReader {
            rd: BufReader::with_capacity(1 << 16, File::open(path)?),
        })
    }

    fn next(&mut self) -> Result<Option<u64>, std::io::Error> {
        let mut b = [0u8; 8];
        match self.rd.read_exact(&mut b) {
            Ok(()) => Ok(Some(u64::from_le_bytes(b))),
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(None),
            Err(e) => Err(e),
        }
    }
}

impl RawSectionWriter {
    fn create(path: PathBuf) -> Result<Self, std::io::Error> {
        let restarts_path = path.with_extension("restarts");
        Ok(RawSectionWriter {
            w: ZWriter::create(&path)?,
            path,
            prev: String::new(),
            n: 0,
            body_len: 0,
            restarts: BufWriter::with_capacity(1 << 16, File::create(&restarts_path)?),
            restarts_path,
            n_restarts: 0,
            restart_varint_bytes: 0,
        })
    }

    fn push(&mut self, term: &str) -> Result<(), std::io::Error> {
        let r = env_restart_interval() as u64;
        let mut entry = Vec::with_capacity(term.len() + 8);
        if self.n.is_multiple_of(r) {
            self.restarts.write_all(&self.body_len.to_le_bytes())?;
            self.n_restarts += 1;
            self.restart_varint_bytes += uvarint_len(self.body_len);
            write_uvarint(&mut entry, 0);
            write_uvarint(&mut entry, term.len() as u64);
            entry.extend_from_slice(term.as_bytes());
        } else {
            let shared = common_prefix_len(&self.prev, term);
            let suffix = &term.as_bytes()[shared..];
            write_uvarint(&mut entry, shared as u64);
            write_uvarint(&mut entry, suffix.len() as u64);
            entry.extend_from_slice(suffix);
        }
        self.w.write_all(&entry)?;
        self.body_len += entry.len() as u64;
        self.prev.clear();
        self.prev.push_str(term);
        self.n += 1;
        Ok(())
    }

    /// Emit the chunked section payload (byte-identical to running
    /// `encode_chunked_dict_section` over the equivalent raw section) into a new
    /// tmp file, deleting the raw body. Streams: the restart offsets are read
    /// back once to cut the chunks and once more to write the header, and the
    /// chunk directory is spilled as it is built.
    fn finish_chunked(
        mut self,
        tmp: &TmpDir,
        out_name: &str,
        codec: u8,
    ) -> Result<FinishedSection, ExtBuildError> {
        self.w.finish()?;
        self.restarts.flush()?;
        drop(self.restarts);
        let term_count = self.n as u32;
        let interval = env_restart_interval() as u64;

        // the raw header exactly as DictSectionBuilder writes it:
        // [n][restart interval][restart count][restart offsets…]
        let header_len = uvarint_len(self.n)
            + uvarint_len(interval)
            + uvarint_len(self.n_restarts)
            + self.restart_varint_bytes;

        // Chunk bounds over the body by run offsets (whole runs, 64 KiB
        // budget), exactly as `encode_chunked_dict_section` cuts them: a chunk
        // starts at a run and takes the following runs while they start less
        // than the budget past its own start.
        let budget = crate::write_opts::dict_chunk_budget() as u64;
        let mut offs = OffsetReader::open(&self.restarts_path)?;
        // The chunks tile the body from offset 0, so it is read straight
        // through: `at` is where the reader stands.
        let mut body = ZReader::open(&self.path)?;
        let mut at = 0u64;
        // compressed chunks and the encoded directory, each spilled
        let comp_path = tmp.path(&format!("{out_name}.chunks"));
        let mut comp_out = BufWriter::with_capacity(1 << 20, File::create(&comp_path)?);
        let dir_path = tmp.path(&format!("{out_name}.dir"));
        let mut dir_out = BufWriter::with_capacity(1 << 16, File::create(&dir_path)?);
        let mut dir_len = 0u64;
        let mut num_chunks = 0u64;
        let mut prev_run = 0u64;
        // The previous chunk's last term — the separator's lower bound. Kept in
        // lockstep with `encode_chunked_dict_section`; the two writers must emit
        // byte-identical directories for the same input.
        let mut prev_last: Option<Vec<u8>> = None;
        let mut entry = Vec::new();
        // `next` is the offset of run `run`, the first run not yet in a chunk
        let mut run = 0u64;
        let mut next = offs.next()?;
        while let Some(start) = next {
            let first_run = run;
            let mut last_run_start = start;
            run += 1;
            next = offs.next()?;
            while let Some(o) = next {
                if o - start >= budget {
                    break;
                }
                last_run_start = o;
                run += 1;
                next = offs.next()?;
            }
            let end = next.unwrap_or(self.body_len);
            if start != at {
                return Err(ExtBuildError::Internal(
                    "dictionary chunks do not tile the body",
                ));
            }
            let mut raw = vec![0u8; (end - start) as usize];
            body.read_exact(&mut raw)?;
            at = end;
            // the chunk's first run entry is a restart: [0][len][full term]
            let first_term = read_restart_term(&raw)
                .ok_or(ExtBuildError::Internal("restart entry unreadable"))?;
            // Routing key = the shortest separator, not the first term; chunk 0
            // needs none. See `crate::dict::SectionChunk::key`.
            let key = if num_chunks == 0 {
                Vec::new()
            } else {
                match &prev_last {
                    None => first_term,
                    Some(pl) => crate::dict::shortest_separator(pl, &first_term),
                }
            };
            if next.is_some() {
                // This chunk's last run is the one before the next chunk's
                // first; `raw` already holds the bytes, so decoding it is free
                // of I/O.
                let last_run_rel = (last_run_start - start) as usize;
                prev_last = crate::dict::run_last_term(&raw, last_run_rel, raw.len());
            }
            let comp = crate::file::compress(codec, &raw);
            comp_out.write_all(&comp)?;
            entry.clear();
            write_uvarint(&mut entry, first_run - prev_run);
            write_uvarint(&mut entry, key.len() as u64);
            entry.extend_from_slice(&key);
            write_uvarint(&mut entry, comp.len() as u64);
            dir_out.write_all(&entry)?;
            dir_len += entry.len() as u64;
            prev_run = first_run;
            num_chunks += 1;
        }
        comp_out.flush()?;
        drop(comp_out);
        dir_out.flush()?;
        drop(dir_out);
        drop(body);
        let _ = std::fs::remove_file(&self.path);

        // assemble: [header_len][header][num_chunks][dir…][compressed chunks…]
        let out_path = tmp.path(out_name);
        let mut out = BufWriter::with_capacity(1 << 20, File::create(&out_path)?);
        let mut head = Vec::new();
        write_uvarint(&mut head, header_len);
        write_uvarint(&mut head, self.n);
        write_uvarint(&mut head, interval);
        write_uvarint(&mut head, self.n_restarts);
        out.write_all(&head)?;
        let mut written = head.len() as u64;
        let mut offs = OffsetReader::open(&self.restarts_path)?;
        while let Some(off) = offs.next()? {
            head.clear();
            write_uvarint(&mut head, off);
            out.write_all(&head)?;
            written += head.len() as u64;
        }
        drop(offs);
        let _ = std::fs::remove_file(&self.restarts_path);
        if written != uvarint_len(header_len) + header_len {
            return Err(ExtBuildError::Internal(
                "dictionary section header length mismatch",
            ));
        }
        head.clear();
        write_uvarint(&mut head, num_chunks);
        out.write_all(&head)?;
        written += head.len() as u64;
        let mut dir_in = File::open(&dir_path)?;
        written += std::io::copy(&mut dir_in, &mut out)?;
        drop(dir_in);
        let _ = std::fs::remove_file(&dir_path);
        let mut comp_in = File::open(&comp_path)?;
        let copied = std::io::copy(&mut comp_in, &mut out)?;
        drop(comp_in);
        out.flush()?;
        let _ = std::fs::remove_file(&comp_path);
        let len = written + copied;
        debug_assert_eq!(
            len,
            uvarint_len(header_len) + header_len + uvarint_len(num_chunks) + dir_len + copied
        );
        Ok(FinishedSection {
            file: SectionFile {
                path: out_path,
                len,
            },
            term_count,
        })
    }
}

fn common_prefix_len(a: &str, b: &str) -> usize {
    a.as_bytes()
        .iter()
        .zip(b.as_bytes())
        .take_while(|(x, y)| x == y)
        .count()
}

/// Read the full term of the restart entry at the start of `raw`.
fn read_restart_term(raw: &[u8]) -> Option<Vec<u8>> {
    let (shared, n1) = crate::varint::read_uvarint(raw)?;
    if shared != 0 {
        return None;
    }
    let (len, n2) = crate::varint::read_uvarint(&raw[n1..])?;
    let start = n1 + n2;
    raw.get(start..start + len as usize).map(|s| s.to_vec())
}

// ---------------------------------------------------------------------------
// Phase 3: remap every chunk to global ids
// ---------------------------------------------------------------------------

/// Rewrite every chunk's statements in global ids, loading one chunk's remap
/// tables at a time, straight into the external sort's first runs: default
/// triples in `first`'s order (sorted runs of `run_len`), named quads as
/// `(graph, s, p, o)` (runs of `quad_run_len`; the graph a subject id in the
/// quad layout, an ordinal in the per-graph one). The default triples are teed
/// into the SCHEMA and LABEL_INDEX passes and each chunk's text-index words
/// are remapped onto the same subject ids. A chunk's spills are deleted as
/// they are read, so the chunks' statements turn into the runs without the
/// two ever being on disk whole at once (there is no `global.tri`).
///
/// Returns the triple runs and the quad runs.
#[allow(clippy::too_many_arguments)]
fn remap_chunks(
    tmp: &TmpDir,
    chunks: &[ChunkInfo],
    remaps: &RemapStore,
    quad_layout: bool,
    first: crate::index::IndexPermutation,
    run_len: usize,
    quad_run_len: usize,
    mut text: Option<&mut crate::text_index_spill::TextSpill>,
    mut schema: Option<&mut ExtSchema>,
    mut labels: Option<&mut ExtLabels>,
) -> Result<(Vec<RunFile>, Vec<RunFile>), ExtBuildError> {
    let mut tri = RunSpiller::<IdTriple>::new(&tmp.dir, first.name(), run_len);
    let mut quads: Option<RunSpiller<IdQuad>> = None;
    let mut ticker = Ticker::new();
    for (ci, chunk) in chunks.iter().enumerate() {
        let maps = remaps.load(ci)?;
        // The chunk's literal words, onto the same global subject ids.
        if let Some(text) = text.as_deref_mut() {
            text.remap_chunk(&tmp.path(&format!("c{ci}.tok")), &maps.subj)?;
        }
        let mut rd = RunReader::<IdTriple>::open(chunk.tri.clone());
        while let Some((s, p, o)) = rd.next()? {
            let gs = maps.subj[(s - 1) as usize];
            let gp = maps.pred[(p - 1) as usize];
            let go = maps.obj[(o - 1) as usize];
            tri.push(first.forward((gs, gp, go)))?;
            ticker.tick(1);
            if let Some(x) = schema.as_deref_mut() {
                x.tee(gs, gp, go)?;
            }
            if let Some(x) = labels.as_deref_mut() {
                x.tee(gs, gp, go)?;
            }
        }
        drop(rd);
        if chunk.quad_count > 0 {
            let q = quads.get_or_insert_with(|| {
                RunSpiller::new(&tmp.dir, &format!("q{}", QUAD_FIRST.name()), quad_run_len)
            });
            // Quad index: the graph is a subject id; else an ordinal.
            let gmap = if quad_layout { &maps.subj } else { &maps.graph };
            let mut rd = RunReader::<IdQuad>::open(chunk.qtri.clone());
            while let Some((g, s, p, o)) = rd.next()? {
                q.push((
                    gmap[(g - 1) as usize],
                    maps.subj[(s - 1) as usize],
                    maps.pred[(p - 1) as usize],
                    maps.obj[(o - 1) as usize],
                ))?;
                ticker.tick(1);
            }
        } else {
            chunk.qtri.remove();
        }
        note_scratch(tmp);
    }
    let total = remaps.total_table_bytes();
    trace::add("remap_total_bytes", total);
    eprintln!(
        "extbuild: remapped {} chunk(s) one at a time — {} B of id tables in all, \
         at most {} B resident",
        chunks.len(),
        total,
        remaps.largest_table_bytes()
    );
    let tri = tri.finish()?;
    let quads = match quads {
        Some(q) => q.finish()?,
        None => Vec::new(),
    };
    Ok((tri, quads))
}

// ---------------------------------------------------------------------------
// Phase 4: the permutations, one external sort chained into the next
// ---------------------------------------------------------------------------

/// The order of the remap's quad runs, `(graph, s, p, o)`: the per-graph
/// layout's grouping key and the quad index's first order, G+SPO.
const QUAD_FIRST: crate::index::IndexPermutation = crate::index::IndexPermutation::Spo;

/// Records between two samples of the spill directory inside a long merge
/// (tests sample often, to see the peak of a small graph).
#[cfg(not(test))]
const SCRATCH_SAMPLE_EVERY: u64 = 1 << 24;
#[cfg(test)]
const SCRATCH_SAMPLE_EVERY: u64 = 1 << 9;

/// Index the triples of `runs` — sorted runs in the order of `perms`' first
/// permutation — under every permutation of `perms`, in container order, each
/// section byte-identical to `encode_tiled_section` over the same triples.
///
/// The permutations are **chained**: the k-way merge of one permutation's
/// runs (with dedup) feeds its streaming tiler and, mapped into the next
/// permutation's order, that permutation's runs. The merge deletes the runs it
/// reads segment by segment, so the next permutation's runs take the space as
/// it is freed: one copy of the statements is on disk at a time, never the
/// two of a separate `global.tri` plus a permutation's runs. `observe` sees
/// every deduplicated triple of each permutation, in its order (the SCHEMA
/// pass); `done` is called as each permutation finishes, with its count.
#[allow(clippy::too_many_arguments)]
fn index_permutations(
    tmp: &TmpDir,
    runs: Vec<RunFile>,
    perms: crate::index::PermSet,
    run_len: usize,
    codec: u8,
    prefix: &str,
    observe: &mut dyn FnMut(crate::index::IndexPermutation, IdTriple) -> std::io::Result<()>,
    done: &mut dyn FnMut(crate::index::IndexPermutation, u64),
) -> Result<(Vec<TiledSection>, u64), ExtBuildError> {
    let order: Vec<crate::index::IndexPermutation> = perms.iter().collect();
    index_chain(tmp, runs, &order, run_len, codec, prefix, observe, done)
}

/// [`index_permutations`] over an explicit order: `runs` are sorted in
/// `order[0]`'s order. (A resumed build starts the chain part-way.)
#[allow(clippy::too_many_arguments)]
fn index_chain(
    tmp: &TmpDir,
    runs: Vec<RunFile>,
    order: &[crate::index::IndexPermutation],
    run_len: usize,
    codec: u8,
    prefix: &str,
    observe: &mut dyn FnMut(crate::index::IndexPermutation, IdTriple) -> std::io::Result<()>,
    done: &mut dyn FnMut(crate::index::IndexPermutation, u64),
) -> Result<(Vec<TiledSection>, u64), ExtBuildError> {
    let mut runs = runs;
    let mut sections = Vec::with_capacity(order.len());
    let mut count: Option<u64> = None;
    for (k, &perm) in order.iter().enumerate() {
        let next = order.get(k + 1).copied();
        let mut spill = next.map(|np| {
            RunSpiller::<IdTriple>::new(&tmp.dir, &format!("{prefix}{}", np.name()), run_len)
        });
        let mut tiler = StreamingTiler::new(tmp, &format!("{prefix}{}", perm.name()), codec)?;
        note_scratch(tmp);
        let mut seen = 0u64;
        // `--progress` counts the default graph's chain (a spilled named
        // graph's runs inside its own phase are not this phase's records).
        let mut ticker = prefix.is_empty().then(Ticker::new);
        let n = spill::merge_runs(std::mem::take(&mut runs), |t: IdTriple| {
            observe(perm, t)?;
            tiler.push(t)?;
            if let Some(tk) = ticker.as_mut() {
                tk.tick(1);
            }
            if let (Some(sp), Some(np)) = (spill.as_mut(), next) {
                sp.push(np.forward(perm.back(t)))?;
            }
            seen += 1;
            if seen.is_multiple_of(SCRATCH_SAMPLE_EVERY) {
                note_scratch(tmp);
            }
            Ok::<(), ExtBuildError>(())
        })?;
        note_scratch(tmp);
        let section = tiler.finish()?;
        if let Some(sp) = spill {
            runs = sp.finish()?;
        }
        // every permutation dedups the same multiset — counts must agree
        if count.is_some_and(|c| c != n) {
            return Err(ExtBuildError::Internal("permutation dedup counts diverge"));
        }
        count = Some(n);
        sections.push(section);
        drop(ticker);
        done(perm, n);
    }
    for r in &runs {
        r.remove(); // an empty permutation set: nothing reads them
    }
    Ok((sections, count.unwrap_or(0)))
}

// ---------------------------------------------------------------------------
// Phase 4b: named graphs — the graph ordinal leads the sort key
// ---------------------------------------------------------------------------

/// A spilled quad in `(graph ordinal, s, p, o)` order.
type IdQuad = (u32, u32, u32, u32);

/// The finished named-graphs section, spilled: a `count` and the concatenated
/// per-graph `(iri, index container)` records the section prefixes it with.
struct NamedSection {
    body: PathBuf,
    body_len: u64,
    /// number of named graphs
    count: u64,
    /// deduplicated statements across every named graph
    triples: u64,
}

/// Bytes [`write_uvarint`] takes for `v`.
fn uvarint_len(mut v: u64) -> u64 {
    let mut n = 1;
    while v >= 0x80 {
        v >>= 7;
        n += 1;
    }
    n
}

/// Merge the remap's quad runs — sorted by `(graph, s, p, o)`, so each graph
/// is one contiguous run — and write one index container per graph, in
/// graph-name order, into a single spill file. `ram_triples` caps how many of
/// a graph's triples may be held resident: a graph over the cap spills and is
/// indexed by the same chained external path the default graph uses, so a
/// single 2-billion quad graph is no worse than the same data in the default
/// graph.
#[allow(clippy::too_many_arguments)]
fn build_named_graphs(
    tmp: &TmpDir,
    quad_runs: Vec<RunFile>,
    graph_names: &Path,
    graph_count: u32,
    tri_run_len: usize,
    ram_triples: usize,
    perms: crate::index::PermSet,
    codec: u8,
) -> Result<NamedSection, ExtBuildError> {
    note_scratch(tmp);
    let body_path = tmp.path("named.body");
    let mut body = BufWriter::with_capacity(1 << 20, File::create(&body_path)?);
    let mut names = TermFileReader::open(graph_names)?;
    let mut emitted = 0u32;
    let mut total: u64 = 0;
    let mut body_len: u64 = 0;

    let mut cur = GraphRun::new();
    let mut ticker = Ticker::new();
    spill::merge_runs(quad_runs, |q: IdQuad| {
        ticker.tick(1);
        if cur.graph != 0 && cur.graph != q.0 {
            // The name file is read in lockstep with the ordinals, so a
            // skipped or out-of-order ordinal would silently pair a graph's
            // triples with another graph's IRI. Ordinals are dense and
            // ascending by construction; check it rather than trust it.
            if cur.graph != emitted + 1 {
                return Err(ExtBuildError::Internal(
                    "graph ordinals are not dense and ascending",
                ));
            }
            let done = std::mem::replace(&mut cur, GraphRun::new());
            body_len += done.finish(
                tmp,
                &mut body,
                &mut names,
                tri_run_len,
                perms,
                codec,
                &mut total,
            )?;
            emitted += 1;
        }
        cur.graph = q.0;
        cur.push(tmp, (q.1, q.2, q.3), ram_triples, perms, tri_run_len)
    })?;
    if cur.graph != 0 {
        if cur.graph != emitted + 1 {
            return Err(ExtBuildError::Internal(
                "graph ordinals are not dense and ascending",
            ));
        }
        body_len += cur.finish(
            tmp,
            &mut body,
            &mut names,
            tri_run_len,
            perms,
            codec,
            &mut total,
        )?;
        emitted += 1;
    }
    body.flush()?;
    drop(body);
    drop(names);
    let _ = std::fs::remove_file(graph_names);

    if emitted != graph_count {
        return Err(ExtBuildError::Internal(
            "named-graph count diverges from the merged graph names",
        ));
    }
    Ok(NamedSection {
        body: body_path,
        body_len,
        count: emitted as u64,
        triples: total,
    })
}

/// One graph's contiguous run: resident until it outgrows `ram_triples`, then
/// spilled as sorted runs in the first permutation's order and indexed
/// externally.
struct GraphRun {
    graph: u32,
    resident: Vec<IdTriple>,
    spill: Option<RunSpiller<IdTriple>>,
    n: u64,
}

impl GraphRun {
    fn new() -> Self {
        GraphRun {
            graph: 0,
            resident: Vec::new(),
            spill: None,
            n: 0,
        }
    }

    fn push(
        &mut self,
        tmp: &TmpDir,
        t: IdTriple,
        ram_triples: usize,
        perms: crate::index::PermSet,
        run_len: usize,
    ) -> Result<(), ExtBuildError> {
        self.n += 1;
        if self.spill.is_none() && self.resident.len() < ram_triples {
            self.resident.push(t);
            return Ok(());
        }
        let first = perms
            .iter()
            .next()
            .ok_or(ExtBuildError::Internal("no permutation to index"))?;
        if self.spill.is_none() {
            let name = format!("ng{}.{}", self.graph, first.name());
            let mut sp = RunSpiller::new(&tmp.dir, &name, run_len);
            for &r in &self.resident {
                sp.push(first.forward(r))?;
            }
            self.resident = Vec::new();
            self.spill = Some(sp);
        }
        let sp = self.spill.as_mut().expect("just opened");
        sp.push(first.forward(t))?;
        Ok(())
    }

    /// Emit `[iri_len][iri][container_len][container]` and return its byte length.
    #[allow(clippy::too_many_arguments)]
    fn finish(
        self,
        tmp: &TmpDir,
        body: &mut BufWriter<File>,
        names: &mut TermFileReader,
        tri_run_len: usize,
        perms: crate::index::PermSet,
        codec: u8,
        total: &mut u64,
    ) -> Result<u64, ExtBuildError> {
        let iri = names
            .next()?
            .ok_or(ExtBuildError::Internal("graph name file exhausted"))?;
        *total += self.n;

        let mut head = Vec::new();
        write_uvarint(&mut head, iri.len() as u64);
        head.extend_from_slice(iri.as_bytes());

        match self.spill {
            // Small graph (the overwhelming majority — fedlex averages ~113
            // quads): build it with the very call the in-RAM builder makes for a
            // graph this size, so byte-identity is not a second
            // implementation's promise — and so a dataset with half a million
            // tiny graphs is not half a million trips through the low-RAM
            // builder's nested rayon, which for a 60-triple graph is all
            // overhead and no parallelism.
            None => {
                let index = crate::GraphIndexBuilder::from_triples(self.resident)
                    .with_perms(perms)
                    .build();
                let container = crate::file::encode_index_container(&index, codec);
                write_uvarint(&mut head, container.len() as u64);
                body.write_all(&head)?;
                body.write_all(&container)?;
                Ok(head.len() as u64 + container.len() as u64)
            }
            // A graph too big for the budget takes the same chained external
            // path the default graph always takes.
            Some(sp) => {
                let prefix = format!("ng{}.", self.graph);
                let (sections, _) = index_permutations(
                    tmp,
                    sp.finish()?,
                    perms,
                    tri_run_len,
                    codec,
                    &prefix,
                    &mut |_, _| Ok(()),
                    &mut |_, _| {},
                )?;
                let mut clen = uvarint_len(sections.len() as u64);
                for s in &sections {
                    clen += uvarint_len(s.len()) + s.len();
                }
                write_uvarint(&mut head, clen);
                body.write_all(&head)?;
                write_uvarint_to(body, sections.len() as u64)?;
                for s in &sections {
                    write_uvarint_to(body, s.len())?;
                    s.write_to(body, None, true)?;
                }
                Ok(head.len() as u64 + clen)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Phase 4b (quad index): the graph-leading orders of `GraphLayout::Quad`
// ---------------------------------------------------------------------------

/// The finished QUAD_INDEX section, spilled, with the digest the index
/// container's seal carries.
struct QuadSectionFile {
    path: PathBuf,
    len: u64,
    digest: [u8; 16],
    graph_count: u64,
    quad_count: u64,
}

/// Encode a batch of finished quad tiles into an order's directory + payload.
fn drain_quad_tiles(
    pending: &mut Vec<Vec<crate::quad::QuadRow>>,
    codec: u8,
    perm: crate::index::IndexPermutation,
    dir: &mut crate::quad::PermDirWriter,
    payload: &mut BufWriter<File>,
) -> Result<(), ExtBuildError> {
    for t in crate::quad::encode_tiles(pending, codec, perm) {
        dir.add(&t);
        payload.write_all(&t.bytes)?;
    }
    pending.clear();
    Ok(())
}

/// Build the QUAD_INDEX section from the remap's quad runs (sorted by
/// `(g, s, p, o)`, the first order): per graph-leading order, a k-way merge
/// into the shared [`crate::quad::QuadTiler`] — byte-identical to
/// `quad::encode_quad_index` — chained into the next order's runs exactly as
/// [`index_permutations`] chains the default graph's.
fn build_quad_section(
    tmp: &TmpDir,
    runs: Vec<RunFile>,
    run_len: usize,
    perms: crate::index::PermSet,
    codec: u8,
) -> Result<QuadSectionFile, ExtBuildError> {
    let order: Vec<crate::index::IndexPermutation> = perms.iter().collect();
    if order.first() != Some(&QUAD_FIRST) {
        return Err(ExtBuildError::Internal(
            "the quad index's first order must be G+SPO",
        ));
    }
    let gblocks_path = tmp.path("quad.gblocks");
    let mut gblocks = BufWriter::with_capacity(1 << 20, File::create(&gblocks_path)?);
    let mut gdir = crate::quad::GraphDirWriter::new(codec);
    let mut dirs: Vec<Vec<u8>> = Vec::with_capacity(order.len());
    let mut payloads: Vec<(PathBuf, u64)> = Vec::with_capacity(order.len());
    let mut quad_count: Option<u64> = None;
    let mut runs = runs;
    for (k, &perm) in order.iter().enumerate() {
        let spo = perm == crate::index::IndexPermutation::Spo;
        let next = order.get(k + 1).copied();
        let mut spill =
            next.map(|np| RunSpiller::<IdQuad>::new(&tmp.dir, &format!("q{}", np.name()), run_len));
        let ppath = tmp.path(&format!("q{}.tiles", perm.name()));
        let mut payload = BufWriter::with_capacity(1 << 20, File::create(&ppath)?);
        let mut dir = crate::quad::PermDirWriter::default();
        let mut tiler = crate::quad::QuadTiler::new();
        let mut pending: Vec<Vec<crate::quad::QuadRow>> = Vec::new();
        // G+SPO also yields the graph directory: (graph, deduplicated count).
        let mut cur: Option<(u32, u64)> = None;
        note_scratch(tmp);
        let mut ticker = Ticker::new();
        spill::merge_runs(std::mem::take(&mut runs), |q: IdQuad| {
            ticker.tick(1);
            tiler.push(q, &mut |t| pending.push(t));
            if pending.len() >= TILE_COMPRESS_BATCH {
                drain_quad_tiles(&mut pending, codec, perm, &mut dir, &mut payload)?;
            }
            if spo {
                cur = match cur {
                    Some((g, n)) if g == q.0 => Some((g, n + 1)),
                    Some((g, n)) => {
                        gdir.push(g, n, &mut gblocks)?;
                        Some((q.0, 1))
                    }
                    None => Some((q.0, 1)),
                };
            }
            if let (Some(sp), Some(np)) = (spill.as_mut(), next) {
                let (a, b, c) = np.forward(perm.back((q.1, q.2, q.3)));
                sp.push((q.0, a, b, c))?;
            }
            Ok::<(), ExtBuildError>(())
        })?;
        note_scratch(tmp);
        let n = tiler.finish(&mut |t| pending.push(t));
        drain_quad_tiles(&mut pending, codec, perm, &mut dir, &mut payload)?;
        if let (true, Some((g, k))) = (spo, cur) {
            gdir.push(g, k, &mut gblocks)?;
        }
        payload.flush()?;
        drop(payload);
        if let Some(sp) = spill {
            runs = sp.finish()?;
        }
        if quad_count.is_some_and(|prev| prev != n) {
            return Err(ExtBuildError::Internal("quad orders' dedup counts diverge"));
        }
        quad_count = Some(n);
        payloads.push((ppath, dir.payload_len()));
        dirs.push(dir.finish());
        eprintln!(
            "extbuild: quad order G+{} indexed ({n} unique quad(s))",
            perm.name()
        );
    }
    let (gindex, gblocks_len, graph_count) = gdir.finish(&mut gblocks)?;
    gblocks.flush()?;
    drop(gblocks);
    let quad_count = quad_count.unwrap_or(0);

    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);
    part_lens.extend(payloads.iter().map(|(_, l)| *l));
    let preamble = crate::quad::encode_preamble(perms, graph_count, quad_count, &part_lens);

    let path = tmp.path("quad.sec");
    let mut out = BufWriter::with_capacity(1 << 20, File::create(&path)?);
    let mut hasher = blake3::Hasher::new();
    let mut len = 0u64;
    for bytes in std::iter::once(&preamble)
        .chain(std::iter::once(&gindex))
        .chain(dirs.iter())
    {
        out.write_all(bytes)?;
        hasher.update(bytes);
        len += bytes.len() as u64;
    }
    for p in std::iter::once(&gblocks_path).chain(payloads.iter().map(|(p, _)| p)) {
        len += copy_hashed(p, &mut out, Some(&mut hasher))?;
        let _ = std::fs::remove_file(p);
    }
    out.flush()?;
    let mut digest = [0u8; 16];
    digest.copy_from_slice(&hasher.finalize().as_bytes()[..16]);
    Ok(QuadSectionFile {
        path,
        len,
        digest,
        graph_count,
        quad_count,
    })
}

fn write_uvarint_to(w: &mut BufWriter<File>, v: u64) -> Result<(), std::io::Error> {
    let mut b = Vec::new();
    write_uvarint(&mut b, v);
    w.write_all(&b)
}

/// Streaming re-implementation of [`crate::index::build_tiles`]'s grouping (same
/// byte-budget accounting, same whole-a-group boundaries) that never holds more
/// than the current a-group + the current tile in RAM. Tiles are compressed in
/// parallel batches and spilled; the section payload (directory + tiles +
/// synopsis trailer) is assembled at `finish`, byte-identical to
/// `encode_tiled_section`.
struct StreamingTiler {
    tile_budget: usize,
    codec: u8,
    /// triples of the tile being accumulated
    tile: Vec<(u32, u32, u32)>,
    tile_size: usize,
    /// the a-group slice currently being measured — bounded: a group whose
    /// running encoded size alone exceeds the tile budget is cut into
    /// consecutive tiles sharing the leading id (same rule as `build_tiles`,
    /// via the shared [`GroupSizer`]), so mega-groups (a 2B-triple predicate
    /// in POS/PSO, a hot class object in OSP/OPS) can no longer grow this
    /// buffer to tens of GB
    group: Vec<(u32, u32, u32)>,
    sizer: GroupSizer,
    gtotal: usize,
    prev_a: u32,
    /// finished-but-uncompressed tiles awaiting a parallel compress batch
    pending: Vec<Vec<(u32, u32, u32)>>,
    /// spilled compressed tiles
    comp_out: BufWriter<File>,
    comp_path: PathBuf,
    /// per-tile directory: (min_a, max_a, comp_len, synopsis)
    dir: Vec<TileDirEntry>,
    count: u64,
}

impl StreamingTiler {
    fn new(tmp: &TmpDir, name: &str, codec: u8) -> Result<Self, ExtBuildError> {
        let comp_path = tmp.path(&format!("{name}.tiles"));
        Ok(StreamingTiler {
            tile_budget: crate::write_opts::tile_budget(),
            codec,
            tile: Vec::new(),
            tile_size: 0,
            group: Vec::new(),
            sizer: GroupSizer::start(0, 0),
            gtotal: 0,
            prev_a: 0,
            pending: Vec::new(),
            comp_out: BufWriter::with_capacity(1 << 20, File::create(&comp_path)?),
            comp_path,
            dir: Vec::new(),
            count: 0,
        })
    }

    /// Push the next triple (already permuted, sorted, deduped). Runs the
    /// SAME boundary rules as `build_tiles` (shared `GroupSizer` accounting):
    /// whole-group packing to the byte budget, plus a mid-group cut whenever
    /// the current group's own running size exceeds the budget — the cut is
    /// what bounds this tiler's memory under mega-group skew.
    fn push(&mut self, t: (u32, u32, u32)) -> Result<(), ExtBuildError> {
        self.count += 1;
        if let Some(&(ga, _, _)) = self.group.first() {
            if t.0 != ga {
                self.close_group()?;
            }
        }
        if self.group.is_empty() {
            self.sizer = GroupSizer::start(t.0, self.prev_a);
        }
        self.group.push(t);
        self.gtotal = self.sizer.push(t.1, t.2);
        if self.gtotal > self.tile_budget {
            // Mega-group cut — mirror `build_tiles`: completed groups plus
            // the slice measured so far become ONE tile; the group continues
            // in a fresh chain with `a` as its own delta base.
            self.tile.append(&mut self.group);
            self.flush_tile()?;
            self.tile_size = 0;
            self.prev_a = t.0;
            self.gtotal = 0;
        }
        Ok(())
    }

    /// The current a-group (or its final slice after mid-group cuts) is
    /// complete: pack it into the current tile, flushing first on overflow —
    /// identical to `build_tiles`' end-of-group rule.
    fn close_group(&mut self) -> Result<(), ExtBuildError> {
        if self.group.is_empty() {
            return Ok(());
        }
        let a = self.group[0].0;
        let gsize = self.sizer.total();
        if !self.tile.is_empty() && self.tile_size + gsize > self.tile_budget {
            self.flush_tile()?;
        }
        self.tile_size += gsize;
        self.prev_a = a;
        self.tile.append(&mut self.group);
        Ok(())
    }

    fn flush_tile(&mut self) -> Result<(), ExtBuildError> {
        if self.tile.is_empty() {
            return Ok(());
        }
        self.pending.push(std::mem::take(&mut self.tile));
        self.tile_size = 0;
        if self.pending.len() >= TILE_COMPRESS_BATCH {
            self.compress_pending()?;
        }
        Ok(())
    }

    fn compress_pending(&mut self) -> Result<(), ExtBuildError> {
        if self.pending.is_empty() {
            return Ok(());
        }
        let batch = std::mem::take(&mut self.pending);
        let codec = self.codec;
        // encode + synopsis + compress each tile; par_iter preserves order
        let encode_one = |run: &Vec<(u32, u32, u32)>| -> (u32, u32, Vec<u8>, (u32, u32, u32, u32)) {
            let mut b = TripleBlockBuilder::new();
            for &t in run {
                b.push(t);
            }
            let bytes = b.build();
            let syn = match crate::triples::TripleBlock::parse(&bytes) {
                Ok(blk) => {
                    let z = blk.zone();
                    (z.min_b, z.max_b, z.min_c, z.max_c)
                }
                Err(_) => (0, u32::MAX, 0, u32::MAX),
            };
            let comp = crate::file::compress(codec, &bytes);
            (run[0].0, run[run.len() - 1].0, comp, syn)
        };
        #[cfg(feature = "parallel")]
        let encoded: Vec<EncodedTile> = {
            use rayon::prelude::*;
            batch.par_iter().map(encode_one).collect()
        };
        #[cfg(not(feature = "parallel"))]
        let encoded: Vec<EncodedTile> = batch.iter().map(encode_one).collect();
        for (min_a, max_a, comp, syn) in encoded {
            self.comp_out.write_all(&comp)?;
            self.dir.push((min_a, max_a, comp.len() as u64, syn));
        }
        Ok(())
    }

    /// Close out: the directory and the synopsis trailer in memory, the
    /// compressed tiles in their spill file. The three are concatenated only
    /// when the section is copied into the output (or a graph's container),
    /// so the tiles are never copied into a second spill file first.
    fn finish(mut self) -> Result<TiledSection, ExtBuildError> {
        self.close_group()?;
        self.flush_tile()?;
        self.compress_pending()?;
        self.comp_out.flush()?;
        drop(self.comp_out);
        Ok(TiledSection::from_dir(&self.dir, self.comp_path))
    }
}

/// A finished permutation section, spilled as its three parts, `head ‖ tiles
/// ‖ trailer`: the tile directory, the compressed tiles (a file) and the
/// synopses — byte-identical, once concatenated, to `encode_tiled_section`.
struct TiledSection {
    head: Vec<u8>,
    tiles: PathBuf,
    tiles_len: u64,
    trailer: Vec<u8>,
}

impl TiledSection {
    /// The section of the tiles in `tiles`, described by `dir`:
    /// `[num_tiles][per tile: delta(min_a), max_a-min_a, comp_len][tiles…][synopses…]`.
    fn from_dir(dir: &[TileDirEntry], tiles: PathBuf) -> Self {
        let mut head = Vec::new();
        write_uvarint(&mut head, dir.len() as u64);
        let mut prev_min = 0u32;
        let mut tiles_len = 0u64;
        for &(min_a, max_a, comp_len, _) in dir {
            write_uvarint(&mut head, (min_a - prev_min) as u64);
            write_uvarint(&mut head, (max_a - min_a) as u64);
            write_uvarint(&mut head, comp_len);
            prev_min = min_a;
            tiles_len += comp_len;
        }
        let mut trailer = Vec::new();
        for &(_, _, _, (min_b, max_b, min_c, max_c)) in dir {
            write_uvarint(&mut trailer, min_b as u64);
            write_uvarint(&mut trailer, (max_b - min_b) as u64);
            write_uvarint(&mut trailer, min_c as u64);
            write_uvarint(&mut trailer, (max_c - min_c) as u64);
        }
        TiledSection {
            head,
            tiles,
            tiles_len,
            trailer,
        }
    }

    /// The section's length in the file.
    fn len(&self) -> u64 {
        self.head.len() as u64 + self.tiles_len + self.trailer.len() as u64
    }

    /// Append the section to `out` (and to `hasher`), deleting its tiles file
    /// afterwards when `consume`.
    fn write_to(
        &self,
        out: &mut BufWriter<File>,
        mut hasher: Option<&mut blake3::Hasher>,
        consume: bool,
    ) -> Result<(), std::io::Error> {
        out.write_all(&self.head)?;
        if let Some(h) = hasher.as_deref_mut() {
            h.update(&self.head);
        }
        let n = copy_hashed(&self.tiles, out, hasher.as_deref_mut())?;
        if n != self.tiles_len {
            return Err(std::io::Error::other(
                "a spilled tile file has the wrong length",
            ));
        }
        out.write_all(&self.trailer)?;
        if let Some(h) = hasher {
            h.update(&self.trailer);
        }
        if consume {
            let _ = std::fs::remove_file(&self.tiles);
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Phase 5: final streaming file assembly
// ---------------------------------------------------------------------------

/// Stream `header | metadata | dict container | index container | text index |
/// named graphs | footer` to `output`, hashing the payload sections
/// incrementally (same part order as `write_dataset_from_parts`), then patch the
/// finished header at offset 0.
///
/// With `consume`, each spilled section is deleted as soon as it has been
/// copied, so the output grows as the spill shrinks instead of the two adding
/// up to twice the file at the end of the write.
#[allow(clippy::too_many_arguments)]
fn write_final_file(
    output: &Path,
    metadata: &[u8],
    build_info: &[u8],
    dict: &MergedDict,
    perm_sections: &[TiledSection],
    text: Option<&crate::text_index_spill::TextSection>,
    named: Option<&NamedSection>,
    quad: Option<&QuadSectionFile>,
    quad_count: u64,
    codec: u8,
    perms: crate::index::PermSet,
    consume: bool,
) -> Result<(), ExtBuildError> {
    let gone = |p: &Path| {
        if consume {
            let _ = std::fs::remove_file(p);
        }
    };
    use crate::header::{
        Header, FLAG_HAS_QUADS, FLAG_HAS_QUOTED_TRIPLES, FLAG_TEXT_INDEX_NAMED_GRAPHS,
        FLAG_TILE_SYNOPSIS, HEADER_LEN,
    };
    // Quad index: the index container ends with the seal (the section's
    // digest), which every pre-quad-index reader refuses on the section count.
    let seal = quad.map(|q| crate::quad::encode_seal(q.digest));

    // container framings are tiny; build them in RAM
    let mut dict_frame = Vec::new();
    write_uvarint(&mut dict_frame, 4);
    let mut dict_len = dict_frame.len() as u64;
    let mut dict_section_heads = Vec::with_capacity(4);
    for s in &dict.section_files {
        let mut h = Vec::new();
        write_uvarint(&mut h, s.len);
        dict_len += h.len() as u64 + s.len;
        dict_section_heads.push(h);
    }

    let mut index_frame = Vec::new();
    write_uvarint(
        &mut index_frame,
        (perm_sections.len() + usize::from(seal.is_some())) as u64,
    );
    let mut index_len = index_frame.len() as u64;
    let mut index_section_heads = Vec::with_capacity(perm_sections.len());
    for s in perm_sections {
        let mut h = Vec::new();
        write_uvarint(&mut h, s.len());
        index_len += h.len() as u64 + s.len();
        index_section_heads.push(h);
    }
    let mut seal_frame = Vec::new();
    if let Some(seal) = &seal {
        write_uvarint(&mut seal_frame, seal.len() as u64);
        seal_frame.extend_from_slice(seal);
        index_len += seal_frame.len() as u64;
    }

    // The named-graphs section is `[count][per graph: iri, container]`; only the
    // count prefix is built here, the records stream from their spill file.
    let mut named_frame = Vec::new();
    let named_len = match named {
        Some(n) => {
            write_uvarint(&mut named_frame, n.count);
            named_frame.len() as u64 + n.body_len
        }
        None => 0,
    };

    let meta_len = metadata.len() as u64;
    let build_len = build_info.len() as u64;
    let dict_offset = HEADER_LEN as u64 + meta_len + build_len;
    let index_offset = dict_offset + dict_len;
    // The pyramid is absent (length 0), so the text index follows the index
    // directly and the named graphs follow it — the same arithmetic
    // `write_dataset_from_parts` does.
    let text_offset = index_offset + index_len;
    let text_len = text.map_or(0, |t| t.len());
    let named_offset = text_offset + text_len;

    let mut out = BufWriter::with_capacity(1 << 20, File::create(output)?);
    let mut hasher = blake3::Hasher::new();

    // header placeholder
    out.write_all(&[0u8; HEADER_LEN])?;

    // metadata (hashed only when present — mirrors write_dataset_from_parts)
    if meta_len > 0 {
        out.write_all(metadata)?;
        hasher.update(metadata);
    }
    // build-info: written adjacent to the metadata (so a card reader fetches
    // both in one coalesced range) but NOT hashed — it records per-build facts
    // that must not perturb the reproducible content hash.
    if build_len > 0 {
        out.write_all(build_info)?;
    }

    // dict container
    let write_hashed = |out: &mut BufWriter<File>,
                        hasher: &mut blake3::Hasher,
                        bytes: &[u8]|
     -> Result<(), std::io::Error> {
        out.write_all(bytes)?;
        hasher.update(bytes);
        Ok(())
    };
    write_hashed(&mut out, &mut hasher, &dict_frame)?;
    for (s, head) in dict.section_files.iter().zip(&dict_section_heads) {
        write_hashed(&mut out, &mut hasher, head)?;
        copy_hashed(&s.path, &mut out, Some(&mut hasher))?;
        gone(&s.path);
    }

    // index container
    write_hashed(&mut out, &mut hasher, &index_frame)?;
    for (s, head) in perm_sections.iter().zip(&index_section_heads) {
        write_hashed(&mut out, &mut hasher, head)?;
        s.write_to(&mut out, Some(&mut hasher), consume)?;
    }
    write_hashed(&mut out, &mut hasher, &seal_frame)?;

    // pyramid section is empty (hash update of nothing = no-op, same as the
    // in-RAM writer pushing an empty slice).

    // text index: `varint table_len | token table | postings`. A kind-11
    // (predicate-restricted) section is outside the content hash and starts
    // with its own digest, patched in below once the payload has gone past —
    // the bytes `write_dataset_from_parts` writes.
    let mut text_digest: Option<blake3::Hash> = None;
    if let Some(t) = text {
        if t.partial {
            out.write_all(&[0u8; crate::header::TEXT_INDEX_PARTIAL_DIGEST_LEN as usize])?;
            let mut digest = blake3::Hasher::new();
            write_hashed(&mut out, &mut digest, &t.head)?;
            copy_hashed(&t.table, &mut out, Some(&mut digest))?;
            copy_hashed(&t.postings, &mut out, Some(&mut digest))?;
            text_digest = Some(digest.finalize());
        } else {
            write_hashed(&mut out, &mut hasher, &t.head)?;
            copy_hashed(&t.table, &mut out, Some(&mut hasher))?;
            copy_hashed(&t.postings, &mut out, Some(&mut hasher))?;
        }
        gone(&t.table);
        gone(&t.postings);
    }

    // named-graphs container
    if let Some(n) = named {
        write_hashed(&mut out, &mut hasher, &named_frame)?;
        copy_hashed(&n.body, &mut out, Some(&mut hasher))?;
        gone(&n.body);
    }

    // quad index: where the named graphs would be; not a hash part of its
    // own (the seal above carries its digest), exactly as the in-RAM writer.
    if let Some(q) = quad {
        copy_hashed(&q.path, &mut out, None)?;
        gone(&q.path);
    }

    out.write_all(&crate::header::MAGIC)?; // footer marker
    out.flush()?;

    let mut hash = [0u8; 16];
    hash.copy_from_slice(&hasher.finalize().as_bytes()[..16]);

    let header = Header {
        version: crate::header::CURRENT_FORMAT_VERSION,
        flags: FLAG_TILE_SYNOPSIS
            | if named_len > 0 || quad.is_some() {
                FLAG_HAS_QUADS
            } else {
                0
            }
            | if quad.is_some() {
                crate::header::FLAG_QUAD_INDEX
            } else {
                0
            }
            | if dict.has_quoted {
                FLAG_HAS_QUOTED_TRIPLES
            } else {
                0
            }
            | if text.is_some_and(|t| t.named) {
                FLAG_TEXT_INDEX_NAMED_GRAPHS
            } else {
                0
            },
        metadata_offset: HEADER_LEN as u64,
        metadata_len: meta_len,
        dictionary_offset: dict_offset,
        dictionary_len: dict_len,
        root_dir_offset: index_offset,
        root_dir_len: index_len,
        pyramid_meta_offset: 0,
        pyramid_meta_len: 0,
        dict_codec: codec,
        block_codec: codec,
        pyramid_levels: 0,
        perms,
        quad_count,
        term_count: dict.term_count,
        content_hash: hash,
        named_graphs_offset: if named_len > 0 { named_offset } else { 0 },
        named_graphs_len: named_len,
        schema_meta_len: 0,
        text_index_offset: if text_len > 0 { text_offset } else { 0 },
        text_index_len: text_len,
        text_index_partial: text.is_some_and(|t| t.partial),
        build_info_offset: if build_len > 0 {
            HEADER_LEN as u64 + meta_len
        } else {
            0
        },
        build_info_len: build_len,
        extra_sections: match quad {
            Some(q) => vec![crate::header::Section {
                kind: crate::header::SectionKind::QuadIndex,
                flags: 0,
                offset: named_offset,
                length: q.len,
            }],
            None => Vec::new(),
        },
    };
    let mut f = out.into_inner().map_err(|e| e.into_error())?;
    f.seek(SeekFrom::Start(0))?;
    f.write_all(&header.to_bytes())?;
    if let Some(d) = text_digest {
        f.seek(SeekFrom::Start(text_offset))?;
        f.write_all(&d.as_bytes()[..crate::header::TEXT_INDEX_PARTIAL_DIGEST_LEN as usize])?;
    }
    f.flush()?;
    Ok(())
}

/// Append the file at `path` to `out` (and to `hasher`); returns its length.
fn copy_hashed(
    path: &Path,
    out: &mut BufWriter<File>,
    mut hasher: Option<&mut blake3::Hasher>,
) -> Result<u64, std::io::Error> {
    let mut rd = File::open(path)?;
    let mut buf = vec![0u8; 1 << 20];
    let mut len = 0u64;
    loop {
        let n = rd.read(&mut buf)?;
        if n == 0 {
            break;
        }
        out.write_all(&buf[..n])?;
        if let Some(h) = hasher.as_deref_mut() {
            h.update(&buf[..n]);
        }
        len += n as u64;
    }
    Ok(len)
}

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

    /// Generate a graph that exercises the merge machinery: terms shared across
    /// chunks, subject-only/object-only/shared classification that differs
    /// per-chunk vs globally, langs, datatypes, bnodes, duplicate triples.
    fn test_quads(n: usize) -> Vec<RawQuad> {
        let mut quads = Vec::new();
        for i in 0..n {
            let s = format!("<http://ex/s{}>", i % (n / 7 + 1));
            let p = format!("<http://ex/p{}>", i % 13);
            let o = match i % 5 {
                0 => format!("<http://ex/s{}>", (i + 3) % (n / 7 + 1)), // makes shared terms
                1 => format!("\"lit {i}\""),
                2 => format!("\"{}\"^^<http://www.w3.org/2001/XMLSchema#integer>", i),
                3 => format!("\"v{}\"@en", i % 50),
                _ => format!("_:b{}", i % 97),
            };
            quads.push((s, p, o, None));
        }
        // duplicates, far apart so they land in different chunks
        for i in 0..(n / 20) {
            let j = i * 17 % n;
            quads.push(quads[j].clone());
        }
        quads
    }

    fn build_reference(quads: Vec<RawQuad>) -> Vec<u8> {
        // reference: the ordinary streaming path, no pyramid / text / metadata
        let qs = quads.clone();
        let (bytes, _stats) = ingest::assemble_dataset_streaming_algo(
            move |visit: &mut dyn FnMut(RawQuad)| {
                for q in qs.iter().cloned() {
                    visit(q);
                }
                Ok(())
            },
            false,
            false,
            None,
            crate::PyramidAlgo::Louvain,
            |_, _, _| Vec::new(),
        )
        .unwrap();
        bytes
    }

    fn build_ext(quads: Vec<RawQuad>, budget: u64) -> (Vec<u8>, BuildStats) {
        static TEST_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let seq = TEST_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "rete-extbuild-test-{}-{budget}-{seq}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");
        let stats = build_external(
            |visit| {
                for q in quads.iter().cloned() {
                    visit(q)?;
                }
                Ok(())
            },
            &out,
            ExternalBuildOptions {
                memory_budget: budget,
                tmp_dir: Some(dir.clone()),
                metadata: Box::new(|_| Vec::new()),
                build_info: Vec::new(),
                perms: crate::index::PermSet::ALL,
                ..Default::default()
            },
        )
        .unwrap();
        let bytes = std::fs::read(&out).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
        (bytes, stats)
    }

    /// A build-info payload is written as a kind-7 section, readable back, and
    /// leaves the content hash identical to a build without one — the external
    /// builder's version of the outside-the-hash property.
    #[test]
    fn external_build_info_is_outside_the_hash() {
        let quads = test_quads(500);
        let (plain, _) = build_ext(quads.clone(), 0);

        let dir = std::env::temp_dir().join(format!("rete-extbuild-bi-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");
        let info = br#"{"built_at":"2026-08-04T00:00:00Z"}"#.to_vec();
        build_external(
            |visit| {
                for q in quads.iter().cloned() {
                    visit(q)?;
                }
                Ok(())
            },
            &out,
            ExternalBuildOptions {
                memory_budget: 0,
                tmp_dir: Some(dir.clone()),
                metadata: Box::new(|_| Vec::new()),
                build_info: info.clone(),
                perms: crate::index::PermSet::ALL,
                ..Default::default()
            },
        )
        .unwrap();
        let with = std::fs::read(&out).unwrap();
        let _ = std::fs::remove_dir_all(&dir);

        assert_eq!(crate::read_build_info(&with).unwrap().unwrap(), info);
        let h_with = crate::Header::from_bytes(&with).unwrap();
        let h_plain = crate::Header::from_bytes(&plain).unwrap();
        assert_eq!(h_with.content_hash, h_plain.content_hash);
        assert!(crate::verify(&with).unwrap());
        // Stripping the section restores the plain image byte-for-byte.
        assert_eq!(crate::attach_build_info(&with, &[]).unwrap(), plain);
        // And the graph still opens.
        crate::Rete::open(&with).unwrap();
    }

    /// The heart of the feature: a tiny budget (forcing many chunks, many sort
    /// runs) must produce **byte-identical** output to the in-RAM build.
    #[test]
    fn external_build_is_byte_identical_to_streaming() {
        let quads = test_quads(3000);
        let reference = build_reference(quads.clone());
        // 64 MiB is the floor; to force chunking on a small graph we can't rely
        // on the floor — instead check both a floor build (1 chunk) and verify
        // chunk-count > 1 via a direct Chunker probe below.
        let (bytes_floor, stats) = build_ext(quads.clone(), 0);
        // `test_quads` repeats some statements, so this fixture is exactly the
        // case #128 was about: the reported count is what the build WROTE (and
        // what the header records), not what it read.
        let header = crate::Header::from_bytes(&bytes_floor).unwrap();
        assert_eq!(stats.statements as u64, header.quad_count);
        assert!(
            stats.statements < quads.len(),
            "fixture must contain duplicates for this to mean anything"
        );
        assert_eq!(
            bytes_floor, reference,
            "single-chunk external build must be byte-identical"
        );
    }

    /// Mega-group inputs (one predicate dominating the graph — the Crossref
    /// `cites` shape) exercise the mid-group tile cuts; the external and
    /// in-RAM builds must STILL be byte-identical, proving both tilers cut at
    /// the same boundaries (shared `GroupSizer`).
    #[test]
    fn skewed_external_build_is_byte_identical() {
        let mut quads: Vec<RawQuad> = Vec::new();
        for i in 0..30_000usize {
            quads.push((
                format!("<http://ex/s{}>", i % 500),
                "<http://ex/cites>".to_string(),
                format!("<http://ex/o{i}>"),
                None,
            ));
        }
        for i in 0..500usize {
            quads.push((
                format!("<http://ex/s{i}>"),
                format!("<http://ex/p{}>", i % 7),
                format!("\"lit {i}\""),
                None,
            ));
        }
        let reference = build_reference(quads.clone());
        let (bytes, stats) = build_ext(quads.clone(), 0);
        assert_eq!(stats.statements, quads.len());
        assert_eq!(
            bytes, reference,
            "mega-group external build must be byte-identical"
        );
    }

    /// Multi-chunk path: shrink the chunk budget directly (bypassing the public
    /// floor) so a small graph is split across many chunks + runs, and the
    /// merged output must STILL be byte-identical.
    #[test]
    fn multi_chunk_external_build_is_byte_identical() {
        let quads = test_quads(3000);
        let reference = build_reference(quads.clone());

        let dir = std::env::temp_dir().join(format!("rete-extbuild-mc-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");

        // drive the internals directly with a tiny chunk budget
        let tmp = TmpDir::create(&dir).unwrap();
        let mut chunker = Chunker::new(&tmp, 4 * 1024, GraphLayout::PerGraph); // ~4 KiB chunks
        for q in quads.iter().cloned() {
            chunker.push(q).unwrap();
        }
        let chunks = chunker.finish().unwrap();
        assert!(
            chunks.len() >= 4,
            "expected many chunks, got {}",
            chunks.len()
        );
        let statements: u64 = chunks.iter().map(|c| c.triple_count).sum();
        let (merged, remaps) = merge_dictionaries(&tmp, &chunks).unwrap();

        // tiny runs to force multi-run merging, chained across permutations
        let codec = crate::file::writer_codec();
        let (runs, _) = remap_chunks(
            &tmp,
            &chunks,
            &remaps,
            false,
            crate::index::IndexPermutation::Spo,
            256,
            256,
            None,
            None,
            None,
        )
        .unwrap();
        assert!(runs.len() >= 4, "expected many runs, got {}", runs.len());
        let (sections, count) = index_permutations(
            &tmp,
            runs,
            crate::index::PermSet::ALL,
            256,
            codec,
            "",
            &mut |_, _| Ok(()),
            &mut |_, _| {},
        )
        .unwrap();
        write_final_file(
            &out,
            &[],
            &[],
            &merged,
            &sections,
            None,
            None,
            None,
            count,
            codec,
            crate::index::PermSet::ALL,
            true,
        )
        .unwrap();

        let bytes = std::fs::read(&out).unwrap();
        assert_eq!(statements as usize, quads.len());
        assert_eq!(
            bytes, reference,
            "multi-chunk external build must be byte-identical"
        );
        drop(tmp);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// [`build_ext`] with the chunk budget forced down to `chunk` bytes, so a
    /// small graph becomes many chunks.
    fn build_ext_split(quads: &[RawQuad], chunk: u64) -> Vec<u8> {
        TEST_SPLIT.with(|c| c.set(Some((chunk, 1 << 10))));
        let (bytes, _) = build_ext(quads.to_vec(), 0);
        TEST_SPLIT.with(|c| c.set(None));
        bytes
    }

    /// The id remap tables were the part of the memory-bounded build that grew
    /// with the dataset: every chunk's stayed resident from the dictionary
    /// merge to the end of the remap. Now they go to disk as the merge writes
    /// them and one chunk's are loaded at a time. Cutting four times the
    /// graph into four times the chunks quadruples what the old build held
    /// and leaves what this one holds where it was: one chunk's tables, at
    /// most a quarter of the chunk budget. The files stay byte-identical.
    #[test]
    fn remap_memory_does_not_grow_with_the_chunk_count() {
        const CHUNK: u64 = 4 * 1024;
        let run = |n: usize| -> (u64, u64, u64) {
            let quads = test_quads(n);
            let reference = build_reference(quads.clone());
            let collector = crate::build_trace::Collector::start();
            let bytes = build_ext_split(&quads, CHUNK);
            let t = collector.snapshot();
            drop(collector);
            assert_eq!(bytes, reference, "{n} quads: external build drifted");
            (
                t.counter("chunks").unwrap(),
                t.counter("remap_total_bytes").unwrap(),
                t.counter("remap_peak_bytes").unwrap(),
            )
        };
        let (k1, total1, peak1) = run(1_000);
        let (k4, total4, peak4) = run(4_000);
        assert!(k1 >= 20 && k4 >= 3 * k1, "chunks: {k1}, then {k4}");
        // What the old merge held resident grows with the chunks…
        assert!(total4 >= 3 * total1, "tables: {total1} B, then {total4} B");
        assert!(
            total4 >= 50 * peak4,
            "{total4} B in all, {peak4} B resident"
        );
        // …what this one holds does not: every buffered statement is charged
        // at least 96 B against the chunk budget and brings at most six ids.
        assert!(
            peak4 <= peak1 * 3 / 2,
            "resident: {peak1} B, then {peak4} B"
        );
        assert!(
            peak4 <= (CHUNK + 1024) / 4,
            "{peak4} B for a {CHUNK} B chunk"
        );
    }

    /// G24: a term-dense stretch — every statement bringing two new terms,
    /// the OpenCitations Meta `oc:doiLink` tail — is sealed by its
    /// dictionary's size, not its bytes, so it takes more and smaller chunks
    /// than the bytes alone would cut; the rest of the graph is chunked as
    /// before. Chunk boundaries never reach the file: it is the in-RAM
    /// build's, and the one-chunk build's, byte for byte.
    #[test]
    fn term_dense_tail_seals_by_dictionary_and_stays_identical() {
        let mut quads = test_quads(2_000);
        for i in 0..3_000usize {
            quads.push((
                format!("<http://ex/s{}>", i % 300),
                "<https://w3id.org/oc/ontology/doiLink>".to_string(),
                format!("<https://doi.org/10.{}/x{i}>", 1000 + i % 7),
                None,
            ));
        }
        for i in 0..3_000usize {
            quads.push((
                format!("<http://ex/id/{i}>"),
                "<http://ex/hasLiteralValue>".to_string(),
                format!("\"10.{}/x{i}\"", 1000 + i % 7),
                None,
            ));
        }
        let reference = build_reference(quads.clone());
        let (one_chunk, _) = build_ext(quads.clone(), 0);
        assert_eq!(one_chunk, reference, "the one-chunk build drifted");

        let chunked = |working: Option<u64>| -> (Vec<u8>, u64, u64) {
            TEST_SPLIT.with(|c| c.set(Some((64 << 10, 1 << 16))));
            TEST_WORKING.with(|c| c.set(working));
            let collector = crate::build_trace::Collector::start();
            let (bytes, _) = build_ext(quads.clone(), 0);
            let t = collector.snapshot();
            drop(collector);
            TEST_SPLIT.with(|c| c.set(None));
            TEST_WORKING.with(|c| c.set(None));
            (
                bytes,
                t.counter("chunks").unwrap(),
                t.counter("chunks_term_sealed").unwrap_or(0),
            )
        };
        // By bytes alone (the cap never reached)...
        let (by_bytes, k_bytes, sealed_bytes) = chunked(Some(u64::MAX));
        assert_eq!(sealed_bytes, 0);
        // ...and with the cap at 2.4 times the byte budget: the head (about
        // 1.7 times its bytes with its dictionary) still reaches the byte
        // budget first, the dense tail (about 2.8 times) does not.
        let (by_terms, k_terms, sealed_terms) = chunked(Some(154 << 10));
        eprintln!("{k_bytes} chunks by bytes; {k_terms} with the cap, {sealed_terms} sealed by it");
        assert!(k_bytes >= 4, "{k_bytes} chunk(s) by bytes");
        // The tail is sealed by its dictionary, the head still by its bytes.
        assert!(
            sealed_terms >= 8 && k_terms - sealed_terms >= 4,
            "{sealed_terms} of {k_terms} chunk(s) sealed by the dictionary"
        );
        assert!(k_terms > k_bytes, "{k_terms} chunks, {k_bytes} by bytes");
        assert_eq!(by_bytes, reference, "the byte-chunked build drifted");
        assert_eq!(by_terms, reference, "the term-chunked build drifted");
    }

    /// G23: the spill is compressed and the permutations are chained, so the
    /// build never holds its id statements raw, let alone twice. Up to 0.4.1
    /// the permutation phase held `global.tri` plus one permutation's runs —
    /// 24 B per statement — beside the finished sections, and the dictionary
    /// merge the 12 B per statement of the chunk spills beside the raw term
    /// files. Here the recorded peak, finished sections included, stays under
    /// the output's size plus 6 B per statement; and the file is the same.
    #[test]
    fn compressed_spill_peak_stays_under_one_raw_copy() {
        let quads = test_quads(40_000);
        let n = quads.len() as u64;
        let reference = build_reference(quads.clone());
        TEST_SPLIT.with(|c| c.set(Some((256 << 10, 1 << 16))));
        TEST_RUNS.with(|c| c.set(Some((6_000, 6_000))));
        let collector = crate::build_trace::Collector::start();
        let (bytes, _) = build_ext(quads, 0);
        let t = collector.snapshot();
        drop(collector);
        TEST_SPLIT.with(|c| c.set(None));
        TEST_RUNS.with(|c| c.set(None));
        assert_eq!(bytes, reference, "the compressed spill changed the file");
        let peak = t.counter("scratch_peak_bytes").unwrap();
        let chunks = t.counter("chunks").unwrap();
        let out = bytes.len() as u64;
        eprintln!(
            "{n} statements, {chunks} chunks: spill peak {peak} B = {:.2} B per statement (output {out} B = {:.2})",
            peak as f64 / n as f64,
            out as f64 / n as f64
        );
        assert!(chunks >= 4, "{chunks} chunk(s)");
        // A raw copy of the statements alone would be 12 B each.
        assert!(
            peak <= out + 6 * n,
            "spill peak {peak} B for {n} statements and a {out} B file"
        );
    }

    /// The two dictionary writers must agree on the **separator keys**, not
    /// just on everything else. `finish_chunked` and
    /// `file::encode_chunked_dict_section` compute the previous chunk's last
    /// term from different sources — a spill file read back in slices, versus
    /// one contiguous buffer — so this is the place they can drift.
    ///
    /// The literals here are long enough that the object-only section really
    /// splits into chunks; a short-IRI graph would compare two one-chunk
    /// directories and prove nothing.
    #[test]
    fn separator_keyed_dictionary_is_byte_identical_across_writers() {
        let blob = "w".repeat(1200);
        let quads: Vec<RawQuad> = (0..900usize)
            .map(|i| {
                (
                    format!("<http://ex/s{i:04}>"),
                    "<http://ex/note>".to_string(),
                    // half share a long prefix (long separators), half diverge
                    // in their first bytes (one-byte separators)
                    if i % 2 == 0 {
                        format!("\"{blob}{i:04}\"")
                    } else {
                        format!("\"{i:04}{blob}\"")
                    },
                    None,
                )
            })
            .collect();

        let reference = build_reference(quads.clone());
        let (bytes, _) = build_ext(quads, 0);
        assert_eq!(
            bytes, reference,
            "the external builder's chunk directory drifted from the in-RAM one"
        );

        // …and the directory they agree on really is multi-chunk and keyed by
        // separators, not by the 1,206-byte literals it used to copy.
        let keys = crate::file::dict_chunk_keys_for_test(&bytes);
        let obj = &keys[2]; // section 2 = object-only, the one with the literals
        assert!(
            obj.len() > 4,
            "object-only section has {} chunks",
            obj.len()
        );
        assert!(obj[0].is_empty(), "chunk 0 must carry no separator");
        let longest = obj.iter().map(Vec::len).max().unwrap();
        assert!(
            longest < 1_200,
            "longest key is {longest} B — that is a stored term, not a separator"
        );

        // Every object term still resolves: the routing works in the merged file.
        let rete = crate::Rete::open(&bytes).unwrap();
        for i in (0..900usize).step_by(7) {
            let o = if i % 2 == 0 {
                format!("\"{blob}{i:04}\"")
            } else {
                format!("\"{i:04}{blob}\"")
            };
            assert!(
                rete.dictionary().object_id(&o).is_some(),
                "object {i} lost by the chunk directory"
            );
        }
    }

    /// …and the same, with the terms spread across **named graphs**. The graph
    /// column changes which chunk a term is first seen in, which changes what
    /// the per-chunk dictionaries look like — so the separator directory the two
    /// writers agree on has to survive quads, not just triples. Same shape as
    /// `separator_keyed_dictionary_is_byte_identical_across_writers` (#222),
    /// with the literals distributed over 30 graphs.
    #[test]
    fn separator_keyed_dictionary_survives_named_graphs() {
        let blob = "w".repeat(1200);
        let quads: Vec<RawQuad> = (0..900usize)
            .map(|i| {
                (
                    format!("<http://ex/s{i:04}>"),
                    "<http://ex/note>".to_string(),
                    if i % 2 == 0 {
                        format!("\"{blob}{i:04}\"")
                    } else {
                        format!("\"{i:04}{blob}\"")
                    },
                    // graph names generated out of order, so the graph merge has
                    // to sort them and the ordinals are not the insertion order
                    Some(format!("<http://ex/g{:02}>", (i * 7) % 30)),
                )
            })
            .collect();

        let reference = build_reference(quads.clone());
        let (bytes, stats) = build_ext(quads, 0);
        assert_eq!(
            bytes, reference,
            "the external builder's chunk directory drifted from the in-RAM one \
             once named graphs were in the input"
        );
        assert_eq!(stats.named_graphs, 30);

        let keys = crate::file::dict_chunk_keys_for_test(&bytes);
        let obj = &keys[2]; // section 2 = object-only, the one with the literals
        assert!(
            obj.len() > 4,
            "object-only section has {} chunks",
            obj.len()
        );
        assert!(obj[0].is_empty(), "chunk 0 must carry no separator");
        let longest = obj.iter().map(Vec::len).max().unwrap();
        assert!(
            longest < 1_200,
            "longest key is {longest} B — that is a stored term, not a separator"
        );
    }

    /// The external file must open and answer queries like any other build.
    #[test]
    fn external_build_output_is_queryable() {
        let quads = test_quads(1200);
        let (bytes, _) = build_ext(quads.clone(), 0);
        let rete = crate::Rete::open(&bytes).unwrap();
        // spot-check a known triple through the SPARQL engine
        let out = crate::eval_query(
            &rete,
            "SELECT (COUNT(*) AS ?n) WHERE { ?s <http://ex/p1> ?o }",
        )
        .unwrap();
        match out {
            crate::QueryOutput::Select(_, rows) => assert_eq!(rows.len(), 1),
            other => panic!("expected select, got {other:?}"),
        }
    }

    /// A finished permutation's spilled tiles, read back: the section (its
    /// directory and synopses rebuilt from the tiles, exactly as the tiler
    /// wrote them), every triple handed to `f` in the permutation's order.
    /// Tiles are independent zstd frames, so the file splits without its
    /// directory — which lived in the killed process's memory.
    #[cfg(feature = "compression")]
    fn section_from_tiles(
        path: &Path,
        codec: u8,
        f: &mut dyn FnMut(IdTriple) -> Result<(), ExtBuildError>,
    ) -> Result<TiledSection, ExtBuildError> {
        let mut file = File::open(path)?;
        let (mut buf, mut pos, mut eof) = (Vec::new(), 0usize, false);
        let mut dir: Vec<TileDirEntry> = Vec::new();
        loop {
            if !eof && buf.len() - pos < (4 << 20) {
                buf.drain(..pos);
                pos = 0;
                let at = buf.len();
                buf.resize(at + (16 << 20), 0);
                let n = file.read(&mut buf[at..])?;
                buf.truncate(at + n);
                eof = n == 0;
                continue;
            }
            if pos == buf.len() {
                break;
            }
            let len = zstd::zstd_safe::find_frame_compressed_size(&buf[pos..])
                .map_err(|_| ExtBuildError::Internal("a spilled tile is cut short"))?;
            let raw = crate::file::decompress(codec, &buf[pos..pos + len])
                .map_err(|_| ExtBuildError::Internal("a spilled tile does not decode"))?;
            let blk = crate::triples::TripleBlock::parse(&raw)
                .map_err(|_| ExtBuildError::Internal("a spilled tile does not parse"))?;
            let triples = blk.triples();
            let z = blk.zone();
            let (Some(first), Some(last)) = (triples.first(), triples.last()) else {
                return Err(ExtBuildError::Internal("an empty spilled tile"));
            };
            dir.push((
                first.0,
                last.0,
                len as u64,
                (z.min_b, z.max_b, z.min_c, z.max_c),
            ));
            for t in triples {
                f(t)?;
            }
            pos += len;
        }
        Ok(TiledSection::from_dir(&dir, path.to_path_buf()))
    }

    /// Restart the permutation chain of a spill whose build was killed in
    /// the permutation phase (see [`resume_from_spill`]): the sections of the
    /// finished permutations of `order`, rebuilt from their tiles, followed by
    /// the rest of the chain, re-run from the last finished one's tiles.
    #[cfg(feature = "compression")]
    fn resume_chain(
        tmp: &TmpDir,
        order: &[crate::index::IndexPermutation],
        statements: u64,
        run_len: usize,
        codec: u8,
    ) -> Result<Vec<TiledSection>, ExtBuildError> {
        let tiles = |p: crate::index::IndexPermutation| tmp.path(&format!("{}.tiles", p.name()));
        // A permutation's tiles file is created as its merge starts, after
        // the previous one's section is finished: the last one present was
        // cut short, every one before it is whole.
        let started = order.iter().take_while(|p| tiles(**p).exists()).count();
        if order.iter().skip(started).any(|p| tiles(*p).exists()) {
            return Err(ExtBuildError::Internal(
                "the permutations' tiles files have gaps",
            ));
        }
        if started < 2 {
            return Err(ExtBuildError::Internal(
                "killed in the first permutation: its runs are half consumed, rerun the build",
            ));
        }
        let cut = started - 1;
        // whatever the cut-short permutation left: its tiles and runs, and
        // the runs it was writing for the next one
        for entry in std::fs::read_dir(&tmp.dir)?.flatten() {
            let n = entry.file_name().to_string_lossy().into_owned();
            let doomed = order[cut..]
                .iter()
                .take(2)
                .any(|p| n.starts_with(&format!("{}.", p.name())));
            if doomed {
                let _ = std::fs::remove_file(entry.path());
            }
        }
        let mut sections = Vec::with_capacity(order.len());
        for &p in &order[..cut - 1] {
            sections.push(section_from_tiles(&tiles(p), codec, &mut |_| Ok(()))?);
        }
        let (prev, next) = (order[cut - 1], order[cut]);
        let mut spill = RunSpiller::<IdTriple>::new(&tmp.dir, next.name(), run_len);
        let mut n = 0u64;
        sections.push(section_from_tiles(&tiles(prev), codec, &mut |t| {
            n += 1;
            spill.push(next.forward(prev.back(t)))?;
            Ok(())
        })?);
        if n != statements {
            return Err(ExtBuildError::Internal(
                "the last finished section does not hold every statement",
            ));
        }
        let (rest, count) = index_chain(
            tmp,
            spill.finish()?,
            &order[cut..],
            run_len,
            codec,
            "",
            &mut |_, _| Ok(()),
            &mut |p, _| eprintln!("resume: {} done", p.name()),
        )?;
        if count != statements {
            return Err(ExtBuildError::Internal("permutation dedup counts diverge"));
        }
        sections.extend(rest);
        Ok(sections)
    }

    /// **Operational resume harness** (ignored; run explicitly with env vars):
    /// finish an external build whose process was killed in the permutation
    /// phase, from its surviving spill directory. Requires:
    ///   RETE_RESUME_SPILL   the .rete-extbuild-* dir
    ///   RETE_RESUME_OUT     output .rete path
    ///   RETE_RESUME_TERMS   merged dictionary term count
    ///   RETE_RESUME_QUADS   deduped triple count (statements when no dups)
    ///   RETE_RESUME_CARD    optional JSON card file to embed
    ///   RETE_RESUME_PERMS   the build's `--permutations`, 6 (default) or 3
    ///   RETE_RESUME_BUDGET_MB  sizes the sort runs (default 16384)
    ///
    /// The permutations are chained and each one's runs are consumed as they
    /// are merged, so no `global.tri` survives to restart from (up to 0.4.1
    /// one did). What survives is every finished permutation's tiles file,
    /// which holds every statement, sorted: [`resume_chain`] reads the last
    /// finished one back and runs the chain again from the permutation that
    /// was cut short. Not resumable: a kill in the first permutation (its
    /// runs are half consumed) or in the final write (each section is deleted
    /// once copied); a kill before the permutations never was.
    ///
    /// **Default graph only.** A spill from a build that had named graphs
    /// carries quad runs (`qSPO.run*`) and `g.graphs`, and this harness
    /// ignores both — it would resume as a file with the named graphs
    /// silently dropped. That is checked rather than commented.
    ///
    /// **A text index is carried over when it was finished.** Phase 3b leaves
    /// `tok.table` + `tok.postings` behind before any permutation is merged,
    /// and they are reused as they are. Text-index files of an unfinished
    /// phase (`global.tok`, `tok.run*`, `c<i>.tok`) are a hard stop for the
    /// same reason as the quad runs.
    #[test]
    #[ignore = "operational tool, driven by RETE_RESUME_* env vars"]
    #[cfg(feature = "compression")]
    fn resume_from_spill() {
        let spill = PathBuf::from(std::env::var("RETE_RESUME_SPILL").expect("RETE_RESUME_SPILL"));
        let names: Vec<String> = std::fs::read_dir(&spill)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        assert!(
            !names
                .iter()
                .any(|n| n.starts_with('q') || n == "g.graphs" || n.starts_with("named.")),
            "this spill has named quads; resuming it here would write a file with \
             the named graphs silently missing — rerun the build instead"
        );
        assert!(
            !names
                .iter()
                .any(|n| n == "global.tok" || n.starts_with("tok.run") || n.ends_with(".tok")),
            "this spill has an unfinished text index (global.tok / tok.run* / c<i>.tok); \
             resuming it here would write a file without it — rerun the build instead"
        );
        let out = PathBuf::from(std::env::var("RETE_RESUME_OUT").expect("RETE_RESUME_OUT"));
        let term_count: u64 = std::env::var("RETE_RESUME_TERMS").unwrap().parse().unwrap();
        let quad_count: u64 = std::env::var("RETE_RESUME_QUADS").unwrap().parse().unwrap();
        let metadata: Vec<u8> = std::env::var("RETE_RESUME_CARD")
            .ok()
            .map(|p| std::fs::read(p).unwrap())
            .unwrap_or_default();
        let perms = match std::env::var("RETE_RESUME_PERMS").as_deref() {
            Ok("3") => crate::index::PermSet::CORE,
            _ => crate::index::PermSet::ALL,
        };
        let budget_mb: u64 = std::env::var("RETE_RESUME_BUDGET_MB")
            .ok()
            .and_then(|v| v.parse().ok())
            .unwrap_or(16384);
        let run_len = ((budget_mb << 20) / 2 / 24) as usize;

        let sec = |name: &str| -> SectionFile {
            let path = spill.join(name);
            let len = std::fs::metadata(&path)
                .unwrap_or_else(|_| panic!("{name} is gone: the final write had begun"))
                .len();
            SectionFile { path, len }
        };
        let merged = MergedDict {
            section_files: [
                sec("g.shared.sec"),
                sec("g.subj.sec"),
                sec("g.obj.sec"),
                sec("g.pred.sec"),
            ],
            term_count,
            has_quoted: false,
            graph_names: None,
            graph_count: 0,
            schema_facts: Default::default(),
        };
        let tmp = TmpDir { dir: spill.clone() };
        let codec = crate::file::writer_codec();
        let order: Vec<_> = perms.iter().collect();
        let sections = resume_chain(&tmp, &order, quad_count, run_len, codec).unwrap();
        let (table, postings) = (spill.join("tok.table"), spill.join("tok.postings"));
        let text = if table.exists() && postings.exists() {
            let table_len = std::fs::metadata(&table).unwrap().len();
            let mut head = Vec::new();
            write_uvarint(&mut head, table_len);
            // The scope block in the token table decides kind 6 or 11, and
            // the header's named-graphs bit.
            let mut prefix = head.clone();
            prefix.extend(std::fs::read(&table).unwrap());
            let scope = crate::text_index::TextIndex::from_token_table(
                &prefix,
                codec,
                Box::new(|_, _| None),
            )
            .expect("tok.table parses")
            .scope()
            .clone();
            eprintln!("resume: reusing the text index");
            Some(crate::text_index_spill::TextSection {
                head,
                table,
                table_len,
                postings_len: std::fs::metadata(&postings).unwrap().len(),
                postings,
                partial: scope.restricts_predicates(),
                named: scope.covers_named_graphs(),
            })
        } else {
            None
        };
        write_final_file(
            &out,
            &metadata,
            &[],
            &merged,
            &sections,
            text.as_ref(),
            None,
            None,
            quad_count,
            codec,
            perms,
            false, // keep the spill until the file is verified
        )
        .unwrap();
        eprintln!("resume: wrote {}", out.display());
        std::mem::forget(tmp);
    }

    /// The resume path, end to end: a build "killed" as its fourth
    /// permutation starts (its tiles half written, its runs and the fifth's
    /// left as they were) resumes from the third's tiles to the same file.
    #[test]
    #[cfg(feature = "compression")]
    fn a_build_killed_mid_chain_resumes_to_the_same_file() {
        let quads = test_quads(5000);
        let reference = build_reference(quads.clone());
        let dir = std::env::temp_dir().join(format!("rete-extbuild-resume-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");
        let tmp = TmpDir::create(&dir).unwrap();
        let mut chunker = Chunker::new(&tmp, 16 * 1024, GraphLayout::PerGraph);
        for q in quads.iter().cloned() {
            chunker.push(q).unwrap();
        }
        let chunks = chunker.finish().unwrap();
        let (merged, remaps) = merge_dictionaries(&tmp, &chunks).unwrap();
        let order: Vec<_> = crate::index::PermSet::ALL.iter().collect();
        let codec = crate::file::writer_codec();
        let (runs, _) = remap_chunks(
            &tmp, &chunks, &remaps, false, order[0], 700, 700, None, None, None,
        )
        .unwrap();
        // The first three permutations finish; the chain stops there, so the
        // fourth's runs are what its merge would have read…
        let (_, n) = index_chain(
            &tmp,
            runs,
            &order[..3],
            700,
            codec,
            "",
            &mut |_, _| Ok(()),
            &mut |_, _| {},
        )
        .unwrap();
        // …and the fourth was cut short with half a tile on disk.
        std::fs::write(
            tmp.path(&format!("{}.tiles", order[3].name())),
            [0x28, 0xb5],
        )
        .unwrap();
        let sections = resume_chain(&tmp, &order, n, 700, codec).unwrap();
        write_final_file(
            &out,
            &[],
            &[],
            &merged,
            &sections,
            None,
            None,
            None,
            n,
            codec,
            crate::index::PermSet::ALL,
            true,
        )
        .unwrap();
        assert_eq!(
            std::fs::read(&out).unwrap(),
            reference,
            "resumed file differs"
        );
        drop(tmp);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A faithful reduction of the one published named-graph dataset
    /// (`switzerland-fedlex`: 56.3 M quads across 497,905 graphs, most of them
    /// tiny). Includes the three awkward shapes on purpose:
    ///   * default-graph triples living alongside named ones,
    ///   * the same triple asserted in two different graphs,
    ///   * a graph holding exactly one statement.
    fn fedlex_shaped_quads(graphs: usize, per_graph: usize) -> Vec<RawQuad> {
        let mut quads: Vec<RawQuad> = Vec::new();
        // the ontology triples fedlex keeps in the default graph
        for i in 0..40usize {
            quads.push((
                format!("<http://data.europa.eu/eli/ontology#p{i}>"),
                "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>".to_string(),
                "<http://www.w3.org/2002/07/owl#FunctionalProperty>".to_string(),
                None,
            ));
        }
        for g in 0..graphs {
            // the graph names are NOT generated in sorted order — the k-way
            // merge really has to order them
            let name = format!(
                "<https://fedlex.data.admin.ch/eli/cc/{:05}/graph>",
                g * 7 % 9973
            );
            let n = if g % 11 == 0 { 1 } else { per_graph };
            for i in 0..n {
                quads.push((
                    format!("<https://fedlex.data.admin.ch/eli/cc/{g}/art_{i}>"),
                    format!("<http://data.europa.eu/eli/ontology#pred{}>", i % 6),
                    match i % 4 {
                        0 => format!("<https://fedlex.data.admin.ch/eli/cc/{g}>"),
                        1 => format!("\"Artikel {i}\"@de"),
                        2 => format!("\"{i}\"^^<http://www.w3.org/2001/XMLSchema#integer>"),
                        _ => format!("_:b{}", i % 13),
                    },
                    Some(name.clone()),
                ));
            }
            // the SAME triple in a second graph — must survive in both
            quads.push((
                "<https://fedlex.data.admin.ch/eli/cc/shared>".to_string(),
                "<http://data.europa.eu/eli/ontology#in_force>".to_string(),
                "\"true\"^^<http://www.w3.org/2001/XMLSchema#boolean>".to_string(),
                Some(name.clone()),
            ));
            // …and in the default graph too
            if g == 0 {
                quads.push((
                    "<https://fedlex.data.admin.ch/eli/cc/shared>".to_string(),
                    "<http://data.europa.eu/eli/ontology#in_force>".to_string(),
                    "\"true\"^^<http://www.w3.org/2001/XMLSchema#boolean>".to_string(),
                    None,
                ));
            }
        }
        // duplicates, far apart, so dedup has something to do in both builders
        for i in 0..(quads.len() / 20) {
            let j = i * 17 % quads.len();
            quads.push(quads[j].clone());
        }
        quads
    }

    /// The acceptance criterion from #139: the same named-graph input built both
    /// ways must be **byte-identical**, not merely equivalent.
    #[test]
    fn named_graph_external_build_is_byte_identical() {
        let quads = fedlex_shaped_quads(60, 9);
        let reference = build_reference(quads.clone());
        let (bytes, stats) = build_ext(quads.clone(), 0);
        assert_eq!(
            bytes, reference,
            "named-graph external build must be byte-identical"
        );

        let header = crate::Header::from_bytes(&bytes).unwrap();
        assert_eq!(stats.statements as u64, header.quad_count);
        assert!(
            stats.statements < quads.len(),
            "fixture must contain duplicates for this to mean anything"
        );
        assert!(stats.named_graphs > 1);
        assert!(stats.default_triples > 0, "default graph must be populated");

        // …and the file really carries the graphs, not just the same bytes.
        let rete = crate::Rete::open(&bytes).unwrap();
        assert_eq!(rete.named_graph_count(), stats.named_graphs);
    }

    /// Many chunks + many sort runs + named graphs at once: the graph ordinals
    /// are merged across chunk-local rankings, so a graph first seen in chunk 7
    /// must land in the same slot as the same graph seen in chunk 0.
    #[test]
    fn multi_chunk_named_graph_build_is_byte_identical() {
        let quads = fedlex_shaped_quads(80, 7);
        let reference = build_reference(quads.clone());

        let dir = std::env::temp_dir().join(format!("rete-extbuild-mcng-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");
        let tmp = TmpDir::create(&dir).unwrap();
        let mut chunker = Chunker::new(&tmp, 4 * 1024, GraphLayout::PerGraph); // ~4 KiB chunks
        for q in quads.iter().cloned() {
            chunker.push(q).unwrap();
        }
        let chunks = chunker.finish().unwrap();
        assert!(
            chunks.len() >= 8,
            "expected many chunks, got {}",
            chunks.len()
        );
        let bytes = finish_from_chunks(&tmp, &chunks, &out, 256, 4).unwrap();
        assert_eq!(
            bytes, reference,
            "multi-chunk named-graph build must be byte-identical"
        );
        drop(tmp);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A graph too large for the budget takes the external per-permutation path
    /// instead of `GraphIndexBuilder`. Both must produce the same container, so
    /// force the spill with a 4-triple cap and compare against the in-RAM build.
    #[test]
    fn oversized_named_graph_spills_and_stays_identical() {
        let mut quads: Vec<RawQuad> = Vec::new();
        for i in 0..4000usize {
            quads.push((
                format!("<http://ex/s{}>", i % 400),
                "<http://ex/cites>".to_string(),
                format!("<http://ex/o{i}>"),
                Some("<http://ex/big>".to_string()),
            ));
        }
        for i in 0..30usize {
            quads.push((
                format!("<http://ex/s{i}>"),
                "<http://ex/p>".to_string(),
                format!("\"lit {i}\""),
                Some("<http://ex/tiny>".to_string()),
            ));
        }
        quads.push((
            "<http://ex/d>".into(),
            "<http://ex/p>".into(),
            "<http://ex/o>".into(),
            None,
        ));
        let reference = build_reference(quads.clone());

        let dir = std::env::temp_dir().join(format!("rete-extbuild-big-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");
        let tmp = TmpDir::create(&dir).unwrap();
        let mut chunker = Chunker::new(&tmp, 64 * 1024, GraphLayout::PerGraph);
        for q in quads.iter().cloned() {
            chunker.push(q).unwrap();
        }
        let chunks = chunker.finish().unwrap();
        // ram_triples = 4 forces `<http://ex/big>` (4,000 quads) down the spill
        // path while `<http://ex/tiny>` stays resident — both in one file.
        let bytes = finish_from_chunks(&tmp, &chunks, &out, 512, 4).unwrap();
        assert_eq!(
            bytes, reference,
            "a spilled named graph must encode identically to an in-RAM one"
        );
        drop(tmp);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Named graphs with an EMPTY default graph: the default index is still
    /// written (zero triples) and the header still says quads.
    #[test]
    fn named_only_build_is_byte_identical() {
        let quads: Vec<RawQuad> = (0..50usize)
            .map(|i| {
                (
                    format!("<http://ex/s{i}>"),
                    "<http://ex/p>".to_string(),
                    format!("\"v{i}\""),
                    Some(format!("<http://ex/g{}>", i % 5)),
                )
            })
            .collect();
        let reference = build_reference(quads.clone());
        let (bytes, stats) = build_ext(quads, 0);
        assert_eq!(bytes, reference, "named-only build must be byte-identical");
        assert_eq!(stats.default_triples, 0);
        assert_eq!(stats.named_graphs, 5);
        let rete = crate::Rete::open(&bytes).unwrap();
        assert_eq!(rete.named_graph_count(), 5);
    }

    /// Named graphs survive the trip: every distinct quad comes back out of the
    /// file, in the right graph, and `GRAPH ?g` still discriminates.
    #[test]
    fn named_graph_output_is_queryable() {
        let quads = fedlex_shaped_quads(12, 5);
        let (bytes, _) = build_ext(quads.clone(), 0);
        let rete = crate::Rete::open(&bytes).unwrap();

        type Quad = (String, String, String, Option<String>);
        let expected: std::collections::BTreeSet<Quad> = quads.iter().cloned().collect();
        let mut got: std::collections::BTreeSet<Quad> = std::collections::BTreeSet::new();
        for (s, p, o) in rete.dump(None) {
            got.insert((s, p, o, None));
        }
        let names: Vec<String> = rete.graph_names().iter().map(|g| g.to_string()).collect();
        for name in &names {
            for (s, p, o) in rete.dump(Some(name)) {
                got.insert((s, p, o, Some(name.clone())));
            }
        }
        assert_eq!(
            got, expected,
            "quads lost or misfiled by the external build"
        );

        let out = crate::eval_query(
            &rete,
            "SELECT (COUNT(DISTINCT ?g) AS ?n) WHERE { GRAPH ?g { ?s ?p ?o } }",
        )
        .unwrap();
        match out {
            crate::QueryOutput::Select(_, rows) => assert_eq!(rows.len(), 1),
            other => panic!("expected select, got {other:?}"),
        }
    }

    /// Drive phases 2-5 from an already-chunked spill with test-sized run and
    /// residency caps, returning the finished file image.
    fn finish_from_chunks(
        tmp: &TmpDir,
        chunks: &[ChunkInfo],
        out: &Path,
        run_len: usize,
        ram_triples: usize,
    ) -> Result<Vec<u8>, ExtBuildError> {
        let (merged, remaps) = merge_dictionaries(tmp, chunks)?;
        let has_named = chunks.iter().any(|c| c.quad_count > 0);
        let (tri_runs, quad_runs) = remap_chunks(
            tmp,
            chunks,
            &remaps,
            false,
            crate::index::IndexPermutation::Spo,
            run_len,
            run_len,
            None,
            None,
            None,
        )?;

        let codec = crate::file::writer_codec();
        let perms = crate::index::PermSet::ALL;
        let (sections, default_count) = index_permutations(
            tmp,
            tri_runs,
            perms,
            run_len,
            codec,
            "",
            &mut |_, _| Ok(()),
            &mut |_, _| {},
        )?;
        let named = if has_named {
            Some(build_named_graphs(
                tmp,
                quad_runs,
                merged.graph_names.as_deref().unwrap(),
                merged.graph_count,
                run_len,
                ram_triples,
                perms,
                codec,
            )?)
        } else {
            None
        };
        let quads = default_count + named.as_ref().map(|n| n.triples).unwrap_or(0);
        write_final_file(
            out,
            &[],
            &[],
            &merged,
            &sections,
            None,
            named.as_ref(),
            None,
            quads,
            codec,
            perms,
            true,
        )?;
        Ok(std::fs::read(out)?)
    }

    // ---- `--text-index` in the memory-bounded build -------------------------

    /// Literal-rich quads: titles and provenance-style descriptions in the
    /// default graph (multi-byte words included), provenance snapshots in
    /// named graphs, on top of the fedlex shape (its `"Artikel …"@de` literals
    /// live in named graphs too).
    fn text_quads() -> Vec<RawQuad> {
        let mut q = fedlex_shaped_quads(40, 9);
        for i in 0..600usize {
            let s = format!("<http://ex/w{}>", i % 150);
            q.push((
                s.clone(),
                "<http://purl.org/dc/terms/title>".to_string(),
                format!("\"Glucose Études {} on ünïcode café\"@en", i % 37),
                None,
            ));
            q.push((
                s.clone(),
                "<http://purl.org/dc/terms/description>".to_string(),
                format!("\"The entity {} has been modified.\"", i % 150),
                None,
            ));
            q.push((
                format!("<http://ex/w{}/prov/se/1>", i % 150),
                "<http://purl.org/dc/terms/description>".to_string(),
                format!("\"The entity has been created ({i}).\""),
                Some(format!("<http://ex/w{}/prov/>", i % 150)),
            ));
        }
        q
    }

    fn text_scopes() -> Vec<crate::text_index::TextIndexScope> {
        use crate::text_index::{TextIndexGraphs, TextIndexScope};
        let none: [&str; 0] = [];
        vec![
            TextIndexScope::default(),
            TextIndexScope::from_options(TextIndexGraphs::All, none, none).unwrap(),
            TextIndexScope::from_options(
                TextIndexGraphs::Default,
                none,
                ["http://purl.org/dc/terms/description"],
            )
            .unwrap(),
            TextIndexScope::from_options(
                TextIndexGraphs::All,
                ["http://purl.org/dc/terms/description"],
                none,
            )
            .unwrap(),
        ]
    }

    fn build_reference_text(
        quads: &[RawQuad],
        scope: &crate::text_index::TextIndexScope,
    ) -> Vec<u8> {
        let (bytes, _stats) = ingest::assemble_dataset_streaming_algo(
            |visit: &mut dyn FnMut(RawQuad)| {
                for q in quads.iter().cloned() {
                    visit(q);
                }
                Ok(())
            },
            false,
            scope.clone(),
            None,
            crate::PyramidAlgo::Louvain,
            |_, _, _| Vec::new(),
        )
        .unwrap();
        bytes
    }

    /// The public entry point with a text index; `split` forces many chunks and
    /// many text sort runs on a small graph.
    fn build_ext_text(
        quads: &[RawQuad],
        scope: &crate::text_index::TextIndexScope,
        split: Option<(u64, usize)>,
    ) -> Vec<u8> {
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir =
            std::env::temp_dir().join(format!("rete-extbuild-text-{}-{seq}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");
        TEST_SPLIT.with(|c| c.set(split));
        let res = build_external(
            |visit| {
                for q in quads.iter().cloned() {
                    visit(q)?;
                }
                Ok(())
            },
            &out,
            ExternalBuildOptions {
                memory_budget: 0,
                tmp_dir: Some(dir.clone()),
                text_index: Some(scope.clone()),
                ..Default::default()
            },
        );
        TEST_SPLIT.with(|c| c.set(None));
        res.unwrap();
        let bytes = std::fs::read(&out).unwrap();
        // The spill directory is gone; only the output remains.
        let left: Vec<_> = std::fs::read_dir(&dir)
            .unwrap()
            .map(|e| e.unwrap().file_name())
            .collect();
        assert_eq!(left, [std::ffi::OsString::from("out.rete")]);
        let _ = std::fs::remove_dir_all(&dir);
        bytes
    }

    /// B1's requirement: with `--text-index` the memory-bounded build writes the
    /// same TEXT_INDEX section as the in-RAM build — and, the pyramid being off
    /// on both sides, the same file — in one chunk and in many, for every scope.
    #[test]
    fn external_text_index_is_byte_identical_to_in_ram() {
        let quads = text_quads();
        for scope in text_scopes() {
            let reference = build_reference_text(&quads, &scope);
            let rh = crate::Header::from_bytes(&reference).unwrap();
            assert!(
                rh.text_index_len > 0,
                "{scope:?}: the fixture must index something"
            );
            assert_eq!(rh.text_index_partial, scope.restricts_predicates());
            assert_eq!(
                rh.text_index_covers_named_graphs(),
                scope.covers_named_graphs()
            );
            for split in [None, Some((4 * 1024, 1024))] {
                let bytes = build_ext_text(&quads, &scope, split);
                assert_eq!(
                    bytes, reference,
                    "{scope:?}, split {split:?}: external build must be byte-identical"
                );
            }
        }
    }

    /// The external file's text index answers searches, verifies, and carries
    /// its scope: the provenance text is found only when named graphs are in
    /// scope, the descriptions only when their predicate is.
    #[test]
    fn external_text_index_is_searchable_in_its_scope() {
        let quads = text_quads();
        let scopes = text_scopes();
        let search = |scope: &crate::text_index::TextIndexScope, word: &str| -> usize {
            let bytes = build_ext_text(&quads, scope, Some((4 * 1024, 1024)));
            assert!(crate::verify(&bytes).unwrap());
            let rete = crate::Rete::open(&bytes).unwrap();
            assert!(rete.has_text_index());
            assert_eq!(rete.text_index().unwrap().scope(), scope);
            rete.text_search(&[word], None, 0).len()
        };
        // "glucose": 150 titled works, in every scope that keeps titles.
        assert_eq!(search(&scopes[0], "glucose"), 150);
        assert_eq!(search(&scopes[2], "glucose"), 150);
        assert_eq!(
            search(&scopes[3], "glucose"),
            0,
            "an include-only scope drops titles"
        );
        // "modified": the default-graph descriptions.
        assert_eq!(search(&scopes[0], "modified"), 150);
        assert_eq!(search(&scopes[2], "modified"), 0, "excluded predicate");
        // "created": only in the named provenance graphs.
        assert_eq!(
            search(&scopes[0], "created"),
            0,
            "named graphs not in scope"
        );
        assert_eq!(search(&scopes[1], "created"), 150);
        assert_eq!(search(&scopes[3], "created"), 150);
        // A multi-byte word survives the spill's byte-level front coding.
        assert_eq!(search(&scopes[0], "études"), 150);
    }

    /// No literal in scope: no section at all, as the in-RAM build writes none.
    #[test]
    fn external_text_index_with_nothing_in_scope_writes_no_section() {
        let quads = test_quads(400);
        let none: [&str; 0] = [];
        let scope = crate::text_index::TextIndexScope::from_options(
            crate::text_index::TextIndexGraphs::Default,
            ["http://ex/never"],
            none,
        )
        .unwrap();
        let reference = build_reference_text(&quads, &scope);
        let bytes = build_ext_text(&quads, &scope, None);
        assert_eq!(bytes, reference);
        assert_eq!(crate::Header::from_bytes(&bytes).unwrap().text_index_len, 0);
    }

    // ---- quad index (`GraphLayout::Quad`) --------------------------------

    fn build_reference_quad(quads: Vec<RawQuad>, perms: crate::index::PermSet) -> Vec<u8> {
        let (bytes, _) = ingest::assemble_dataset_streaming_with_layout(
            move |visit: &mut dyn FnMut(RawQuad)| {
                for q in quads.iter().cloned() {
                    visit(q);
                }
                Ok(())
            },
            false,
            false,
            None,
            crate::PyramidAlgo::Louvain,
            perms,
            GraphLayout::Quad,
            |_, _, _| Vec::new(),
        )
        .unwrap();
        bytes
    }

    fn build_ext_quad(quads: Vec<RawQuad>, perms: crate::index::PermSet) -> (Vec<u8>, BuildStats) {
        static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let dir =
            std::env::temp_dir().join(format!("rete-extbuild-quad-{}-{seq}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");
        let stats = build_external(
            |visit| {
                for q in quads.iter().cloned() {
                    visit(q)?;
                }
                Ok(())
            },
            &out,
            ExternalBuildOptions {
                memory_budget: 0,
                tmp_dir: Some(dir.clone()),
                perms,
                graphs: GraphLayout::Quad,
                ..Default::default()
            },
        )
        .unwrap();
        let bytes = std::fs::read(&out).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
        (bytes, stats)
    }

    /// The external quad build writes the in-RAM build's bytes, for both
    /// permutation sets — the shared `QuadTiler` is what guarantees it.
    #[test]
    fn quad_external_build_is_byte_identical() {
        for perms in [crate::index::PermSet::ALL, crate::index::PermSet::CORE] {
            let quads = fedlex_shaped_quads(60, 9);
            let reference = build_reference_quad(quads.clone(), perms);
            let (bytes, stats) = build_ext_quad(quads.clone(), perms);
            assert_eq!(bytes, reference, "quad external build, {perms:?}");
            let header = crate::Header::from_bytes(&bytes).unwrap();
            assert!(header.has_quad_index());
            assert_eq!(stats.statements as u64, header.quad_count);
            let rete = crate::Rete::open(&bytes).unwrap();
            assert_eq!(rete.named_graph_count(), stats.named_graphs);
            assert!(crate::file::verify(&bytes).unwrap());
        }
    }

    /// Many chunks and many sort runs: graph names first seen in different
    /// chunks must merge into one dictionary id, and runs must merge back into
    /// the same tiles.
    #[test]
    fn multi_chunk_multi_run_quad_build_is_byte_identical() {
        let quads = fedlex_shaped_quads(80, 7);
        let reference = build_reference_quad(quads.clone(), crate::index::PermSet::ALL);

        let dir = std::env::temp_dir().join(format!("rete-extbuild-mcq-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let out = dir.join("out.rete");
        let tmp = TmpDir::create(&dir).unwrap();
        let mut chunker = Chunker::new(&tmp, 4 * 1024, GraphLayout::Quad);
        for q in quads.iter().cloned() {
            chunker.push(q).unwrap();
        }
        let chunks = chunker.finish().unwrap();
        assert!(
            chunks.len() >= 8,
            "expected many chunks, got {}",
            chunks.len()
        );
        let (merged, remaps) = merge_dictionaries(&tmp, &chunks).unwrap();
        assert_eq!(merged.graph_count, 0, "no separate graph-name merge");
        // 64-quad runs: many runs per order, chained and merged back.
        let (tri_runs, quad_runs) = remap_chunks(
            &tmp,
            &chunks,
            &remaps,
            true,
            crate::index::IndexPermutation::Spo,
            256,
            64,
            None,
            None,
            None,
        )
        .unwrap();
        assert!(quad_runs.len() >= 4, "{} quad run(s)", quad_runs.len());
        let codec = crate::file::writer_codec();
        let perms = crate::index::PermSet::ALL;
        let (sections, default_count) = index_permutations(
            &tmp,
            tri_runs,
            perms,
            256,
            codec,
            "",
            &mut |_, _| Ok(()),
            &mut |_, _| {},
        )
        .unwrap();
        let quad = build_quad_section(&tmp, quad_runs, 64, perms, codec).unwrap();
        write_final_file(
            &out,
            &[],
            &[],
            &merged,
            &sections,
            None,
            None,
            Some(&quad),
            default_count + quad.quad_count,
            codec,
            perms,
            true,
        )
        .unwrap();
        let bytes = std::fs::read(&out).unwrap();
        assert_eq!(bytes, reference, "multi-chunk, multi-run quad build");
        drop(tmp);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Frequent object-only terms with ties at every count, named graphs whose
    /// names are also objects, and the most frequent object of all, which is
    /// a subject in one statement at the very end.
    fn frequent_object_quads() -> Vec<RawQuad> {
        let rdf_type = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>";
        let mut q = test_quads(1_500);
        for i in 0..3_000usize {
            let s = format!("<http://ex/item/{i:05}>");
            q.push((
                s.clone(),
                rdf_type.into(),
                format!("<http://vocab/C{}>", i % 9),
                None,
            ));
            // forty statuses of 75 statements each: the cut falls in a tie
            q.push((
                s.clone(),
                "<http://ex/status>".into(),
                format!("\"st{}\"", i % 40),
                None,
            ));
            q.push((
                s.clone(),
                "<http://ex/doi>".into(),
                format!("<https://doi.org/10.1/x{i}>"),
                None,
            ));
            // a graph name is a term of the quad index (a subject), not
            // otherwise: there it is an object-only term like any other
            let g = format!("<http://ex/g{}>", i % 3);
            q.push((s, "<http://ex/inGraph>".into(), g.clone(), Some(g)));
        }
        for i in 0..4_000usize {
            q.push((
                format!("<http://ex/item/{:05}>", i % 3_000),
                "<http://ex/about>".into(),
                "<http://ex/hub>".into(),
                None,
            ));
        }
        q.push((
            "<http://ex/hub>".into(),
            "<http://ex/label>".into(),
            "\"hub\"".into(),
            None,
        ));
        q
    }

    /// G3: `--frequent-objects N` in the memory-bounded build. The chunks
    /// count, the walk before the merge picks the same `N` terms as the in-RAM
    /// builder — the same counts, duplicates included, the same tie-break —
    /// and the merge files them where it does: the file is the in-RAM
    /// build's, byte for byte, in one chunk or many, in either named-graph
    /// layout, for a cut inside a tie and for `N` past every candidate.
    #[test]
    fn frequent_objects_external_build_is_byte_identical() {
        use crate::write_opts::TEST_FREQUENT_OBJECTS;
        let quads = frequent_object_quads();
        let plain = build_reference(quads.clone());
        for n in [1usize, 9, 64, 100_000] {
            TEST_FREQUENT_OBJECTS.with(|c| c.set(Some(n)));
            let reference = build_reference(quads.clone());
            let (one_chunk, _) = build_ext(quads.clone(), 0);
            TEST_SPLIT.with(|c| c.set(Some((16 << 10, 1 << 16))));
            let collector = crate::build_trace::Collector::start();
            let (chunked, _) = build_ext(quads.clone(), 0);
            let chunks = collector.snapshot().counter("chunks").unwrap();
            drop(collector);
            let (quad_chunked, _) = build_ext_quad(quads.clone(), crate::index::PermSet::ALL);
            TEST_SPLIT.with(|c| c.set(None));
            let (quad_one, _) = build_ext_quad(quads.clone(), crate::index::PermSet::ALL);
            let quad_reference = build_reference_quad(quads.clone(), crate::index::PermSet::ALL);
            TEST_FREQUENT_OBJECTS.with(|c| c.set(None));

            assert!(chunks >= 8, "{chunks} chunk(s)");
            assert_ne!(reference, plain, "N = {n}: nothing was promoted");
            assert_eq!(one_chunk, reference, "N = {n}: one chunk");
            assert_eq!(chunked, reference, "N = {n}: {chunks} chunks");
            assert_eq!(quad_one, quad_reference, "N = {n}: quad index, one chunk");
            assert_eq!(quad_chunked, quad_reference, "N = {n}: quad index, chunked");

            let rete = crate::Rete::open(&chunked).unwrap();
            let dict = rete.dictionary();
            let shared = |t: &str| dict.object_id(t).unwrap() <= dict.shared_count();
            // The hub is a subject once: shared by role, never a candidate.
            assert!(shared("<http://ex/hub>"));
            if n >= 9 {
                assert!(
                    shared("<http://ex/g0>"),
                    "N = {n}: the busiest object-only term"
                );
            }
            if n == 64 {
                // three graphs, nine classes, forty statuses, then a tie
                assert!(shared("\"st39\"") && shared("<http://vocab/C8>"));
            }
        }
    }

    /// The quad layout needs the 3- or 6-permutation set (see `quad::check_perms`).
    #[test]
    fn quad_external_build_refuses_other_permutation_sets() {
        let dir = std::env::temp_dir().join(format!("rete-extbuild-q5-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let r = build_external(
            |visit| visit(("<a>".into(), "<p>".into(), "<b>".into(), Some("<g>".into()))),
            &dir.join("out.rete"),
            ExternalBuildOptions {
                tmp_dir: Some(dir.clone()),
                perms: crate::index::PermSet::from_bits(0b0001_1111).unwrap(),
                graphs: GraphLayout::Quad,
                ..Default::default()
            },
        );
        assert!(r.is_err());
        let _ = std::fs::remove_dir_all(&dir);
    }
}