cuttlefish-rs 0.0.0

Parallel, external-memory construction of uncolored and colored compacted de Bruijn graphs. The Cuttlefish 3 library.
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
//! External weak-super-k-mer bucket storage.
//!
//! Writers use the same 128-subgraph atlas hierarchy as Cuttlefish 3. Worker
//! buffers are drained in source/worker order, and open files are bounded so a
//! build does not require one descriptor per subgraph. The on-disk format is a
//! private, versioned Rust format and may be compressed with LZ4 blocks.

use crate::discontinuity::{current_open_file_count, open_file_limit};
use crate::dna::{Base, ascii_base_bits, valid_ascii_base_bits};
use crate::params::BuildParams;
use crate::partition::WeakSuperKmer;
use std::collections::BTreeMap;
use std::fs::{self, File, OpenOptions};
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom, Write};
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::{
    Arc, Mutex,
    atomic::{AtomicU64, AtomicUsize, Ordering},
};
use std::time::{Duration, Instant};

const MAGIC: &[u8; 8] = b"CF3WSK1\0";
const RECORD_COUNT_OFFSET: u64 = 34;
const HEADER_LEN: u64 = 42;
const COMPRESSED_BLOCK_HEADER_LEN: usize = 12;
const MAX_SOURCE_ID: u32 = 0x1f_ffff;
const MAX_OPEN_BUCKET_WRITERS: usize = 512;
/// Largest record the staging buffers emit: attribute plus four label words.
const MAX_RECORD_BYTES: usize = 4 + 4 * 8;
const MAX_PENDING_BUCKET_BYTES: usize = 1024 * 1024;
// Keep a colored source window coalesced in worker-local atlas buffers. C++
// retains roughly this amount per active worker set; the larger cap avoids
// repeatedly scanning every graph bucket merely to move tiny fragments into
// the shared atlas.
const MAX_TOTAL_PENDING_BYTES: usize = 128 * 1024 * 1024;
const ATLAS_GRAPH_COUNT: usize = 128;
const SUBGRAPH_CHUNK_BYTES: usize = 64 * 1024;

/// Bytes reserved per segment when buckets share container files.
///
/// The segment decouples the write unit from the read and reclaim units. A
/// flush stays at `SUBGRAPH_CHUNK_BYTES` because that is a memory budget --
/// 16,384 buckets times 64 KiB of staging -- while reads become segment-sized
/// and reclaim becomes block-aligned, which is what lets a consumed bucket be
/// punched out in full.
///
/// Sized from measurement on 149,998 Salmonella assemblies: 237.8 GB across
/// 16,385 buckets, mean 14.51 MB, p1 8.80 MB and p99 22.77 MB, so the
/// distribution is tight and the only real cost is the partial final segment
/// each bucket leaves. At 256 KiB that is 2.15 GB, 0.90% of the directory,
/// against 7.3 MB of chain metadata. Larger segments trade waste for fewer
/// reads, and reads were measured not to matter on local storage.
const DEFAULT_BUCKET_SEGMENT_BYTES: u64 = 256 * 1024;

/// Descriptors left for everything downstream of the bucket containers: the
/// edge-matrix containers, local-unitig buckets, stitch writers and the
/// coordinate-bucket fanout, all of which plan against the same budget.
const RESERVED_NON_BUCKET_DESCRIPTORS: usize = 384;

fn bucket_segment_bytes() -> u64 {
    static BYTES: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
    *BYTES.get_or_init(|| {
        std::env::var("CF3_RS_BUCKET_SEGMENT_BYTES")
            .ok()
            .and_then(|value| value.parse::<u64>().ok())
            .filter(|bytes| *bytes >= MAX_RECORD_BYTES as u64 && bytes % 4096 == 0)
            .unwrap_or(DEFAULT_BUCKET_SEGMENT_BYTES)
    })
}

/// The physical files backing the weak-super-k-mer buckets.
///
/// One container per atlas rather than one file per bucket, taking a 16,384
/// bucket build from 16,385 files to 129. Two things make this cheap rather
/// than intricate. Every bucket already writes under its atlas's mutex
/// (`SharedBucketSink::append_bucket`), and a container holds exactly one
/// atlas's buckets, so a container is only ever written by the thread holding
/// that lock and needs no lock of its own. And a flush no longer opens
/// anything: `BucketFile::open_existing` cost an `openat`, seven unbuffered
/// reads to re-read a 42-byte header, a revalidation, an `lseek` and a `close`
/// on *every* 64 KiB flush, which is about eleven syscalls times the 14.4
/// million flushes a full-corpus build performs. A container flush is one
/// `pwrite`.
///
/// The measured prize is smaller than that count suggests -- partitioning's
/// whole system time is 436.7 s of CPU across 64 threads, so the ceiling is
/// a couple of seconds of wall -- and larger somewhere unexpected. XFS
/// speculatively preallocates on extending writes, and with 16,385 repeatedly
/// reopened files it held 332.7 GB for 237.8 GB of data. Writing 128 files
/// instead returns that 94.9 GB.
#[derive(Debug)]
pub struct BucketContainers {
    files: Vec<BucketContainerFile>,
    segment_bytes: u64,
    /// Latched so an unsupported filesystem is reported once, not per bucket.
    punch_unsupported: std::sync::atomic::AtomicBool,
}

#[derive(Debug)]
struct BucketContainerFile {
    path: PathBuf,
    file: File,
    /// Next unreserved byte offset. Atomic for shape rather than contention:
    /// one atlas owns one container.
    cursor: AtomicU64,
}

impl BucketContainers {
    /// Containers a build may hold open, given the descriptor budget.
    ///
    /// One per atlas is the natural choice and what a normal limit allows, but
    /// it must not be a floor: the per-file layout this replaced held no
    /// descriptors between flushes, so a tight `ulimit -n` merely narrowed the
    /// fanout planners rather than failing the build. Sharing a container
    /// between atlases costs nothing -- the segment cursor is atomic, so
    /// concurrent reservations from different atlas locks are already safe --
    /// and keeps that property.
    fn plan_container_count(atlas_count: usize) -> usize {
        let budget = open_file_limit()
            .saturating_sub(current_open_file_count())
            // Local contraction opens the edge-matrix containers and the
            // local-unitig buckets on top of these, and the fanout planners
            // want room of their own.
            .saturating_sub(RESERVED_NON_BUCKET_DESCRIPTORS)
            / 2;
        atlas_count.min(budget.max(1))
    }

    fn create(bucket_dir: &Path, container_count: usize) -> Result<Self, BucketError> {
        let mut files = Vec::with_capacity(container_count);
        for index in 0..container_count {
            let path = bucket_dir.join(format!("{index:05}.wskc"));
            let file = OpenOptions::new()
                .create(true)
                .truncate(true)
                .read(true)
                .write(true)
                .open(&path)
                .map_err(|source| BucketError::Io {
                    path: path.clone(),
                    source,
                })?;
            files.push(BucketContainerFile {
                path,
                file,
                cursor: AtomicU64::new(0),
            });
        }
        Ok(Self {
            files,
            segment_bytes: bucket_segment_bytes(),
            punch_unsupported: std::sync::atomic::AtomicBool::new(false),
        })
    }

    /// Opens the containers a finished manifest names, for reading.
    fn open(
        bucket_dir: &Path,
        container_count: usize,
        segment_bytes: u64,
    ) -> Result<Self, BucketError> {
        let mut files = Vec::with_capacity(container_count);
        for index in 0..container_count {
            let path = bucket_dir.join(format!("{index:05}.wskc"));
            let file = OpenOptions::new()
                .read(true)
                .write(true)
                .open(&path)
                .map_err(|source| BucketError::Io {
                    path: path.clone(),
                    source,
                })?;
            files.push(BucketContainerFile {
                path,
                file,
                cursor: AtomicU64::new(0),
            });
        }
        Ok(Self {
            files,
            segment_bytes,
            punch_unsupported: std::sync::atomic::AtomicBool::new(false),
        })
    }

    #[inline]
    pub fn segment_bytes(&self) -> u64 {
        self.segment_bytes
    }

    #[inline]
    pub fn len(&self) -> usize {
        self.files.len()
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }

    #[inline]
    fn reserve_segment(&self, container: usize) -> u64 {
        self.files[container]
            .cursor
            .fetch_add(self.segment_bytes, Ordering::Relaxed)
    }

    fn write_at(&self, container: usize, offset: u64, bytes: &[u8]) -> Result<(), BucketError> {
        let file = &self.files[container];
        file.file
            .write_all_at(bytes, offset)
            .map_err(|source| BucketError::Io {
                path: file.path.clone(),
                source,
            })
    }

    fn read_at(&self, container: usize, offset: u64, buf: &mut [u8]) -> Result<(), BucketError> {
        let file = &self.files[container];
        file.file
            .read_exact_at(buf, offset)
            .map_err(|source| BucketError::Io {
                path: file.path.clone(),
                source,
            })
    }

    /// Releases a consumed bucket's segments without disturbing its neighbours.
    ///
    /// This is not optional, which measurement rather than reasoning settled.
    /// The per-file layout unlinked each bucket as local contraction consumed
    /// it, and containers cannot: a container is only droppable once all 128
    /// of its buckets are done. Containers do start about 94 GB below the
    /// per-file layout, because they do not accumulate XFS speculative
    /// preallocation, and the expectation was that this covered it. It does
    /// not -- the work-directory peak moves out of the end of partitioning and
    /// into local contraction, where the containers still hold everything
    /// while local-unitig buckets, labels and the edge matrix accumulate on
    /// top, and peak disk rose 24.5 GB.
    ///
    /// Punching restores the incremental release. Segments are reserved at a
    /// 4 KiB multiple, so a punch frees whole filesystem blocks rather than
    /// leaving partial ones behind -- the one thing raw extents, averaging
    /// 16.1 KiB and unaligned, could not have done. Adjacent segments are
    /// punched in one call.
    pub fn release_segments(&self, container: usize, segments: &[u32]) {
        if segments.is_empty() {
            return;
        }
        let mut ordered = segments.to_vec();
        ordered.sort_unstable();
        let file = &self.files[container];
        let mut start = u64::from(ordered[0]) * self.segment_bytes;
        let mut end = start + self.segment_bytes;
        for &index in &ordered[1..] {
            let offset = u64::from(index) * self.segment_bytes;
            if offset == end {
                end += self.segment_bytes;
                continue;
            }
            self.report_punch(punch_hole(&file.file, start, end - start));
            start = offset;
            end = offset + self.segment_bytes;
        }
        self.report_punch(punch_hole(&file.file, start, end - start));
    }

    /// Says once if the filesystem will not punch holes.
    ///
    /// Reclaim failing is not an error -- the container is unlinked wholesale
    /// at the end regardless -- but it silently costs peak disk, which is most
    /// of what the container layout is for. HFS+ and some network filesystems
    /// do not implement it, and macOS rejects a range that is not aligned to
    /// the filesystem block size. Better to say so than to leave someone
    /// wondering why the work directory is larger than documented.
    fn report_punch(&self, punched: bool) {
        if punched || self.punch_unsupported.swap(true, Ordering::Relaxed) {
            return;
        }
        eprintln!(
            "cuttlefish3-rs: this filesystem will not punch holes, so consumed \
             bucket space is held until the build ends; peak disk will be higher"
        );
    }

    pub fn paths(&self) -> impl Iterator<Item = &Path> {
        self.files.iter().map(|file| file.path.as_path())
    }
}

/// Punches `len` bytes at `offset` out of `file`.
///
/// There is no portable interface for this and no crate that abstracts one:
/// Linux spells it `fallocate(FALLOC_FL_PUNCH_HOLE)` and macOS spells it
/// `fcntl(F_PUNCHHOLE)`, and both `nix` and `rustix` gate their `fallocate`
/// behind `target_os = "linux"` with no Apple equivalent offered. So the two
/// are written out here.
///
/// Both interfaces require the range to be filesystem-block aligned -- macOS
/// returns `EINVAL` for a punch that is not a multiple of the block size --
/// which every call here satisfies by construction, because offsets and
/// lengths are whole segments and `bucket_segment_bytes` admits only multiples
/// of 4096. That is a second, independent reason buckets got segments rather
/// than the raw 16.1 KiB extents a flush would otherwise produce.
///
/// Failure is ignored on purpose. A filesystem without hole punching -- an old
/// HFS+ volume, or a network mount -- costs disk rather than correctness,
/// because the container is unlinked wholesale at the end regardless.
#[cfg(target_os = "linux")]
fn punch_hole(file: &File, offset: u64, len: u64) -> bool {
    use std::os::fd::AsRawFd;
    // SAFETY: the descriptor is owned by `file` and outlives the call, and the
    // kernel validates the range itself.
    unsafe {
        libc::fallocate(
            file.as_raw_fd(),
            libc::FALLOC_FL_KEEP_SIZE | libc::FALLOC_FL_PUNCH_HOLE,
            offset as libc::off_t,
            len as libc::off_t,
        ) == 0
    }
}

#[cfg(target_vendor = "apple")]
fn punch_hole(file: &File, offset: u64, len: u64) -> bool {
    use std::os::fd::AsRawFd;
    let punch = libc::fpunchhole_t {
        fp_flags: 0,
        reserved: 0,
        fp_offset: offset as libc::off_t,
        fp_length: len as libc::off_t,
    };
    // SAFETY: as above; `punch` outlives the call and F_PUNCHHOLE reads it as
    // a `*const fpunchhole_t`.
    unsafe { libc::fcntl(file.as_raw_fd(), libc::F_PUNCHHOLE, &punch) == 0 }
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
fn punch_hole(_file: &File, _offset: u64, _len: u64) -> bool {
    false
}

/// Sequential reader over one bucket's segment chain.
///
/// `BucketReader` uses its source purely as a `Read`, so presenting the chain
/// this way leaves the whole decode path -- record iteration, the compressed
/// block framing, the borrowed-record fast path -- exactly as it was for whole
/// files. Reads stop at each segment boundary, and the caller's `BufReader`
/// hides that.
#[derive(Debug)]
struct SegmentChainReader {
    containers: Arc<BucketContainers>,
    container: usize,
    segments: Vec<u64>,
    len: u64,
    pos: u64,
}

impl Read for SegmentChainReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.pos >= self.len || buf.is_empty() {
            return Ok(0);
        }
        let segment_bytes = self.containers.segment_bytes;
        let index = (self.pos / segment_bytes) as usize;
        let within = self.pos % segment_bytes;
        let room = (segment_bytes - within).min(self.len - self.pos);
        let take = (buf.len() as u64).min(room) as usize;
        let offset = self.segments[index] + within;
        self.containers
            .read_at(self.container, offset, &mut buf[..take])
            .map_err(std::io::Error::other)?;
        self.pos += take as u64;
        Ok(take)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BucketEmitStats {
    pub bucket_dir: PathBuf,
    pub bucket_files: usize,
    pub bytes_written: u64,
}

pub struct BucketEmitter {
    bucket_dir: PathBuf,
    k: u16,
    minimizer_len: u16,
    graph_count: usize,
    colored: bool,
    compress_buckets: bool,
    label_words: usize,
    files: BTreeMap<usize, BucketFileMeta>,
    writers: BTreeMap<usize, BucketFile>,
    pending: Vec<PendingBucket>,
    pending_bytes: usize,
    scratch: CompressionScratch,
}

pub struct SharedBucketSink {
    bucket_dir: PathBuf,
    containers: BucketContainers,
    k: u16,
    minimizer_len: u16,
    graph_count: usize,
    colored: bool,
    compress_buckets: bool,
    label_words: usize,
    workers: usize,
    atlases: Vec<Mutex<SharedBucketAtlas>>,
    flush_calls: AtomicU64,
    flush_nanos: AtomicU64,
}

pub struct SharedBucketEmitter {
    sink: Arc<SharedBucketSink>,
    pending: Vec<PendingBucket>,
    uncolored_pending: Vec<PendingColoredAtlas>,
    colored_pending: Vec<PendingColoredAtlas>,
    pending_bytes: usize,
    deferred_uncolored: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct BucketFileMeta {
    path: PathBuf,
    records: u64,
    bytes_written: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct PendingBucket {
    records: u64,
    bytes: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
struct PendingColoredAtlas {
    graph_ids: Vec<u16>,
    bytes: Vec<u8>,
}

#[derive(Default)]
struct SharedBucketFileMeta {
    buffer: Vec<u8>,
    buffer_records: u64,
    total_records: u64,
    written_records: u64,
    bytes_written: u64,
    /// Segment indices this bucket owns, in write order.
    segments: Vec<u32>,
    /// Bytes used in the last segment; a flush that overruns it straddles into
    /// a freshly reserved one, which the reader stitches back because it walks
    /// the chain in order.
    segment_used: u64,
}

struct SharedBucketAtlas {
    first_graph_id: usize,
    files: Vec<SharedBucketFileMeta>,
    buffered_bytes: usize,
    /// Shared by every flush through this atlas, which the atlas lock already
    /// serializes, so it costs no contention and saves an allocation per block.
    scratch: CompressionScratch,
}

#[derive(Default)]
struct SharedBucketFlushStats {
    calls: u64,
}

/// Where one bucket's bytes live.
///
/// Both forms are real: the shared production sink writes containers, and
/// `BucketEmitter` -- the serial emitter the tests and the legacy path use --
/// still writes one file per bucket with its header inline. Keeping the enum
/// lets the reader serve both without duplicating the decode path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BucketLocation {
    /// One whole file, carrying its own 42-byte header.
    File(PathBuf),
    /// A chain of segments inside a shared container. The header that a whole
    /// file would carry lives in the manifest instead, so nothing has to be
    /// re-read and revalidated per flush.
    Container {
        container: usize,
        /// Segment indices in write order; byte offset is index * segment_bytes.
        segments: Vec<u32>,
        /// Logical length, which is the sum of the payload written into those
        /// segments and is generally less than their reserved capacity.
        bytes: u64,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Manifest entry for one weak-super-k-mer bucket.
pub struct BucketManifestEntry {
    pub graph_id: usize,
    pub records: u64,
    pub location: BucketLocation,
}

impl BucketManifestEntry {
    /// Bytes this bucket occupies, for the longest-bucket-first scheduler.
    ///
    /// Containers make this free. The per-file layout had to `stat` all 16,384
    /// buckets before local contraction could sort them.
    pub fn stored_bytes(&self) -> Result<u64, BucketError> {
        match &self.location {
            BucketLocation::File(path) => {
                fs::metadata(path)
                    .map(|meta| meta.len())
                    .map_err(|source| BucketError::Io {
                        path: path.clone(),
                        source,
                    })
            }
            BucketLocation::Container { bytes, .. } => Ok(*bytes),
        }
    }

    /// The whole-file path, when the bucket is one.
    pub fn file_path(&self) -> Option<&Path> {
        match &self.location {
            BucketLocation::File(path) => Some(path.as_path()),
            BucketLocation::Container { .. } => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Versioned parameters decoded from a bucket file header.
pub struct BucketHeader {
    pub k: u16,
    pub minimizer_len: u16,
    pub graph_count: usize,
    pub graph_id: usize,
    pub colored: bool,
    pub compressed: bool,
    pub interleaved_compression: bool,
    pub label_words: usize,
    pub records: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
/// Decoded weak-super-k-mer record with an ASCII label.
pub struct BucketRecord {
    pub graph_id: usize,
    pub len: usize,
    pub source_id: Option<u32>,
    pub left_discontinuous: bool,
    pub right_discontinuous: bool,
    pub label: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
/// Decoded weak-super-k-mer record retaining its packed two-bit label.
pub struct BucketPackedRecord {
    pub graph_id: usize,
    pub len: usize,
    pub source_id: Option<u32>,
    pub left_discontinuous: bool,
    pub right_discontinuous: bool,
    pub words: Vec<u64>,
}

pub(crate) struct BorrowedBucketPackedRecord<'a> {
    pub graph_id: usize,
    pub len: usize,
    pub source_id: Option<u32>,
    pub left_discontinuous: bool,
    pub right_discontinuous: bool,
    pub words: &'a [u64],
}

/// Byte source behind a `BucketReader`.
///
/// The decode path treats its source as a plain sequential `Read`, so a
/// segment chain slots in beside a whole file without any of the record
/// iteration, block framing, or borrowed-record handling needing to know.
enum BucketSource {
    File(File),
    Chain(SegmentChainReader),
}

impl Read for BucketSource {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self {
            Self::File(file) => file.read(buf),
            Self::Chain(chain) => chain.read(buf),
        }
    }
}

/// Opens buckets, whichever layout the directory uses.
///
/// A container directory keeps the shared header in its manifest, so this owns
/// both and hands out readers; a whole-file directory carries the header in
/// each bucket and this just opens paths. Threading one of these through the
/// consumers replaces threading a path per bucket.
pub struct BucketStore {
    containers: Option<Arc<BucketContainers>>,
    header: Option<ContainerManifestHeader>,
}

impl BucketStore {
    /// Opens a bucket directory and reads its manifest.
    pub fn open_dir(
        bucket_dir: impl AsRef<Path>,
    ) -> Result<(Self, Vec<BucketManifestEntry>), BucketError> {
        let bucket_dir = bucket_dir.as_ref();
        if let Some((header, entries)) = read_container_manifest(bucket_dir)? {
            let containers =
                BucketContainers::open(bucket_dir, header.container_count, header.segment_bytes)?;
            return Ok((
                Self {
                    containers: Some(Arc::new(containers)),
                    header: Some(header),
                },
                entries,
            ));
        }
        let entries = read_manifest(bucket_dir)?;
        Ok((
            Self {
                containers: None,
                header: None,
            },
            entries,
        ))
    }

    /// A store for a directory that is known to hold whole bucket files.
    pub fn files_only() -> Self {
        Self {
            containers: None,
            header: None,
        }
    }

    pub fn containers(&self) -> Option<&Arc<BucketContainers>> {
        self.containers.as_ref()
    }

    /// Opens one bucket for reading.
    pub fn reader(&self, entry: &BucketManifestEntry) -> Result<BucketReader, BucketError> {
        match &entry.location {
            BucketLocation::File(path) => BucketReader::open(path),
            BucketLocation::Container {
                container,
                segments,
                bytes,
            } => {
                let (Some(containers), Some(header)) = (&self.containers, &self.header) else {
                    return Err(BucketError::MalformedRecord);
                };
                BucketReader::open_chain(
                    Arc::clone(containers),
                    *container,
                    segments.clone(),
                    *bytes,
                    header.bucket_header(entry.graph_id, entry.records),
                )
            }
        }
    }
}

/// Streaming reader for one versioned weak-super-k-mer bucket.
pub struct BucketReader {
    path: PathBuf,
    file: BufReader<BucketSource>,
    header: BucketHeader,
    records_read: u64,
    block_attrs: Vec<u8>,
    block_labels: Vec<u8>,
    block_interleaved: Vec<u8>,
    compressed_block: Vec<u8>,
    block_records: usize,
    block_record: usize,
}

impl BucketReader {
    pub fn open(path: impl AsRef<Path>) -> Result<Self, BucketError> {
        let path = path.as_ref().to_path_buf();
        let file = File::open(&path).map_err(|source| BucketError::Io {
            path: path.clone(),
            source,
        })?;
        let mut file = BufReader::with_capacity(1024 * 1024, BucketSource::File(file));
        let header = read_header(&mut file, &path)?;

        Ok(Self {
            path,
            file,
            header,
            records_read: 0,
            block_attrs: Vec::new(),
            block_labels: Vec::new(),
            block_interleaved: Vec::new(),
            compressed_block: Vec::new(),
            block_records: 0,
            block_record: 0,
        })
    }

    /// Opens a bucket stored as a segment chain.
    ///
    /// There is no inline header to skip: a container's buckets keep theirs in
    /// the manifest, so the chain starts at the first record byte and the
    /// caller supplies the header it would otherwise have read.
    fn open_chain(
        containers: Arc<BucketContainers>,
        container: usize,
        segments: Vec<u32>,
        bytes: u64,
        header: BucketHeader,
    ) -> Result<Self, BucketError> {
        let segment_bytes = containers.segment_bytes();
        let path = containers.files[container].path.clone();
        let chain = SegmentChainReader {
            containers,
            container,
            segments: segments
                .iter()
                .map(|s| u64::from(*s) * segment_bytes)
                .collect(),
            len: bytes,
            pos: 0,
        };
        Ok(Self {
            path,
            file: BufReader::with_capacity(1024 * 1024, BucketSource::Chain(chain)),
            header,
            records_read: 0,
            block_attrs: Vec::new(),
            block_labels: Vec::new(),
            block_interleaved: Vec::new(),
            compressed_block: Vec::new(),
            block_records: 0,
            block_record: 0,
        })
    }

    #[inline]
    pub fn header(&self) -> &BucketHeader {
        &self.header
    }

    pub fn next_record(&mut self) -> Result<Option<BucketRecord>, BucketError> {
        let mut record = BucketRecord::default();
        if self.next_record_into(&mut record)? {
            Ok(Some(record))
        } else {
            Ok(None)
        }
    }

    pub fn next_record_into(&mut self, record: &mut BucketRecord) -> Result<bool, BucketError> {
        let mut packed = BucketPackedRecord::default();
        if !self.next_packed_record_into(&mut packed)? {
            return Ok(false);
        }

        record.graph_id = packed.graph_id;
        record.len = packed.len;
        record.source_id = packed.source_id;
        record.left_discontinuous = packed.left_discontinuous;
        record.right_discontinuous = packed.right_discontinuous;
        decode_label_into(&packed.words, packed.len, &mut record.label)?;
        Ok(true)
    }

    pub fn next_packed_record_into(
        &mut self,
        record: &mut BucketPackedRecord,
    ) -> Result<bool, BucketError> {
        if self.records_read == self.header.records {
            return Ok(false);
        }

        let mut fixed = [0u8; 4];
        let fixed_len = if self.header.colored { 4 } else { 2 };
        if self.header.compressed {
            if self.block_record == self.block_records {
                self.read_compressed_block()?;
            }
            let start = self.block_record * fixed_len;
            if self.header.interleaved_compression {
                let record_len = record_size(self.header.colored, self.header.label_words);
                let start = self.block_record * record_len;
                fixed[..fixed_len]
                    .copy_from_slice(&self.block_interleaved[start..start + fixed_len]);
            } else {
                fixed[..fixed_len].copy_from_slice(&self.block_attrs[start..start + fixed_len]);
            }
        } else {
            self.file
                .read_exact(&mut fixed[..fixed_len])
                .map_err(|source| BucketError::Io {
                    path: self.path.clone(),
                    source,
                })?;
        }
        let packed_attr = if self.header.colored {
            u32::from_le_bytes(fixed[0..4].try_into().unwrap())
        } else {
            u16::from_le_bytes(fixed[0..2].try_into().unwrap()) as u32
        };

        record.words.clear();
        record.words.resize(self.header.label_words, 0);
        for (word_idx, word) in record.words.iter_mut().enumerate() {
            if self.header.compressed {
                if self.header.interleaved_compression {
                    let record_len = record_size(self.header.colored, self.header.label_words);
                    let start = self.block_record * record_len + fixed_len + word_idx * 8;
                    *word = u64::from_le_bytes(
                        self.block_interleaved[start..start + 8].try_into().unwrap(),
                    );
                } else {
                    let start = (self.block_record * self.header.label_words + word_idx) * 8;
                    *word =
                        u64::from_le_bytes(self.block_labels[start..start + 8].try_into().unwrap());
                }
            } else {
                *word = read_u64(&mut self.file, &self.path)?;
            }
        }

        let len = (packed_attr & 0xff) as usize;
        let source_id = self
            .header
            .colored
            .then_some((packed_attr >> 10) & MAX_SOURCE_ID);
        record.graph_id = self.header.graph_id;
        record.len = len;
        record.source_id = source_id;
        record.left_discontinuous = (packed_attr & (1 << 8)) != 0;
        record.right_discontinuous = (packed_attr & (1 << 9)) != 0;

        self.records_read += 1;
        if self.header.compressed {
            self.block_record += 1;
        }
        Ok(true)
    }

    pub fn try_for_each_packed_record<E, F>(
        &mut self,
        record: &mut BucketPackedRecord,
        mut f: F,
    ) -> Result<(), E>
    where
        E: From<BucketError>,
        F: FnMut(&BucketPackedRecord) -> Result<(), E>,
    {
        let remaining = self.header.records.saturating_sub(self.records_read);
        if remaining == 0 {
            return Ok(());
        }
        if self.header.compressed {
            while self.next_packed_record_into(record).map_err(E::from)? {
                f(record)?;
            }
            return Ok(());
        }
        let record_size = record_size(self.header.colored, self.header.label_words);
        let payload_bytes = remaining
            .checked_mul(record_size as u64)
            .ok_or(BucketError::TooManyRecords)?;
        let mut payload = vec![0u8; payload_bytes as usize];
        self.file
            .read_exact(&mut payload)
            .map_err(|source| BucketError::Io {
                path: self.path.clone(),
                source,
            })?;

        for chunk in payload.chunks_exact(record_size) {
            let (packed_attr, words_start) = if self.header.colored {
                (u32::from_le_bytes(chunk[0..4].try_into().unwrap()), 4)
            } else {
                (
                    u16::from_le_bytes(chunk[0..2].try_into().unwrap()) as u32,
                    2,
                )
            };

            record.words.clear();
            record.words.reserve(self.header.label_words);
            for word_idx in 0..self.header.label_words {
                let start = words_start + word_idx * 8;
                record.words.push(u64::from_le_bytes(
                    chunk[start..start + 8].try_into().unwrap(),
                ));
            }

            let len = (packed_attr & 0xff) as usize;
            let source_id = self
                .header
                .colored
                .then_some((packed_attr >> 10) & MAX_SOURCE_ID);
            record.graph_id = self.header.graph_id;
            record.len = len;
            record.source_id = source_id;
            record.left_discontinuous = (packed_attr & (1 << 8)) != 0;
            record.right_discontinuous = (packed_attr & (1 << 9)) != 0;

            self.records_read += 1;
            f(record)?;
        }
        Ok(())
    }

    pub(crate) fn try_for_each_borrowed_packed_record<E, F>(&mut self, mut f: F) -> Result<(), E>
    where
        E: From<BucketError>,
        F: FnMut(BorrowedBucketPackedRecord<'_>) -> Result<(), E>,
    {
        if !self.header.compressed {
            let mut record = BucketPackedRecord::default();
            return self.try_for_each_packed_record(&mut record, |record| {
                f(BorrowedBucketPackedRecord {
                    graph_id: record.graph_id,
                    len: record.len,
                    source_id: record.source_id,
                    left_discontinuous: record.left_discontinuous,
                    right_discontinuous: record.right_discontinuous,
                    words: &record.words,
                })
            });
        }
        if self.header.label_words > 4 {
            return Err(E::from(BucketError::MalformedRecord));
        }

        let fixed_len = if self.header.colored { 4 } else { 2 };
        while self.records_read < self.header.records {
            if self.block_record == self.block_records {
                self.read_compressed_block().map_err(E::from)?;
            }
            let record_index = self.block_record;
            let (packed_attr, words_bytes) = if self.header.interleaved_compression {
                let record_len = record_size(self.header.colored, self.header.label_words);
                let start = record_index * record_len;
                let attr = if self.header.colored {
                    u32::from_le_bytes(self.block_interleaved[start..start + 4].try_into().unwrap())
                } else {
                    u16::from_le_bytes(self.block_interleaved[start..start + 2].try_into().unwrap())
                        as u32
                };
                (
                    attr,
                    &self.block_interleaved[start + fixed_len..start + record_len],
                )
            } else {
                let attr_start = record_index * fixed_len;
                let attr = if self.header.colored {
                    u32::from_le_bytes(
                        self.block_attrs[attr_start..attr_start + 4]
                            .try_into()
                            .unwrap(),
                    )
                } else {
                    u16::from_le_bytes(
                        self.block_attrs[attr_start..attr_start + 2]
                            .try_into()
                            .unwrap(),
                    ) as u32
                };
                let words_start = record_index * self.header.label_words * 8;
                (
                    attr,
                    &self.block_labels[words_start..words_start + self.header.label_words * 8],
                )
            };
            let mut words = [0u64; 4];
            for (word, bytes) in words[..self.header.label_words]
                .iter_mut()
                .zip(words_bytes.chunks_exact(8))
            {
                *word = u64::from_le_bytes(bytes.try_into().unwrap());
            }
            self.records_read += 1;
            self.block_record += 1;
            f(BorrowedBucketPackedRecord {
                graph_id: self.header.graph_id,
                len: (packed_attr & 0xff) as usize,
                source_id: self
                    .header
                    .colored
                    .then_some((packed_attr >> 10) & MAX_SOURCE_ID),
                left_discontinuous: packed_attr & (1 << 8) != 0,
                right_discontinuous: packed_attr & (1 << 9) != 0,
                words: &words[..self.header.label_words],
            })?;
        }
        Ok(())
    }

    pub fn records(self) -> BucketRecords {
        BucketRecords { reader: self }
    }

    fn read_compressed_block(&mut self) -> Result<(), BucketError> {
        let mut header = [0u8; COMPRESSED_BLOCK_HEADER_LEN];
        self.file
            .read_exact(&mut header)
            .map_err(|source| BucketError::Io {
                path: self.path.clone(),
                source,
            })?;
        let records = u32::from_le_bytes(header[0..4].try_into().unwrap()) as usize;
        let attr_bytes = u32::from_le_bytes(header[4..8].try_into().unwrap()) as usize;
        let label_bytes = u32::from_le_bytes(header[8..12].try_into().unwrap()) as usize;
        if records == 0
            || attr_bytes == 0
            || (!self.header.interleaved_compression && label_bytes == 0)
            || (self.header.interleaved_compression && label_bytes != 0)
        {
            return Err(BucketError::MalformedRecord);
        }
        let remaining = usize::try_from(self.header.records - self.records_read)
            .map_err(|_| BucketError::TooManyRecords)?;
        if records > remaining {
            return Err(BucketError::MalformedRecord);
        }
        self.compressed_block.resize(attr_bytes + label_bytes, 0);
        self.file
            .read_exact(&mut self.compressed_block)
            .map_err(|source| BucketError::Io {
                path: self.path.clone(),
                source,
            })?;
        let fixed_len = if self.header.colored { 4 } else { 2 };
        if self.header.interleaved_compression {
            self.block_interleaved.resize(
                records * record_size(self.header.colored, self.header.label_words),
                0,
            );
            let decoded = lz4_flex::block::decompress_into(
                &self.compressed_block[..attr_bytes],
                &mut self.block_interleaved,
            )
            .map_err(|_| BucketError::MalformedRecord)?;
            if decoded != self.block_interleaved.len() {
                return Err(BucketError::MalformedRecord);
            }
            self.block_records = records;
            self.block_record = 0;
            return Ok(());
        }
        self.block_attrs.resize(records * fixed_len, 0);
        self.block_labels
            .resize(records * self.header.label_words * 8, 0);
        let decoded_attrs = lz4_flex::block::decompress_into(
            &self.compressed_block[..attr_bytes],
            &mut self.block_attrs,
        )
        .map_err(|_| BucketError::MalformedRecord)?;
        let decoded_labels = lz4_flex::block::decompress_into(
            &self.compressed_block[attr_bytes..],
            &mut self.block_labels,
        )
        .map_err(|_| BucketError::MalformedRecord)?;
        if decoded_attrs != self.block_attrs.len() || decoded_labels != self.block_labels.len() {
            return Err(BucketError::MalformedRecord);
        }
        self.block_records = records;
        self.block_record = 0;
        Ok(())
    }
}

/// Iterator over decoded records from a [`BucketReader`].
pub struct BucketRecords {
    reader: BucketReader,
}

impl Iterator for BucketRecords {
    type Item = Result<BucketRecord, BucketError>;

    fn next(&mut self) -> Option<Self::Item> {
        self.reader.next_record().transpose()
    }
}

const CONTAINER_MANIFEST_MAGIC: &[u8; 8] = b"CF3WSKC1";
const CONTAINER_MANIFEST_NAME: &str = "manifest.bin";

/// The parameters every bucket in a container directory shares.
///
/// This is the 42-byte per-bucket header, hoisted. Under the per-file layout it
/// was written once per bucket and then re-read and revalidated on *every*
/// 64 KiB flush, because a flush reopened the file to append. Stored once for
/// the whole directory, that disappears; the only genuinely per-bucket field
/// was the record count, which the manifest already carried.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContainerManifestHeader {
    pub k: u16,
    pub minimizer_len: u16,
    pub graph_count: usize,
    pub colored: bool,
    pub label_words: usize,
    pub compressed: bool,
    pub interleaved_compression: bool,
    pub segment_bytes: u64,
    pub container_count: usize,
}

impl ContainerManifestHeader {
    fn compression_code(&self) -> u8 {
        if self.interleaved_compression {
            2
        } else {
            u8::from(self.compressed)
        }
    }

    /// The per-bucket header a whole-file reader would have found inline.
    fn bucket_header(&self, graph_id: usize, records: u64) -> BucketHeader {
        BucketHeader {
            k: self.k,
            minimizer_len: self.minimizer_len,
            graph_count: self.graph_count,
            graph_id,
            colored: self.colored,
            label_words: self.label_words,
            compressed: self.compressed,
            interleaved_compression: self.interleaved_compression,
            records,
        }
    }
}

fn write_u32_to(out: &mut Vec<u8>, value: u32) {
    out.extend_from_slice(&value.to_le_bytes());
}

fn write_u64_to(out: &mut Vec<u8>, value: u64) {
    out.extend_from_slice(&value.to_le_bytes());
}

/// Writes the container manifest: shared header, then one record per bucket.
pub fn write_container_manifest(
    bucket_dir: &Path,
    header: &ContainerManifestHeader,
    entries: &[BucketManifestEntry],
) -> Result<(), BucketError> {
    let path = bucket_dir.join(CONTAINER_MANIFEST_NAME);
    let mut out = Vec::with_capacity(64 + entries.len() * 32);
    out.extend_from_slice(CONTAINER_MANIFEST_MAGIC);
    out.extend_from_slice(&header.k.to_le_bytes());
    out.extend_from_slice(&header.minimizer_len.to_le_bytes());
    write_u64_to(&mut out, header.graph_count as u64);
    out.push(u8::from(header.colored));
    out.push(header.label_words as u8);
    out.push(header.compression_code());
    out.push(0);
    write_u64_to(&mut out, header.segment_bytes);
    write_u64_to(&mut out, header.container_count as u64);
    write_u64_to(&mut out, entries.len() as u64);
    for entry in entries {
        let BucketLocation::Container {
            container,
            segments,
            bytes,
        } = &entry.location
        else {
            return Err(BucketError::MalformedManifest(path.clone()));
        };
        write_u64_to(&mut out, entry.graph_id as u64);
        write_u64_to(&mut out, entry.records);
        write_u64_to(&mut out, *bytes);
        write_u32_to(&mut out, *container as u32);
        write_u32_to(&mut out, segments.len() as u32);
        for segment in segments {
            write_u32_to(&mut out, *segment);
        }
    }
    fs::write(&path, &out).map_err(|source| BucketError::Io {
        path: path.clone(),
        source,
    })
}

struct ManifestCursor<'a> {
    bytes: &'a [u8],
    pos: usize,
    path: &'a Path,
}

impl<'a> ManifestCursor<'a> {
    fn take(&mut self, len: usize) -> Result<&'a [u8], BucketError> {
        let end = self
            .pos
            .checked_add(len)
            .filter(|end| *end <= self.bytes.len())
            .ok_or_else(|| BucketError::MalformedManifest(self.path.to_path_buf()))?;
        let slice = &self.bytes[self.pos..end];
        self.pos = end;
        Ok(slice)
    }

    fn u16(&mut self) -> Result<u16, BucketError> {
        Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
    }

    fn u32(&mut self) -> Result<u32, BucketError> {
        Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
    }

    fn u64(&mut self) -> Result<u64, BucketError> {
        Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap()))
    }
}

/// Reads the container manifest, if this directory has one.
pub fn read_container_manifest(
    bucket_dir: impl AsRef<Path>,
) -> Result<Option<(ContainerManifestHeader, Vec<BucketManifestEntry>)>, BucketError> {
    let path = bucket_dir.as_ref().join(CONTAINER_MANIFEST_NAME);
    let bytes = match fs::read(&path) {
        Ok(bytes) => bytes,
        Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(source) => {
            return Err(BucketError::Io {
                path: path.clone(),
                source,
            });
        }
    };
    let mut cursor = ManifestCursor {
        bytes: &bytes,
        pos: 0,
        path: &path,
    };
    if cursor.take(8)? != CONTAINER_MANIFEST_MAGIC {
        return Err(BucketError::MalformedManifest(path.clone()));
    }
    let k = cursor.u16()?;
    let minimizer_len = cursor.u16()?;
    let graph_count = cursor.u64()? as usize;
    let flags = cursor.take(4)?;
    let (colored, label_words, compression) = (flags[0], flags[1], flags[2]);
    if colored > 1 || compression > 2 || flags[3] != 0 {
        return Err(BucketError::MalformedManifest(path.clone()));
    }
    let header = ContainerManifestHeader {
        k,
        minimizer_len,
        graph_count,
        colored: colored == 1,
        label_words: label_words as usize,
        compressed: compression != 0,
        interleaved_compression: compression == 2,
        segment_bytes: cursor.u64()?,
        container_count: cursor.u64()? as usize,
    };
    if header.segment_bytes == 0
        || header.label_words as usize != label_word_count(k, minimizer_len)
    {
        return Err(BucketError::MalformedManifest(path.clone()));
    }
    let bucket_count = cursor.u64()? as usize;
    let mut entries = Vec::with_capacity(bucket_count);
    for _ in 0..bucket_count {
        let graph_id = cursor.u64()? as usize;
        let records = cursor.u64()?;
        let bytes_len = cursor.u64()?;
        let container = cursor.u32()? as usize;
        let segment_count = cursor.u32()? as usize;
        if graph_id >= graph_count || container >= header.container_count {
            return Err(BucketError::MalformedManifest(path.clone()));
        }
        let mut segments = Vec::with_capacity(segment_count);
        for _ in 0..segment_count {
            segments.push(cursor.u32()?);
        }
        // The chain must be able to hold the logical length, and must not be
        // more than one segment longer than it needs to be.
        let capacity = segment_count as u64 * header.segment_bytes;
        if bytes_len > capacity || capacity.saturating_sub(bytes_len) >= header.segment_bytes {
            return Err(BucketError::MalformedManifest(path.clone()));
        }
        entries.push(BucketManifestEntry {
            graph_id,
            records,
            location: BucketLocation::Container {
                container,
                segments,
                bytes: bytes_len,
            },
        });
    }
    Ok(Some((header, entries)))
}

/// Reads and validates `manifest.tsv` from a bucket directory.
pub fn read_manifest(
    bucket_dir: impl AsRef<Path>,
) -> Result<Vec<BucketManifestEntry>, BucketError> {
    let bucket_dir = bucket_dir.as_ref();
    let path = bucket_dir.join("manifest.tsv");
    let file = File::open(&path).map_err(|source| BucketError::Io {
        path: path.clone(),
        source,
    })?;
    let mut out = Vec::new();

    for (line_no, line) in BufReader::new(file).lines().enumerate() {
        let line = line.map_err(|source| BucketError::Io {
            path: path.clone(),
            source,
        })?;
        if line_no == 0 {
            if line != "graph_id\trecords\tpath" {
                return Err(BucketError::MalformedManifest(path.clone()));
            }
            continue;
        }
        if line.trim().is_empty() {
            continue;
        }

        let mut fields = line.splitn(3, '\t');
        let graph_id = fields
            .next()
            .ok_or_else(|| BucketError::MalformedManifest(path.clone()))?
            .parse()
            .map_err(|_| BucketError::MalformedManifest(path.clone()))?;
        let records = fields
            .next()
            .ok_or_else(|| BucketError::MalformedManifest(path.clone()))?
            .parse()
            .map_err(|_| BucketError::MalformedManifest(path.clone()))?;
        let bucket_path = fields
            .next()
            .ok_or_else(|| BucketError::MalformedManifest(path.clone()))?;
        out.push(BucketManifestEntry {
            graph_id,
            records,
            location: BucketLocation::File(PathBuf::from(bucket_path)),
        });
    }

    Ok(out)
}

pub fn coalesce_bucket_manifest(
    bucket_dir: &Path,
    entries: &[BucketManifestEntry],
) -> Result<BucketEmitStats, BucketError> {
    coalesce_bucket_manifest_with_threads(bucket_dir, entries, 1)
}

pub fn coalesce_bucket_manifest_with_threads(
    bucket_dir: &Path,
    entries: &[BucketManifestEntry],
    threads: usize,
) -> Result<BucketEmitStats, BucketError> {
    let mut by_graph = BTreeMap::<usize, Vec<BucketManifestEntry>>::new();
    for entry in entries {
        by_graph
            .entry(entry.graph_id)
            .or_default()
            .push(entry.clone());
    }

    let groups = by_graph.into_iter().collect::<Vec<_>>();
    let workers = threads.max(1).min(groups.len().max(1));
    let mut manifest = if workers == 1 {
        let mut manifest = Vec::with_capacity(groups.len());
        for group in &groups {
            manifest.push(coalesce_bucket_group(bucket_dir, group)?);
        }
        manifest
    } else {
        let next_group = AtomicUsize::new(0);
        let mut manifest = std::thread::scope(|scope| {
            let mut handles = Vec::new();
            for _ in 0..workers {
                let next_group = &next_group;
                let groups = &groups;
                handles.push(scope.spawn(move || {
                    let mut local = Vec::new();
                    loop {
                        let group_idx = next_group.fetch_add(1, Ordering::Relaxed);
                        let Some(group) = groups.get(group_idx) else {
                            break;
                        };
                        local.push(coalesce_bucket_group(bucket_dir, group)?);
                    }
                    Ok::<_, BucketError>(local)
                }));
            }

            let mut manifest = Vec::with_capacity(groups.len());
            for handle in handles {
                manifest.extend(handle.join().map_err(|_| BucketError::WorkerPanic)??);
            }
            Ok::<_, BucketError>(manifest)
        })?;
        manifest.sort_by_key(|(graph_id, _, path, _)| (*graph_id, path.clone()));
        manifest
    };
    let total_bytes = manifest.iter().map(|(_, _, _, bytes)| *bytes).sum();
    let public_manifest = manifest
        .drain(..)
        .map(|(graph_id, records, path, _)| (graph_id, records, path))
        .collect::<Vec<_>>();

    write_manifest(bucket_dir, &public_manifest)?;

    Ok(BucketEmitStats {
        bucket_dir: bucket_dir.to_path_buf(),
        bucket_files: public_manifest.len(),
        bytes_written: total_bytes,
    })
}

fn coalesce_bucket_group(
    bucket_dir: &Path,
    group: &(usize, Vec<BucketManifestEntry>),
) -> Result<(usize, u64, PathBuf, u64), BucketError> {
    let (graph_id, graph_entries) = group;
    // Coalescing concatenates raw payloads, which only whole uncompressed
    // bucket files expose; a container's buckets are read through the store.
    let entry_path = |entry: &BucketManifestEntry| {
        entry
            .file_path()
            .map(Path::to_path_buf)
            .ok_or_else(|| BucketError::MalformedManifest(bucket_dir.to_path_buf()))
    };
    let first_header = read_bucket_header(&entry_path(&graph_entries[0])?)?;
    let mut writer = BucketFile::create(
        bucket_dir,
        first_header.k,
        first_header.minimizer_len,
        first_header.graph_count,
        *graph_id,
        first_header.colored,
        first_header.label_words,
        first_header.compressed,
    )?;

    for entry in graph_entries {
        let path = entry_path(entry)?;
        let copied_records = copy_bucket_payload(&path, &first_header, *graph_id, &mut writer)?;
        if copied_records != entry.records {
            return Err(BucketError::MalformedHeader(path));
        }
    }

    writer.finish()?;
    Ok((
        *graph_id,
        writer.records,
        writer.path.clone(),
        writer.bytes_written,
    ))
}

fn read_bucket_header(path: &Path) -> Result<BucketHeader, BucketError> {
    let mut file = File::open(path).map_err(|source| BucketError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    read_header(&mut file, path)
}

fn copy_bucket_payload(
    path: &Path,
    expected: &BucketHeader,
    graph_id: usize,
    writer: &mut BucketFile,
) -> Result<u64, BucketError> {
    let mut file = File::open(path).map_err(|source| BucketError::Io {
        path: path.to_path_buf(),
        source,
    })?;
    let header = read_header(&mut file, path)?;
    if header.k != expected.k
        || header.minimizer_len != expected.minimizer_len
        || header.graph_count != expected.graph_count
        || header.graph_id != graph_id
        || header.colored != expected.colored
        || header.label_words != expected.label_words
    {
        return Err(BucketError::MalformedHeader(path.to_path_buf()));
    }

    let payload_bytes = header
        .records
        .checked_mul(record_size(header.colored, header.label_words) as u64)
        .ok_or(BucketError::TooManyRecords)?;
    let actual_len = file
        .metadata()
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })?
        .len();
    if actual_len != HEADER_LEN + payload_bytes {
        return Err(BucketError::MalformedHeader(path.to_path_buf()));
    }

    file.seek(SeekFrom::Start(HEADER_LEN))
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })?;
    let copied =
        std::io::copy(&mut file.take(payload_bytes), &mut writer.file).map_err(|source| {
            BucketError::Io {
                path: path.to_path_buf(),
                source,
            }
        })?;
    if copied != payload_bytes {
        return Err(BucketError::MalformedHeader(path.to_path_buf()));
    }
    writer.records = writer
        .records
        .checked_add(header.records)
        .ok_or(BucketError::TooManyRecords)?;
    writer.bytes_written += copied;
    Ok(header.records)
}

impl BucketEmitter {
    pub fn create(params: &BuildParams, graph_count: usize) -> Result<Self, BucketError> {
        Self::create_in_dir(params, graph_count, bucket_dir(params))
    }

    pub fn create_in_dir(
        params: &BuildParams,
        graph_count: usize,
        bucket_dir: PathBuf,
    ) -> Result<Self, BucketError> {
        if graph_count > u64::MAX as usize {
            return Err(BucketError::GraphCountTooLarge(graph_count));
        }

        if bucket_dir.exists() {
            fs::remove_dir_all(&bucket_dir).map_err(|source| BucketError::Io {
                path: bucket_dir.clone(),
                source,
            })?;
        }
        fs::create_dir_all(&bucket_dir).map_err(|source| BucketError::Io {
            path: bucket_dir.clone(),
            source,
        })?;

        Ok(Self {
            bucket_dir,
            k: params.k,
            minimizer_len: params.minimizer_len,
            graph_count,
            colored: params.color,
            compress_buckets: params.color || params.compress_buckets,
            label_words: label_word_count(params.k, params.minimizer_len),
            files: BTreeMap::new(),
            scratch: CompressionScratch::default(),
            writers: BTreeMap::new(),
            pending: vec![PendingBucket::default(); graph_count],
            pending_bytes: 0,
        })
    }

    pub fn add(&mut self, superkmer: &WeakSuperKmer, seq: &[u8]) -> Result<(), BucketError> {
        if superkmer.graph_id >= self.graph_count {
            return Err(BucketError::InvalidGraphId(superkmer.graph_id));
        }
        if seq.len() > u8::MAX as usize {
            return Err(BucketError::LabelTooLong(seq.len()));
        }

        let attr = if self.colored {
            let source_id = superkmer.source_id.ok_or(BucketError::MissingSourceId)?;
            if source_id > MAX_SOURCE_ID {
                return Err(BucketError::SourceIdTooLarge(source_id));
            }
            pack_colored_attr(
                seq.len(),
                source_id,
                superkmer.left_discontinuous,
                superkmer.right_discontinuous,
            )
        } else {
            pack_uncolored_attr(
                seq.len(),
                superkmer.left_discontinuous,
                superkmer.right_discontinuous,
            )
        };
        let graph_id = superkmer.graph_id;
        let record_len = record_size(self.colored, self.label_words);
        let pending = &mut self.pending[graph_id];
        pending.records = pending
            .records
            .checked_add(1)
            .ok_or(BucketError::TooManyRecords)?;
        append_record(
            &mut pending.bytes,
            attr,
            graph_id,
            seq,
            self.label_words,
            self.colored,
        )?;
        self.pending_bytes += record_len;

        if self.pending[graph_id].bytes.len() >= MAX_PENDING_BUCKET_BYTES {
            self.flush_pending_bucket(graph_id)?;
        } else if self.pending_bytes >= MAX_TOTAL_PENDING_BYTES {
            self.flush_largest_pending_bucket()?;
        }
        Ok(())
    }

    fn flush_largest_pending_bucket(&mut self) -> Result<(), BucketError> {
        let Some((graph_id, _)) = self
            .pending
            .iter()
            .enumerate()
            .max_by_key(|(_, pending)| pending.bytes.len())
        else {
            return Ok(());
        };
        self.flush_pending_bucket(graph_id)
    }

    fn flush_pending_bucket(&mut self, graph_id: usize) -> Result<(), BucketError> {
        if self.pending[graph_id].bytes.is_empty() {
            return Ok(());
        }
        let pending = std::mem::take(&mut self.pending[graph_id]);
        self.pending_bytes -= pending.bytes.len();

        let (records, bytes_written) = {
            self.ensure_writer(graph_id)?;
            let Self {
                writers, scratch, ..
            } = self;
            let writer = writers.get_mut(&graph_id).expect("writer just ensured");
            writer.write_records(&pending.bytes, pending.records, scratch)?
        };
        let meta = self.files.get_mut(&graph_id).unwrap();
        meta.records = records;
        meta.bytes_written = bytes_written;
        Ok(())
    }

    fn ensure_writer(&mut self, graph_id: usize) -> Result<&mut BucketFile, BucketError> {
        if !self.writers.contains_key(&graph_id) {
            self.evict_writer_if_needed(graph_id)?;
            let writer = match self.files.get(&graph_id) {
                Some(meta) => {
                    BucketFile::open_existing(&meta.path, meta.records, meta.bytes_written)?
                }
                None => {
                    let writer = BucketFile::create(
                        &self.bucket_dir,
                        self.k,
                        self.minimizer_len,
                        self.graph_count,
                        graph_id,
                        self.colored,
                        self.label_words,
                        self.compress_buckets,
                    )?;
                    self.files.insert(
                        graph_id,
                        BucketFileMeta {
                            path: writer.path.clone(),
                            records: writer.records,
                            bytes_written: writer.bytes_written,
                        },
                    );
                    writer
                }
            };
            self.writers.insert(graph_id, writer);
        }

        Ok(self.writers.get_mut(&graph_id).unwrap())
    }

    fn evict_writer_if_needed(&mut self, requested_graph_id: usize) -> Result<(), BucketError> {
        if self.writers.len() < MAX_OPEN_BUCKET_WRITERS {
            return Ok(());
        }

        let evict_graph_id = self
            .writers
            .keys()
            .copied()
            .find(|&graph_id| graph_id != requested_graph_id)
            .unwrap_or(requested_graph_id);
        if let Some(mut writer) = self.writers.remove(&evict_graph_id) {
            writer.flush()?;
        }
        Ok(())
    }

    pub fn finish(mut self) -> Result<BucketEmitStats, BucketError> {
        let mut manifest = Vec::new();
        for graph_id in 0..self.pending.len() {
            if !self.pending[graph_id].bytes.is_empty() {
                self.flush_pending_bucket(graph_id)?;
            }
        }

        for (graph_id, meta) in &self.files {
            if let Some(writer) = self.writers.get_mut(graph_id) {
                writer.finish()?;
            } else {
                BucketFile::finish_closed(&meta.path, meta.records)?;
            }
            manifest.push((*graph_id, meta.records, meta.path.clone()));
        }

        write_manifest(&self.bucket_dir, &manifest)?;

        Ok(BucketEmitStats {
            bucket_dir: self.bucket_dir,
            bucket_files: manifest.len(),
            bytes_written: self.files.values().map(|meta| meta.bytes_written).sum(),
        })
    }
}

impl SharedBucketSink {
    pub fn create(params: &BuildParams, graph_count: usize) -> Result<Arc<Self>, BucketError> {
        let bucket_dir = bucket_dir(params);
        if bucket_dir.exists() {
            fs::remove_dir_all(&bucket_dir).map_err(|source| BucketError::Io {
                path: bucket_dir.clone(),
                source,
            })?;
        }
        fs::create_dir_all(&bucket_dir).map_err(|source| BucketError::Io {
            path: bucket_dir.clone(),
            source,
        })?;

        // One container per atlas where descriptors allow. An atlas
        // serializes its own writes with a mutex, so at one-to-one a container
        // has a single writer; when several atlases share one, the atomic
        // segment cursor keeps that safe.
        let atlas_count = graph_count.div_ceil(ATLAS_GRAPH_COUNT);
        let container_count = BucketContainers::plan_container_count(atlas_count);
        if container_count < atlas_count {
            eprintln!(
                "cuttlefish3-rs: descriptor budget allows {container_count} bucket container(s) rather than {atlas_count}"
            );
        }
        let containers = BucketContainers::create(&bucket_dir, container_count)?;

        Ok(Arc::new(Self {
            bucket_dir,
            containers,
            k: params.k,
            minimizer_len: params.minimizer_len,
            graph_count,
            colored: params.color,
            compress_buckets: params.color || params.compress_buckets,
            label_words: label_word_count(params.k, params.minimizer_len),
            workers: params.threads.max(1),
            atlases: (0..graph_count.div_ceil(ATLAS_GRAPH_COUNT))
                .map(|atlas_id| {
                    let first_graph_id = atlas_id * ATLAS_GRAPH_COUNT;
                    let file_count = (graph_count - first_graph_id).min(ATLAS_GRAPH_COUNT);
                    Mutex::new(SharedBucketAtlas {
                        first_graph_id,
                        files: (0..file_count)
                            .map(|_| SharedBucketFileMeta::default())
                            .collect(),
                        buffered_bytes: 0,
                        scratch: CompressionScratch::default(),
                    })
                })
                .collect(),
            flush_calls: AtomicU64::new(0),
            flush_nanos: AtomicU64::new(0),
        }))
    }

    pub fn emitter(self: &Arc<Self>) -> SharedBucketEmitter {
        self.make_emitter(false)
    }

    pub fn deferred_uncolored_emitter(self: &Arc<Self>) -> SharedBucketEmitter {
        self.make_emitter(true)
    }

    fn make_emitter(self: &Arc<Self>, deferred_uncolored: bool) -> SharedBucketEmitter {
        SharedBucketEmitter {
            sink: Arc::clone(self),
            pending: if self.colored || deferred_uncolored {
                Vec::new()
            } else {
                vec![PendingBucket::default(); self.graph_count]
            },
            uncolored_pending: if !self.colored && deferred_uncolored {
                (0..self.atlases.len())
                    .map(|_| PendingColoredAtlas::default())
                    .collect()
            } else {
                Vec::new()
            },
            colored_pending: if self.colored {
                (0..self.atlases.len())
                    .map(|_| PendingColoredAtlas::default())
                    .collect()
            } else {
                Vec::new()
            },
            pending_bytes: 0,
            deferred_uncolored,
        }
    }

    pub fn flush_uncolored_emitters(
        &self,
        emitters: Vec<SharedBucketEmitter>,
    ) -> Result<(), BucketError> {
        let started = Instant::now();
        let mut by_atlas = (0..self.atlases.len())
            .map(|_| Mutex::new(Vec::<PendingColoredAtlas>::new()))
            .collect::<Vec<_>>();
        for mut emitter in emitters {
            for (atlas_id, pending) in emitter.uncolored_pending.drain(..).enumerate() {
                if !pending.bytes.is_empty() {
                    by_atlas[atlas_id]
                        .get_mut()
                        .map_err(|_| BucketError::WorkerPanic)?
                        .push(pending);
                }
            }
        }
        let next = AtomicUsize::new(0);
        let workers = self.workers.min(self.atlases.len().max(1));
        let calls = std::thread::scope(|scope| {
            let mut handles = Vec::with_capacity(workers);
            for _ in 0..workers {
                handles.push(scope.spawn(|| {
                    let mut calls = 0;
                    loop {
                        let atlas_id = next.fetch_add(1, Ordering::Relaxed);
                        let Some(pending) = by_atlas.get(atlas_id) else {
                            break;
                        };
                        let pending = std::mem::take(
                            &mut *pending.lock().map_err(|_| BucketError::WorkerPanic)?,
                        );
                        if pending.is_empty() {
                            continue;
                        }
                        let mut stats = SharedBucketFlushStats::default();
                        for chunk in pending {
                            self.append_uncolored_atlas_inner(atlas_id, chunk, &mut stats)?;
                        }
                        let mut atlas = self.atlases[atlas_id]
                            .lock()
                            .map_err(|_| BucketError::WorkerPanic)?;
                        atlas.flush_all(
                            &self.containers,
                            false,
                            self.label_words,
                            self.compress_buckets,
                            &mut stats,
                        )?;
                        calls += stats.calls;
                    }
                    Ok::<_, BucketError>(calls)
                }));
            }
            let mut calls = 0;
            for handle in handles {
                calls += handle.join().map_err(|_| BucketError::WorkerPanic)??;
            }
            Ok::<_, BucketError>(calls)
        })?;
        self.record_flush_stats(SharedBucketFlushStats { calls }, started.elapsed());
        Ok(())
    }

    fn append_uncolored_atlas(
        &self,
        atlas_id: usize,
        pending: PendingColoredAtlas,
    ) -> Result<(), BucketError> {
        let started = Instant::now();
        let mut stats = SharedBucketFlushStats::default();
        self.append_uncolored_atlas_inner(atlas_id, pending, &mut stats)?;
        self.record_flush_stats(stats, started.elapsed());
        Ok(())
    }

    fn append_uncolored_atlas_inner(
        &self,
        atlas_id: usize,
        pending: PendingColoredAtlas,
        stats: &mut SharedBucketFlushStats,
    ) -> Result<(), BucketError> {
        if pending.bytes.is_empty() {
            return Ok(());
        }
        let record_len = record_size(false, self.label_words);
        if pending.graph_ids.len() * record_len != pending.bytes.len() {
            return Err(BucketError::MalformedRecord);
        }
        let mut atlas = self.atlases[atlas_id]
            .lock()
            .map_err(|_| BucketError::WorkerPanic)?;
        for (&graph_id, record) in pending
            .graph_ids
            .iter()
            .zip(pending.bytes.chunks_exact(record_len))
        {
            let graph_id = usize::from(graph_id);
            let Some(local_graph_id) = graph_id.checked_sub(atlas.first_graph_id) else {
                return Err(BucketError::InvalidGraphId(graph_id));
            };
            let Some(file) = atlas.files.get_mut(local_graph_id) else {
                return Err(BucketError::InvalidGraphId(graph_id));
            };
            file.total_records = file
                .total_records
                .checked_add(1)
                .ok_or(BucketError::TooManyRecords)?;
            file.buffer_records = file
                .buffer_records
                .checked_add(1)
                .ok_or(BucketError::TooManyRecords)?;
            file.buffer.extend_from_slice(record);
        }
        atlas.buffered_bytes += pending.bytes.len();
        for local_graph_id in 0..atlas.files.len() {
            if atlas.files[local_graph_id].buffer.len() >= SUBGRAPH_CHUNK_BYTES {
                atlas.flush_subgraph(
                    local_graph_id,
                    &self.containers,
                    false,
                    self.label_words,
                    self.compress_buckets,
                    stats,
                )?;
            }
        }
        Ok(())
    }

    fn append_bucket(&self, graph_id: usize, pending: PendingBucket) -> Result<(), BucketError> {
        if pending.bytes.is_empty() {
            return Ok(());
        }
        let started = Instant::now();
        let atlas_id = graph_id / ATLAS_GRAPH_COUNT;
        let local_graph_id = graph_id % ATLAS_GRAPH_COUNT;
        let mut atlas = self.atlases[atlas_id]
            .lock()
            .map_err(|_| BucketError::WorkerPanic)?;
        atlas.append_bucket(local_graph_id, pending)?;
        if self.colored {
            return Ok(());
        }
        if atlas.files[local_graph_id].buffer.len() < SUBGRAPH_CHUNK_BYTES {
            return Ok(());
        }

        let mut flush_stats = SharedBucketFlushStats::default();
        atlas.flush_subgraph(
            local_graph_id,
            &self.containers,
            self.colored,
            self.label_words,
            self.compress_buckets,
            &mut flush_stats,
        )?;
        self.record_flush_stats(flush_stats, started.elapsed());
        Ok(())
    }

    fn append_colored_atlas(
        &self,
        atlas_id: usize,
        pending: PendingColoredAtlas,
    ) -> Result<(), BucketError> {
        if pending.bytes.is_empty() {
            return Ok(());
        }
        let record_len = record_size(true, self.label_words);
        if pending.graph_ids.len() * record_len != pending.bytes.len() {
            return Err(BucketError::MalformedRecord);
        }
        let started = Instant::now();
        let mut atlas = self.atlases[atlas_id]
            .lock()
            .map_err(|_| BucketError::WorkerPanic)?;
        for (&graph_id, record) in pending
            .graph_ids
            .iter()
            .zip(pending.bytes.chunks_exact(record_len))
        {
            let graph_id = usize::from(graph_id);
            let Some(local_graph_id) = graph_id.checked_sub(atlas.first_graph_id) else {
                return Err(BucketError::InvalidGraphId(graph_id));
            };
            let Some(file) = atlas.files.get_mut(local_graph_id) else {
                return Err(BucketError::InvalidGraphId(graph_id));
            };
            file.total_records = file
                .total_records
                .checked_add(1)
                .ok_or(BucketError::TooManyRecords)?;
            file.buffer_records = file
                .buffer_records
                .checked_add(1)
                .ok_or(BucketError::TooManyRecords)?;
            file.buffer.extend_from_slice(record);
        }
        atlas.buffered_bytes += pending.bytes.len();
        let mut flush_stats = SharedBucketFlushStats::default();
        for local_graph_id in 0..atlas.files.len() {
            if atlas.files[local_graph_id].buffer.len() >= SUBGRAPH_CHUNK_BYTES {
                atlas.flush_subgraph(
                    local_graph_id,
                    &self.containers,
                    true,
                    self.label_words,
                    self.compress_buckets,
                    &mut flush_stats,
                )?;
            }
        }
        self.record_flush_stats(flush_stats, started.elapsed());
        Ok(())
    }

    pub fn flush_stats(&self) -> (u64, Duration) {
        (
            self.flush_calls.load(Ordering::Relaxed),
            Duration::from_nanos(self.flush_nanos.load(Ordering::Relaxed)),
        )
    }

    pub fn flush_colored_window(
        &self,
        source_min: u32,
        source_max: u32,
    ) -> Result<(), BucketError> {
        if !self.colored || source_min > source_max {
            return Err(BucketError::MalformedRecord);
        }
        let started = Instant::now();
        let record_len = record_size(true, self.label_words);
        let next_atlas = AtomicUsize::new(0);
        let workers = self.workers.min(self.atlases.len().max(1));
        let flush_calls = std::thread::scope(|scope| {
            let mut handles = Vec::with_capacity(workers);
            for _ in 0..workers {
                handles.push(scope.spawn(|| {
                    let mut stats = SharedBucketFlushStats::default();
                    loop {
                        let atlas_id = next_atlas.fetch_add(1, Ordering::Relaxed);
                        let Some(atlas) = self.atlases.get(atlas_id) else {
                            break;
                        };
                        let mut atlas = atlas.lock().map_err(|_| BucketError::WorkerPanic)?;
                        for local_graph_id in 0..atlas.files.len() {
                            sort_colored_payload_by_source(
                                &mut atlas.files[local_graph_id].buffer,
                                record_len,
                                source_min,
                                source_max,
                            )?;
                            atlas.flush_subgraph(
                                local_graph_id,
                                &self.containers,
                                true,
                                self.label_words,
                                true,
                                &mut stats,
                            )?;
                        }
                    }
                    Ok::<_, BucketError>(stats.calls)
                }));
            }
            let mut calls = 0u64;
            for handle in handles {
                calls += handle.join().map_err(|_| BucketError::WorkerPanic)??;
            }
            Ok::<_, BucketError>(calls)
        })?;
        self.record_flush_stats(
            SharedBucketFlushStats { calls: flush_calls },
            started.elapsed(),
        );
        Ok(())
    }

    pub fn flush_colored_emitters(
        &self,
        emitters: Vec<SharedBucketEmitter>,
    ) -> Result<(), BucketError> {
        if !self.colored {
            return Err(BucketError::MalformedRecord);
        }

        let emitter_count = emitters.len();
        let mut pending_by_atlas = (0..self.atlases.len())
            .map(|_| Vec::with_capacity(emitter_count))
            .collect::<Vec<Vec<PendingColoredAtlas>>>();
        for emitter in emitters {
            if !std::ptr::eq(Arc::as_ptr(&emitter.sink), self) {
                return Err(BucketError::MalformedRecord);
            }
            if !emitter.pending.is_empty()
                || emitter.colored_pending.len() != pending_by_atlas.len()
            {
                return Err(BucketError::MalformedRecord);
            }
            for (atlas_id, pending) in emitter.colored_pending.into_iter().enumerate() {
                if !pending.bytes.is_empty() {
                    pending_by_atlas[atlas_id].push(pending);
                }
            }
        }

        let started = Instant::now();
        let workers = self.workers.min(pending_by_atlas.len().max(1));
        let chunk_size = pending_by_atlas.len().div_ceil(workers);
        let flush_calls = std::thread::scope(|scope| {
            let mut handles = Vec::with_capacity(workers);
            for (chunk_id, atlas_work) in pending_by_atlas.chunks_mut(chunk_size).enumerate() {
                handles.push(scope.spawn(move || {
                    let mut stats = SharedBucketFlushStats::default();
                    let first_atlas = chunk_id * chunk_size;
                    for (offset, worker_buckets) in atlas_work.iter_mut().enumerate() {
                        let atlas_id = first_atlas + offset;
                        let mut atlas = self.atlases[atlas_id]
                            .lock()
                            .map_err(|_| BucketError::WorkerPanic)?;
                        let record_len = record_size(true, self.label_words);
                        for pending in worker_buckets.iter() {
                            if pending.graph_ids.len() * record_len != pending.bytes.len() {
                                return Err(BucketError::MalformedRecord);
                            }
                            for (&graph_id, record) in pending
                                .graph_ids
                                .iter()
                                .zip(pending.bytes.chunks_exact(record_len))
                            {
                                append_colored_atlas_record(&mut atlas, graph_id, record)?;
                            }
                        }
                        atlas.buffered_bytes += worker_buckets
                            .iter()
                            .map(|pending| pending.bytes.len())
                            .sum::<usize>();
                        for local_graph_id in 0..atlas.files.len() {
                            atlas.flush_subgraph(
                                local_graph_id,
                                &self.containers,
                                true,
                                self.label_words,
                                true,
                                &mut stats,
                            )?;
                            // This consumes the complete colored emitter set, so these
                            // buffers will not be reused. Releasing their capacity here
                            // avoids retaining every uncompressed subgraph bucket while
                            // the remaining worker atlas chunks are still resident.
                            atlas.files[local_graph_id].buffer = Vec::new();
                        }
                    }
                    Ok::<_, BucketError>(stats.calls)
                }));
            }
            let mut calls = 0u64;
            for handle in handles {
                calls += handle.join().map_err(|_| BucketError::WorkerPanic)??;
            }
            Ok::<_, BucketError>(calls)
        })?;
        self.record_flush_stats(
            SharedBucketFlushStats { calls: flush_calls },
            started.elapsed(),
        );
        Ok(())
    }

    pub fn finish(&self) -> Result<BucketEmitStats, BucketError> {
        let mut entries = Vec::new();
        let mut finish_flush_stats = SharedBucketFlushStats::default();
        let finish_started = Instant::now();
        let mut bytes_written = 0u64;
        for atlas in &self.atlases {
            let mut atlas = atlas.lock().map_err(|_| BucketError::WorkerPanic)?;
            atlas.flush_all(
                &self.containers,
                self.colored,
                self.label_words,
                self.compress_buckets,
                &mut finish_flush_stats,
            )?;
            let first_graph_id = atlas.first_graph_id;
            let container = (first_graph_id / ATLAS_GRAPH_COUNT) % self.containers.len();
            for (local_graph_id, meta) in atlas.files.iter_mut().enumerate() {
                let meta = std::mem::take(meta);
                if meta.total_records == 0 {
                    continue;
                }
                bytes_written += meta.bytes_written;
                entries.push(BucketManifestEntry {
                    graph_id: first_graph_id + local_graph_id,
                    records: meta.total_records,
                    location: BucketLocation::Container {
                        container,
                        segments: meta.segments,
                        bytes: meta.bytes_written,
                    },
                });
            }
        }
        self.record_flush_stats(finish_flush_stats, finish_started.elapsed());
        entries.sort_unstable_by_key(|entry| entry.graph_id);

        // Nothing to patch and nothing to reopen. The per-file layout finished
        // by reopening all 16,384 buckets to write the record count into each
        // header, parallelised across workers because it was slow enough to
        // matter; the count now lives in the manifest that has to be written
        // anyway.
        let header = ContainerManifestHeader {
            k: self.k,
            minimizer_len: self.minimizer_len,
            graph_count: self.graph_count,
            colored: self.colored,
            label_words: self.label_words,
            compressed: self.compress_buckets,
            interleaved_compression: self.compress_buckets
                && !self.colored
                && !force_split_compression(),
            segment_bytes: self.containers.segment_bytes(),
            // The number of containers actually created, which is not the
            // atlas count when the descriptor budget narrowed it.
            container_count: self.containers.len(),
        };
        write_container_manifest(&self.bucket_dir, &header, &entries)?;
        Ok(BucketEmitStats {
            bucket_dir: self.bucket_dir.clone(),
            bucket_files: entries.len(),
            bytes_written,
        })
    }

    fn record_flush_stats(&self, stats: SharedBucketFlushStats, elapsed: Duration) {
        if stats.calls == 0 {
            return;
        }
        self.flush_calls.fetch_add(stats.calls, Ordering::Relaxed);
        self.flush_nanos.fetch_add(
            u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX),
            Ordering::Relaxed,
        );
    }
}

fn append_colored_atlas_record(
    atlas: &mut SharedBucketAtlas,
    graph_id: u16,
    record: &[u8],
) -> Result<(), BucketError> {
    let graph_id = usize::from(graph_id);
    let local_graph_id = graph_id
        .checked_sub(atlas.first_graph_id)
        .ok_or(BucketError::InvalidGraphId(graph_id))?;
    let file = atlas
        .files
        .get_mut(local_graph_id)
        .ok_or(BucketError::InvalidGraphId(graph_id))?;
    file.total_records = file
        .total_records
        .checked_add(1)
        .ok_or(BucketError::TooManyRecords)?;
    file.buffer_records = file
        .buffer_records
        .checked_add(1)
        .ok_or(BucketError::TooManyRecords)?;
    file.buffer.extend_from_slice(record);
    Ok(())
}

fn sort_colored_payload_by_source(
    payload: &mut Vec<u8>,
    record_len: usize,
    source_min: u32,
    source_max: u32,
) -> Result<(), BucketError> {
    if payload.is_empty() {
        return Ok(());
    }
    if payload.len() % record_len != 0 {
        return Err(BucketError::MalformedRecord);
    }
    let source_count =
        usize::try_from(source_max - source_min + 1).map_err(|_| BucketError::MalformedRecord)?;
    let mut offsets = vec![0usize; source_count];
    for record in payload.chunks_exact(record_len) {
        let attr = u32::from_le_bytes(record[..4].try_into().expect("colored attribute"));
        let source = attr >> 10;
        if source < source_min || source > source_max {
            return Err(BucketError::MalformedRecord);
        }
        offsets[(source - source_min) as usize] += 1;
    }
    let mut prefix = 0usize;
    for offset in &mut offsets {
        let count = *offset;
        *offset = prefix;
        prefix += count;
    }
    let mut sorted = vec![0u8; payload.len()];
    for record in payload.chunks_exact(record_len) {
        let attr = u32::from_le_bytes(record[..4].try_into().expect("colored attribute"));
        let source = ((attr >> 10) - source_min) as usize;
        let output = offsets[source] * record_len;
        sorted[output..output + record_len].copy_from_slice(record);
        offsets[source] += 1;
    }
    *payload = sorted;
    Ok(())
}

impl SharedBucketAtlas {
    fn append_bucket(
        &mut self,
        local_graph_id: usize,
        pending: PendingBucket,
    ) -> Result<(), BucketError> {
        let file = &mut self.files[local_graph_id];
        file.total_records = file
            .total_records
            .checked_add(pending.records)
            .ok_or(BucketError::TooManyRecords)?;
        file.buffer_records = file
            .buffer_records
            .checked_add(pending.records)
            .ok_or(BucketError::TooManyRecords)?;
        self.buffered_bytes += pending.bytes.len();
        file.buffer.extend_from_slice(&pending.bytes);
        Ok(())
    }

    fn flush_all(
        &mut self,
        containers: &BucketContainers,
        colored: bool,
        label_words: usize,
        compress_buckets: bool,
        stats: &mut SharedBucketFlushStats,
    ) -> Result<(), BucketError> {
        for local_graph_id in 0..self.files.len() {
            self.flush_subgraph(
                local_graph_id,
                containers,
                colored,
                label_words,
                compress_buckets,
                stats,
            )?;
        }
        Ok(())
    }

    /// Writes one bucket's staged records into its container.
    ///
    /// This is the whole syscall saving. The per-file path reached here with
    /// an `openat`, seven unbuffered reads to re-read the 42-byte header, a
    /// revalidation, an `lseek` to the end and a `close` -- around eleven
    /// syscalls for every 64 KiB flush, and a full-corpus build performs 14.4
    /// million of them. A container flush is the `pwrite` and nothing else:
    /// the header is in the manifest, the descriptor is already open, and the
    /// offset is known rather than sought.
    fn flush_subgraph(
        &mut self,
        local_graph_id: usize,
        containers: &BucketContainers,
        colored: bool,
        label_words: usize,
        compress_buckets: bool,
        stats: &mut SharedBucketFlushStats,
    ) -> Result<(), BucketError> {
        let container = (self.first_graph_id / ATLAS_GRAPH_COUNT) % containers.len();
        let Self { files, scratch, .. } = self;
        let file = &mut files[local_graph_id];
        if file.buffer.is_empty() {
            return Ok(());
        }
        let flushed_bytes = file.buffer.len();
        let record_size = record_size(colored, label_words) as u64;

        let written = if compress_buckets {
            let interleaved = !colored && !force_split_compression();
            let len = encode_compressed_block(
                &file.buffer,
                file.buffer_records,
                record_size,
                label_words,
                interleaved,
                scratch,
            )?;
            let block = std::mem::take(&mut scratch.block);
            let written = append_to_chain(containers, container, file, &block)?;
            scratch.block = block;
            debug_assert_eq!(written, len as u64);
            written
        } else {
            let buffer = std::mem::take(&mut file.buffer);
            let written = append_to_chain(containers, container, file, &buffer);
            file.buffer = buffer;
            written?
        };

        file.written_records += file.buffer_records;
        file.bytes_written += written;
        file.buffer.clear();
        file.buffer_records = 0;
        self.buffered_bytes -= flushed_bytes;
        stats.calls += 1;
        Ok(())
    }
}

/// Appends `bytes` to a bucket's segment chain, reserving as it goes.
///
/// A block may straddle a segment boundary rather than starting a fresh
/// segment. That costs a second `pwrite` for the rare block that spans one,
/// and saves refusing to fill the tail of every segment -- which at a 64 KiB
/// flush and a 256 KiB segment would waste up to a quarter of the directory.
/// The reader concatenates the chain in order, so a split block reassembles.
fn append_to_chain(
    containers: &BucketContainers,
    container: usize,
    file: &mut SharedBucketFileMeta,
    bytes: &[u8],
) -> Result<u64, BucketError> {
    let segment_bytes = containers.segment_bytes();
    let mut written = 0usize;
    while written < bytes.len() {
        if file.segments.is_empty() || file.segment_used == segment_bytes {
            let offset = containers.reserve_segment(container);
            let index =
                u32::try_from(offset / segment_bytes).map_err(|_| BucketError::TooManyRecords)?;
            file.segments.push(index);
            file.segment_used = 0;
        }
        let room = (segment_bytes - file.segment_used) as usize;
        let take = room.min(bytes.len() - written);
        let offset = u64::from(*file.segments.last().unwrap()) * segment_bytes + file.segment_used;
        containers.write_at(container, offset, &bytes[written..written + take])?;
        written += take;
        file.segment_used += take as u64;
    }
    Ok(written as u64)
}

impl SharedBucketEmitter {
    pub fn flush_colored_worker_if_required(&mut self) -> Result<(), BucketError> {
        if !self.sink.colored {
            return Err(BucketError::MalformedRecord);
        }
        for atlas_id in 0..self.colored_pending.len() {
            if self.colored_pending[atlas_id].bytes.len() >= SUBGRAPH_CHUNK_BYTES {
                self.flush_pending_colored_atlas(atlas_id)?;
            }
        }
        Ok(())
    }

    pub fn add(&mut self, superkmer: &WeakSuperKmer, seq: &[u8]) -> Result<(), BucketError> {
        self.add_impl(superkmer, seq, true)
    }

    pub fn add_valid(&mut self, superkmer: &WeakSuperKmer, seq: &[u8]) -> Result<(), BucketError> {
        debug_assert!(seq.iter().all(|&base| ascii_base_bits(base).is_some()));
        self.add_impl(superkmer, seq, false)
    }

    fn add_impl(
        &mut self,
        superkmer: &WeakSuperKmer,
        seq: &[u8],
        check_bases: bool,
    ) -> Result<(), BucketError> {
        if superkmer.graph_id >= self.sink.graph_count {
            return Err(BucketError::InvalidGraphId(superkmer.graph_id));
        }
        if seq.len() > u8::MAX as usize {
            return Err(BucketError::LabelTooLong(seq.len()));
        }

        let attr = if self.sink.colored {
            let source_id = superkmer.source_id.ok_or(BucketError::MissingSourceId)?;
            if source_id > MAX_SOURCE_ID {
                return Err(BucketError::SourceIdTooLarge(source_id));
            }
            pack_colored_attr(
                seq.len(),
                source_id,
                superkmer.left_discontinuous,
                superkmer.right_discontinuous,
            )
        } else {
            pack_uncolored_attr(
                seq.len(),
                superkmer.left_discontinuous,
                superkmer.right_discontinuous,
            )
        };
        let graph_id = superkmer.graph_id;
        let record_len = record_size(self.sink.colored, self.sink.label_words);
        if self.sink.colored {
            let atlas_id = graph_id / ATLAS_GRAPH_COUNT;
            let pending = &mut self.colored_pending[atlas_id];
            pending.graph_ids.push(graph_id as u16);
            if check_bases {
                append_record(
                    &mut pending.bytes,
                    attr,
                    graph_id,
                    seq,
                    self.sink.label_words,
                    true,
                )?;
            } else {
                append_record_valid(
                    &mut pending.bytes,
                    attr,
                    graph_id,
                    seq,
                    self.sink.label_words,
                    true,
                )?;
            }
        } else if self.deferred_uncolored {
            let atlas_id = graph_id / ATLAS_GRAPH_COUNT;
            let pending = &mut self.uncolored_pending[atlas_id];
            pending.graph_ids.push(graph_id as u16);
            if !check_bases {
                append_uncolored_record_valid(
                    &mut pending.bytes,
                    attr as u16,
                    graph_id as u16,
                    seq,
                    self.sink.label_words,
                )?;
            } else {
                append_record(
                    &mut pending.bytes,
                    attr,
                    graph_id,
                    seq,
                    self.sink.label_words,
                    false,
                )?;
            }
        } else {
            let pending = &mut self.pending[graph_id];
            pending.records = pending
                .records
                .checked_add(1)
                .ok_or(BucketError::TooManyRecords)?;
            if !check_bases {
                append_uncolored_record_valid(
                    &mut pending.bytes,
                    attr as u16,
                    graph_id as u16,
                    seq,
                    self.sink.label_words,
                )?;
            } else {
                append_record(
                    &mut pending.bytes,
                    attr,
                    graph_id,
                    seq,
                    self.sink.label_words,
                    false,
                )?;
            }
        }
        self.pending_bytes += record_len;

        // As in C++, colored worker-atlas chunks are checked and handed to the
        // shared atlas at the source boundary, not in the middle of a source.
        if self.deferred_uncolored {
            let atlas_id = graph_id / ATLAS_GRAPH_COUNT;
            if self.uncolored_pending[atlas_id].bytes.len() >= SUBGRAPH_CHUNK_BYTES {
                self.flush_pending_uncolored_atlas(atlas_id)?;
            }
        } else if !self.sink.colored
            && !self.deferred_uncolored
            && self.pending[graph_id].bytes.len() >= MAX_PENDING_BUCKET_BYTES
        {
            self.flush_pending_bucket(graph_id)?;
        } else if !self.sink.colored
            && !self.deferred_uncolored
            && self.pending_bytes >= MAX_TOTAL_PENDING_BYTES
        {
            self.flush_largest_pending_bucket()?;
        }
        Ok(())
    }

    fn flush_largest_pending_bucket(&mut self) -> Result<(), BucketError> {
        if self.sink.colored {
            let Some((atlas_id, _)) = self
                .colored_pending
                .iter()
                .enumerate()
                .max_by_key(|(_, pending)| pending.bytes.len())
            else {
                return Ok(());
            };
            return self.flush_pending_colored_atlas(atlas_id);
        }
        let Some((graph_id, _)) = self
            .pending
            .iter()
            .enumerate()
            .max_by_key(|(_, pending)| pending.bytes.len())
        else {
            return Ok(());
        };
        self.flush_pending_bucket(graph_id)
    }

    fn flush_pending_bucket(&mut self, graph_id: usize) -> Result<(), BucketError> {
        if self.pending[graph_id].bytes.is_empty() {
            return Ok(());
        }
        let pending = std::mem::take(&mut self.pending[graph_id]);
        self.pending_bytes -= pending.bytes.len();
        self.sink.append_bucket(graph_id, pending)
    }

    fn flush_pending_colored_atlas(&mut self, atlas_id: usize) -> Result<(), BucketError> {
        if self.colored_pending[atlas_id].bytes.is_empty() {
            return Ok(());
        }
        let pending = std::mem::take(&mut self.colored_pending[atlas_id]);
        self.pending_bytes -= pending.bytes.len();
        self.sink.append_colored_atlas(atlas_id, pending)
    }

    fn flush_pending_uncolored_atlas(&mut self, atlas_id: usize) -> Result<(), BucketError> {
        if self.uncolored_pending[atlas_id].bytes.is_empty() {
            return Ok(());
        }
        let pending = std::mem::take(&mut self.uncolored_pending[atlas_id]);
        self.pending_bytes -= pending.bytes.len();
        self.sink.append_uncolored_atlas(atlas_id, pending)
    }

    pub fn finish(mut self) -> Result<(), BucketError> {
        if self.sink.colored {
            for atlas_id in 0..self.colored_pending.len() {
                if !self.colored_pending[atlas_id].bytes.is_empty() {
                    self.flush_pending_colored_atlas(atlas_id)?;
                }
            }
        } else if self.deferred_uncolored {
            for atlas_id in 0..self.uncolored_pending.len() {
                if !self.uncolored_pending[atlas_id].bytes.is_empty() {
                    self.flush_pending_uncolored_atlas(atlas_id)?;
                }
            }
        } else {
            for graph_id in 0..self.pending.len() {
                if !self.pending[graph_id].bytes.is_empty() {
                    self.flush_pending_bucket(graph_id)?;
                }
            }
        }
        Ok(())
    }
}

pub fn bucket_dir(params: &BuildParams) -> PathBuf {
    let output_name = Path::new(&params.output_prefix)
        .file_name()
        .and_then(|s| s.to_str())
        .filter(|s| !s.is_empty())
        .unwrap_or("cuttlefish3");
    PathBuf::from(&params.work_dir).join(format!("{output_name}.cf3rs.wsk"))
}

pub fn write_manifest(
    bucket_dir: &Path,
    entries: &[(usize, u64, PathBuf)],
) -> Result<(), BucketError> {
    let path = bucket_dir.join("manifest.tsv");
    let mut out = File::create(&path).map_err(|source| BucketError::Io {
        path: path.clone(),
        source,
    })?;
    writeln!(out, "graph_id\trecords\tpath").map_err(|source| BucketError::Io {
        path: path.clone(),
        source,
    })?;
    for (graph_id, records, bucket_path) in entries {
        writeln!(out, "{graph_id}\t{records}\t{}", bucket_path.display()).map_err(|source| {
            BucketError::Io {
                path: path.clone(),
                source,
            }
        })?;
    }
    Ok(())
}

/// Encodes one compressed block into `scratch.block`, returning its length.
///
/// Assembling the whole block -- 12-byte header plus one or two LZ4 streams --
/// before it is written keeps a flush to a single `write` on a file that has
/// no buffering, and lets a container flush reuse the identical framing.
fn encode_compressed_block(
    bytes: &[u8],
    records: u64,
    record_size: u64,
    label_words: usize,
    interleaved: bool,
    scratch: &mut CompressionScratch,
) -> Result<usize, BucketError> {
    let records_u32 = u32::try_from(records).map_err(|_| BucketError::TooManyRecords)?;
    if records_u32 == 0 {
        scratch.block.clear();
        return Ok(0);
    }
    let (attr_len, label_len) = if interleaved {
        (CompressionScratch::encode(bytes, &mut scratch.encoded)?, 0)
    } else {
        let record_len = usize::try_from(record_size).unwrap();
        let fixed_len = record_len - label_words * 8;
        scratch.attrs.clear();
        scratch.labels.clear();
        scratch.attrs.reserve(records as usize * fixed_len);
        scratch.labels.reserve(records as usize * label_words * 8);
        for record in bytes.chunks_exact(record_len) {
            scratch.attrs.extend_from_slice(&record[..fixed_len]);
            scratch.labels.extend_from_slice(&record[fixed_len..]);
        }
        let attrs = std::mem::take(&mut scratch.attrs);
        let labels = std::mem::take(&mut scratch.labels);
        let attr_len = CompressionScratch::encode(&attrs, &mut scratch.encoded)?;
        let label_len = CompressionScratch::encode(&labels, &mut scratch.encoded_labels)?;
        scratch.attrs = attrs;
        scratch.labels = labels;
        (attr_len, label_len)
    };
    let attr_len_u32 = u32::try_from(attr_len).map_err(|_| BucketError::TooManyRecords)?;
    let label_len_u32 = u32::try_from(label_len).map_err(|_| BucketError::TooManyRecords)?;

    scratch.block.clear();
    scratch.block.extend_from_slice(&records_u32.to_le_bytes());
    scratch.block.extend_from_slice(&attr_len_u32.to_le_bytes());
    scratch
        .block
        .extend_from_slice(&label_len_u32.to_le_bytes());
    scratch
        .block
        .extend_from_slice(&scratch.encoded[..attr_len]);
    if label_len != 0 {
        scratch
            .block
            .extend_from_slice(&scratch.encoded_labels[..label_len]);
    }
    Ok(scratch.block.len())
}

fn append_record(
    out: &mut Vec<u8>,
    packed_attr: u32,
    _graph_id: usize,
    seq: &[u8],
    label_words: usize,
    colored: bool,
) -> Result<(), BucketError> {
    let mut words = [0u64; 4];
    if label_words > words.len() {
        return Err(BucketError::MalformedRecord);
    }
    for (idx, &ch) in seq.iter().enumerate() {
        let base_bits = ascii_base_bits(ch).ok_or(BucketError::InvalidBase(ch))?;
        let word_idx = idx / 32;
        let shift = 2 * (31 - (idx % 32));
        words[word_idx] |= (base_bits as u64) << shift;
    }

    if colored {
        out.extend_from_slice(&packed_attr.to_le_bytes());
    } else {
        out.extend_from_slice(&(packed_attr as u16).to_le_bytes());
    }
    for &word in &words[..label_words] {
        out.extend_from_slice(&word.to_le_bytes());
    }
    Ok(())
}

fn append_record_valid(
    out: &mut Vec<u8>,
    packed_attr: u32,
    _graph_id: usize,
    seq: &[u8],
    label_words: usize,
    colored: bool,
) -> Result<(), BucketError> {
    let words = pack_valid_label(seq, label_words)?;

    let mut record = [0u8; MAX_RECORD_BYTES];
    let attr_len = if colored {
        record[..4].copy_from_slice(&packed_attr.to_le_bytes());
        4
    } else {
        record[..2].copy_from_slice(&(packed_attr as u16).to_le_bytes());
        2
    };
    for (idx, &word) in words[..label_words].iter().enumerate() {
        let at = attr_len + idx * 8;
        record[at..at + 8].copy_from_slice(&word.to_le_bytes());
    }
    out.extend_from_slice(&record[..attr_len + label_words * 8]);
    Ok(())
}

#[inline]
fn append_uncolored_record_valid(
    out: &mut Vec<u8>,
    packed_attr: u16,
    _graph_id: u16,
    seq: &[u8],
    label_words: usize,
) -> Result<(), BucketError> {
    let words = pack_valid_label(seq, label_words)?;

    // Assemble the record on the stack and append it once. Reserving and then
    // extending per field costs a capacity check and a `memcpy` call for each of
    // the attribute and every label word; C++ writes its equivalent with plain
    // indexed stores into pre-reserved arrays.
    let mut record = [0u8; MAX_RECORD_BYTES];
    record[..2].copy_from_slice(&packed_attr.to_le_bytes());
    for (idx, &word) in words[..label_words].iter().enumerate() {
        let at = 2 + idx * 8;
        record[at..at + 8].copy_from_slice(&word.to_le_bytes());
    }
    out.extend_from_slice(&record[..2 + label_words * 8]);
    Ok(())
}

#[inline(always)]
/// Packs 32 valid ACGT bases into one 64-bit word, first base in the high bits.
///
/// The scalar form carries a loop-carried dependency (`word = (word << 2) | c`),
/// so it neither vectorizes nor pipelines: 32 serial iterations for one word,
/// which dominates record packing. Each 2-bit code is a pure bitwise function of
/// its byte, so eight bases can be reduced at a time inside a `u64` and the
/// codes gathered with a single `PEXT`.
fn pack_valid_word_32(seq: &[u8]) -> u64 {
    debug_assert!(seq.len() >= 32);
    #[cfg(all(target_arch = "x86_64", target_feature = "bmi2"))]
    {
        let mut word = 0u64;
        for chunk in 0..4 {
            let bytes = u64::from_le_bytes(
                seq[chunk * 8..chunk * 8 + 8]
                    .try_into()
                    .expect("eight bases"),
            );
            // Per byte: ((b >> 2) ^ (b >> 1)) & 0b11, evaluated eight at a time.
            let codes = ((bytes >> 2) ^ (bytes >> 1)) & 0x0303_0303_0303_0303;
            // Gather the eight 2-bit codes, lowest byte first, into 16 bits.
            let packed = unsafe { core::arch::x86_64::_pext_u64(codes, 0x0303_0303_0303_0303) };
            // The scalar form shifts the first base furthest left, and PEXT emits
            // the first (lowest-address) base in the least significant bits, so
            // reverse the 2-bit groups within this 16-bit lane.
            let reversed = reverse_2bit_groups_16(packed as u16);
            word = (word << 16) | u64::from(reversed);
        }
        word
    }
    #[cfg(not(all(target_arch = "x86_64", target_feature = "bmi2")))]
    {
        let mut word = 0u64;
        for &base in &seq[..32] {
            word = (word << 2) | u64::from(valid_ascii_base_bits(base));
        }
        word
    }
}

/// Reverses the order of the eight 2-bit groups in a 16-bit value.
#[cfg(all(target_arch = "x86_64", target_feature = "bmi2"))]
#[inline]
fn reverse_2bit_groups_16(value: u16) -> u16 {
    let v = value as u32;
    // Swap adjacent 2-bit pairs, then nibbles, then bytes.
    let v = ((v & 0x3333) << 2) | ((v >> 2) & 0x3333);
    let v = ((v & 0x0f0f) << 4) | ((v >> 4) & 0x0f0f);
    (((v & 0x00ff) << 8) | ((v >> 8) & 0x00ff)) as u16
}

#[inline]
fn pack_valid_label(seq: &[u8], label_words: usize) -> Result<[u64; 4], BucketError> {
    let mut words = [0u64; 4];
    if label_words > words.len() || seq.len() > label_words * 32 {
        return Err(BucketError::MalformedRecord);
    }

    let full_words = seq.len() / 32;
    for word_idx in 0..full_words {
        words[word_idx] = pack_valid_word_32(&seq[word_idx * 32..]);
    }
    let tail = &seq[full_words * 32..];
    if !tail.is_empty() {
        let mut word = 0u64;
        for &base in tail {
            word = (word << 2) | u64::from(valid_ascii_base_bits(base));
        }
        words[full_words] = word << (2 * (32 - tail.len()));
    }
    Ok(words)
}

struct BucketFile {
    path: PathBuf,
    file: File,
    records: u64,
    bytes_written: u64,
    record_size: u64,
    compressed: bool,
    interleaved_compression: bool,
    label_words: usize,
}

/// Reusable staging for compressed bucket writes.
///
/// A `BucketFile` is opened per flush, so these buffers belong to the emitter
/// that owns the flush loop; held there, a 64 KiB block costs no allocation.
#[derive(Default)]
pub(crate) struct CompressionScratch {
    /// Fixed-size attributes, de-interleaved out of the record stream.
    attrs: Vec<u8>,
    /// Label words, de-interleaved out of the record stream.
    labels: Vec<u8>,
    /// LZ4 output for the attribute stream, or for the whole block.
    encoded: Vec<u8>,
    /// LZ4 output for the label stream.
    encoded_labels: Vec<u8>,
    /// Header and payload assembled for a single `write_all`.
    block: Vec<u8>,
}

impl CompressionScratch {
    /// Compresses `input` into `out`, returning the encoded length.
    ///
    /// `out` only ever grows, so the zero-fill a resize implies is paid once
    /// per writer rather than once per block.
    fn encode(input: &[u8], out: &mut Vec<u8>) -> Result<usize, BucketError> {
        let bound = lz4_flex::block::get_maximum_output_size(input.len());
        if out.len() < bound {
            out.resize(bound, 0);
        }
        lz4_flex::block::compress_into(input, &mut out[..bound])
            .map_err(|_| BucketError::MalformedRecord)
    }
}

/// Whether uncolored buckets compress attributes and labels as separate
/// streams, the way the colored path and C++ both do.
///
/// The interleaved default compresses whole records in one stream. The header
/// records which was used, so readers stay correct under either setting.
fn force_split_compression() -> bool {
    static SPLIT: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
    *SPLIT.get_or_init(|| std::env::var_os("CF3_RS_SPLIT_COMPRESSION").is_some())
}

impl BucketFile {
    #[allow(clippy::too_many_arguments)]
    fn create(
        bucket_dir: &Path,
        k: u16,
        minimizer_len: u16,
        graph_count: usize,
        graph_id: usize,
        colored: bool,
        label_words: usize,
        compressed: bool,
    ) -> Result<Self, BucketError> {
        let path = bucket_dir.join(format!("{graph_id:05}.wsk"));
        let mut file = File::create(&path).map_err(|source| BucketError::Io {
            path: path.clone(),
            source,
        })?;

        file.write_all(MAGIC).map_err(|source| BucketError::Io {
            path: path.clone(),
            source,
        })?;
        write_u16(&mut file, &path, k)?;
        write_u16(&mut file, &path, minimizer_len)?;
        write_u64(&mut file, &path, graph_count as u64)?;
        write_u64(&mut file, &path, graph_id as u64)?;
        let interleaved_compression = compressed && !colored && !force_split_compression();
        file.write_all(&[
            u8::from(colored),
            label_words as u8,
            if interleaved_compression {
                2
            } else {
                u8::from(compressed)
            },
            0,
            0,
            0,
        ])
        .map_err(|source| BucketError::Io {
            path: path.clone(),
            source,
        })?;
        write_u64(&mut file, &path, 0)?;

        Ok(Self {
            path,
            file,
            records: 0,
            bytes_written: HEADER_LEN,
            record_size: record_size(colored, label_words) as u64,
            compressed,
            interleaved_compression,
            label_words,
        })
    }

    fn open_existing(path: &Path, records: u64, bytes_written: u64) -> Result<Self, BucketError> {
        let mut file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .map_err(|source| BucketError::Io {
                path: path.to_path_buf(),
                source,
            })?;
        let header = read_header(&mut file, path)?;
        file.seek(SeekFrom::End(0))
            .map_err(|source| BucketError::Io {
                path: path.to_path_buf(),
                source,
            })?;

        Ok(Self {
            path: path.to_path_buf(),
            file,
            records,
            bytes_written,
            record_size: record_size(header.colored, header.label_words) as u64,
            compressed: header.compressed,
            interleaved_compression: header.interleaved_compression,
            label_words: header.label_words,
        })
    }

    fn write_records(
        &mut self,
        bytes: &[u8],
        records: u64,
        scratch: &mut CompressionScratch,
    ) -> Result<(u64, u64), BucketError> {
        debug_assert_eq!(bytes.len() as u64, records * self.record_size);
        let written = if self.compressed {
            self.write_compressed_block(bytes, records, scratch)?
        } else {
            self.file
                .write_all(bytes)
                .map_err(|source| BucketError::Io {
                    path: self.path.clone(),
                    source,
                })?;
            bytes.len() as u64
        };
        self.records = self
            .records
            .checked_add(records)
            .ok_or(BucketError::TooManyRecords)?;
        self.bytes_written += written;
        Ok((self.records, self.bytes_written))
    }

    fn write_compressed_block(
        &mut self,
        bytes: &[u8],
        records: u64,
        scratch: &mut CompressionScratch,
    ) -> Result<u64, BucketError> {
        let len = encode_compressed_block(
            bytes,
            records,
            self.record_size,
            self.label_words,
            self.interleaved_compression,
            scratch,
        )?;
        if len == 0 {
            return Ok(0);
        }
        self.file
            .write_all(&scratch.block)
            .map_err(|source| BucketError::Io {
                path: self.path.clone(),
                source,
            })?;
        Ok(len as u64)
    }

    fn flush(&mut self) -> Result<(), BucketError> {
        self.file.flush().map_err(|source| BucketError::Io {
            path: self.path.clone(),
            source,
        })
    }

    fn finish(&mut self) -> Result<(), BucketError> {
        write_record_count(&mut self.file, &self.path, self.records)?;
        self.file
            .seek(SeekFrom::End(0))
            .map_err(|source| BucketError::Io {
                path: self.path.clone(),
                source,
            })?;
        self.file.flush().map_err(|source| BucketError::Io {
            path: self.path.clone(),
            source,
        })
    }

    fn finish_closed(path: &Path, records: u64) -> Result<(), BucketError> {
        let mut file = OpenOptions::new()
            .read(true)
            .write(true)
            .open(path)
            .map_err(|source| BucketError::Io {
                path: path.to_path_buf(),
                source,
            })?;
        write_record_count(&mut file, path, records)?;
        file.flush().map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })
    }
}

fn write_record_count(file: &mut File, path: &Path, records: u64) -> Result<(), BucketError> {
    file.seek(SeekFrom::Start(RECORD_COUNT_OFFSET))
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })?;
    write_u64(file, path, records)
}

fn label_word_count(k: u16, minimizer_len: u16) -> usize {
    let max_weak_superkmer_len = 2 * (usize::from(k) - 1) - usize::from(minimizer_len) + 2;
    max_weak_superkmer_len.div_ceil(32)
}

fn record_size(colored: bool, label_words: usize) -> usize {
    (if colored { 4 } else { 2 }) + label_words * 8
}

fn pack_uncolored_attr(len: usize, left_discontinuous: bool, right_discontinuous: bool) -> u32 {
    (len as u32) | ((left_discontinuous as u32) << 8) | ((right_discontinuous as u32) << 9)
}

fn pack_colored_attr(
    len: usize,
    source_id: u32,
    left_discontinuous: bool,
    right_discontinuous: bool,
) -> u32 {
    pack_uncolored_attr(len, left_discontinuous, right_discontinuous) | (source_id << 10)
}

fn decode_label_into(words: &[u64], len: usize, seq: &mut Vec<u8>) -> Result<(), BucketError> {
    if len > words.len() * 32 {
        return Err(BucketError::MalformedRecord);
    }

    seq.clear();
    seq.reserve(len);
    for idx in 0..len {
        let word_idx = idx / 32;
        let shift = 2 * (31 - (idx % 32));
        let base = match ((words[word_idx] >> shift) & 0b11) as u8 {
            0 => Base::A,
            1 => Base::C,
            2 => Base::G,
            3 => Base::T,
            _ => unreachable!(),
        };
        seq.push(base.to_ascii());
    }
    Ok(())
}

fn read_header(file: &mut impl Read, path: &Path) -> Result<BucketHeader, BucketError> {
    let mut magic = [0u8; 8];
    file.read_exact(&mut magic)
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })?;
    if &magic != MAGIC {
        return Err(BucketError::BadMagic(path.to_path_buf()));
    }

    let k = read_u16(file, path)?;
    let minimizer_len = read_u16(file, path)?;
    let graph_count = usize::try_from(read_u64(file, path)?)
        .map_err(|_| BucketError::MalformedHeader(path.to_path_buf()))?;
    let graph_id = usize::try_from(read_u64(file, path)?)
        .map_err(|_| BucketError::MalformedHeader(path.to_path_buf()))?;

    let mut flags = [0u8; 6];
    file.read_exact(&mut flags)
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })?;
    let colored = match flags[0] {
        0 => false,
        1 => true,
        _ => return Err(BucketError::MalformedHeader(path.to_path_buf())),
    };
    let label_words = flags[1] as usize;
    if label_words == 0 || label_words != label_word_count(k, minimizer_len) {
        return Err(BucketError::MalformedHeader(path.to_path_buf()));
    }
    let (compressed, interleaved_compression) = match flags[2] {
        0 => (false, false),
        1 => (true, false),
        2 if !colored => (true, true),
        _ => return Err(BucketError::MalformedHeader(path.to_path_buf())),
    };
    if flags[3..].iter().any(|&b| b != 0) {
        return Err(BucketError::MalformedHeader(path.to_path_buf()));
    }
    let records = read_u64(file, path)?;

    if graph_id >= graph_count {
        return Err(BucketError::MalformedHeader(path.to_path_buf()));
    }

    Ok(BucketHeader {
        k,
        minimizer_len,
        graph_count,
        graph_id,
        colored,
        compressed,
        interleaved_compression,
        label_words,
        records,
    })
}

fn read_u16(file: &mut impl Read, path: &Path) -> Result<u16, BucketError> {
    let mut bytes = [0u8; 2];
    file.read_exact(&mut bytes)
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })?;
    Ok(u16::from_le_bytes(bytes))
}

fn read_u64(file: &mut impl Read, path: &Path) -> Result<u64, BucketError> {
    let mut bytes = [0u8; 8];
    file.read_exact(&mut bytes)
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })?;
    Ok(u64::from_le_bytes(bytes))
}

fn write_u16(file: &mut File, path: &Path, value: u16) -> Result<(), BucketError> {
    file.write_all(&value.to_le_bytes())
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })
}

fn write_u64(file: &mut File, path: &Path, value: u64) -> Result<(), BucketError> {
    file.write_all(&value.to_le_bytes())
        .map_err(|source| BucketError::Io {
            path: path.to_path_buf(),
            source,
        })
}

#[derive(Debug)]
pub enum BucketError {
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    GraphCountTooLarge(usize),
    InvalidGraphId(usize),
    LabelTooLong(usize),
    MissingSourceId,
    SourceIdTooLarge(u32),
    InvalidBase(u8),
    TooManyRecords,
    BadMagic(PathBuf),
    MalformedHeader(PathBuf),
    MalformedManifest(PathBuf),
    MalformedRecord,
    RecordGraphMismatch {
        expected: usize,
        got: usize,
    },
    WorkerPanic,
}

impl std::fmt::Display for BucketError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
            Self::GraphCountTooLarge(count) => write!(f, "graph count is too large: {count}"),
            Self::InvalidGraphId(graph_id) => write!(f, "invalid graph id: {graph_id}"),
            Self::LabelTooLong(len) => write!(f, "weak super-kmer label is too long: {len}"),
            Self::MissingSourceId => write!(f, "colored bucket record is missing source id"),
            Self::SourceIdTooLarge(source_id) => {
                write!(
                    f,
                    "source id exceeds 21-bit colored bucket limit: {source_id}"
                )
            }
            Self::InvalidBase(b) => write!(f, "invalid base in bucket label: '{}'", *b as char),
            Self::TooManyRecords => write!(f, "too many weak super-kmer records"),
            Self::BadMagic(path) => write!(
                f,
                "not a CF3 Rust weak-superkmer bucket: {}",
                path.display()
            ),
            Self::MalformedHeader(path) => {
                write!(
                    f,
                    "malformed weak-superkmer bucket header: {}",
                    path.display()
                )
            }
            Self::MalformedManifest(path) => {
                write!(
                    f,
                    "malformed weak-superkmer bucket manifest: {}",
                    path.display()
                )
            }
            Self::MalformedRecord => write!(f, "malformed weak-superkmer bucket record"),
            Self::RecordGraphMismatch { expected, got } => {
                write!(
                    f,
                    "bucket record graph id mismatch: expected {expected}, got {got}"
                )
            }
            Self::WorkerPanic => write!(f, "bucket worker thread panicked"),
        }
    }
}

impl std::error::Error for BucketError {}

#[cfg(test)]
mod tests {
    /// Reclaim must actually return blocks, not merely be called.
    ///
    /// A failed punch is ignored by design -- the container is unlinked
    /// wholesale at the end regardless -- which means a filesystem or platform
    /// where it silently does nothing costs peak disk with no other symptom.
    /// That is exactly what happened once already: deferring reclaim left the
    /// work directory 24.5 GB larger and presented as an unexplained number.
    /// This asserts the blocks come back, so the macOS `fcntl(F_PUNCHHOLE)`
    /// path is verified by CI rather than assumed from the fact that it
    /// compiles.
    #[test]
    fn releasing_segments_returns_blocks_to_the_filesystem() {
        use std::os::unix::fs::MetadataExt;

        let dir = std::env::temp_dir().join(format!(
            "cf3-punch-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let containers = BucketContainers::create(&dir, 1).unwrap();
        let segment = containers.segment_bytes();
        let segments: Vec<u32> = (0..8).collect();
        let payload = vec![0xA5u8; segment as usize];
        for &index in &segments {
            containers
                .write_at(0, u64::from(index) * segment, &payload)
                .unwrap();
        }

        let path = dir.join("00000.wskc");
        let allocated = || fs::metadata(&path).unwrap().blocks() * 512;
        let before = allocated();
        assert!(
            before >= segments.len() as u64 * segment,
            "expected {} bytes of blocks before punching, saw {before}",
            segments.len() as u64 * segment
        );

        containers.release_segments(0, &segments);
        let after = allocated();

        assert!(
            after < before / 2,
            "punching {} segments freed {} of {before} bytes; this filesystem may \
             not support hole punching, in which case consumed bucket space is \
             held until the build ends and peak disk is higher than documented",
            segments.len(),
            before - after
        );
        // The file keeps its length; only the blocks behind it go away.
        assert_eq!(
            fs::metadata(&path).unwrap().len(),
            segments.len() as u64 * segment
        );

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn packed_word_matches_scalar_reference() {
        fn scalar(seq: &[u8]) -> u64 {
            let mut word = 0u64;
            for &base in &seq[..32] {
                word = (word << 2) | u64::from(valid_ascii_base_bits(base));
            }
            word
        }
        let alphabet = b"ACGT";
        // Deterministic pseudo-random coverage plus structured edge cases.
        let mut state = 0x1234_5678_9abc_def0u64;
        for case in 0..2048 {
            let mut seq = [0u8; 32];
            for (i, slot) in seq.iter_mut().enumerate() {
                state = state
                    .wrapping_mul(6364136223846793005)
                    .wrapping_add(1442695040888963407);
                *slot = if case < 4 {
                    alphabet[(case + i) % 4]
                } else {
                    alphabet[(state >> 33) as usize % 4]
                };
            }
            assert_eq!(
                pack_valid_word_32(&seq),
                scalar(&seq),
                "mismatch for {:?}",
                std::str::from_utf8(&seq).unwrap()
            );
        }
    }

    use super::*;

    #[test]
    fn deferred_uncolored_atlas_chunks_preserve_graph_buckets() {
        let dir = std::env::temp_dir().join(format!(
            "cf3-uncolored-atlas-bucket-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        fs::create_dir_all(&dir).unwrap();
        let mut params = BuildParams::new(crate::GraphInput::References, "test".to_string());
        params.k = 31;
        params.minimizer_len = 15;
        params.vertex_partitions = 1;
        params.threads = 2;
        params.work_dir = dir.to_string_lossy().into_owned();
        let sink = SharedBucketSink::create(&params, ATLAS_GRAPH_COUNT + 1).unwrap();
        let expected = [(0, b'A'), (7, b'C'), (ATLAS_GRAPH_COUNT, b'G')];
        let mut emitters = Vec::new();
        for repeat in 0..2 {
            let mut emitter = sink.deferred_uncolored_emitter();
            for &(graph_id, base) in &expected {
                for _ in 0..(repeat + 1) {
                    emitter
                        .add_valid(
                            &WeakSuperKmer {
                                graph_id,
                                offset: 0,
                                len: 31,
                                source_id: None,
                                left_discontinuous: false,
                                right_discontinuous: false,
                            },
                            &[base; 31],
                        )
                        .unwrap();
                }
            }
            emitters.push(emitter);
        }
        sink.flush_uncolored_emitters(emitters).unwrap();
        let stats = sink.finish().unwrap();

        let (store, entries) = BucketStore::open_dir(&stats.bucket_dir).unwrap();
        for &(graph_id, base) in &expected {
            let entry = entries
                .iter()
                .find(|entry| entry.graph_id == graph_id)
                .expect("bucket in manifest");
            let mut reader = store.reader(entry).unwrap();
            let mut record = BucketRecord::default();
            let mut count = 0;
            while reader.next_record_into(&mut record).unwrap() {
                assert_eq!(record.graph_id, graph_id);
                assert_eq!(record.label, vec![base; 31]);
                count += 1;
            }
            assert_eq!(count, 3);
        }
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn colored_atlas_windows_preserve_global_source_order() {
        let dir = std::env::temp_dir().join(format!(
            "cf3-colored-bucket-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        fs::create_dir_all(&dir).unwrap();
        let mut params = BuildParams::new(crate::GraphInput::References, "test".to_string());
        params.color = true;
        params.k = 31;
        params.minimizer_len = 15;
        params.vertex_partitions = 1;
        params.threads = 1;
        params.work_dir = dir.to_string_lossy().into_owned();
        let sink = SharedBucketSink::create(&params, 1).unwrap();

        for (source_min, source_max, sources) in
            [(1, 3, vec![3, 1, 3, 2, 1]), (4, 6, vec![6, 4, 5, 4])]
        {
            let mut emitter = sink.emitter();
            for source_id in sources {
                emitter
                    .add_valid(
                        &WeakSuperKmer {
                            graph_id: 0,
                            offset: 0,
                            len: 31,
                            source_id: Some(source_id),
                            left_discontinuous: false,
                            right_discontinuous: false,
                        },
                        &[b'A'; 31],
                    )
                    .unwrap();
            }
            emitter.finish().unwrap();
            sink.flush_colored_window(source_min, source_max).unwrap();
        }
        let stats = sink.finish().unwrap();

        let (store, entries) = BucketStore::open_dir(&stats.bucket_dir).unwrap();
        let entry = entries
            .iter()
            .find(|entry| entry.graph_id == 0)
            .expect("bucket in manifest");
        let mut reader = store.reader(entry).unwrap();
        assert!(reader.header().compressed);
        let mut sources = Vec::new();
        let mut record = BucketPackedRecord::default();
        while reader.next_packed_record_into(&mut record).unwrap() {
            sources.push(record.source_id.unwrap());
        }
        assert_eq!(sources, [1, 1, 2, 3, 3, 4, 4, 5, 6]);

        // Clipping the container leaves the manifest claiming a length the
        // chain can no longer supply, which is the container-shaped version of
        // a bucket file cut short by a killed run.
        let container_path = stats.bucket_dir.join("00000.wskc");
        let len = fs::metadata(&container_path).unwrap().len();
        OpenOptions::new()
            .write(true)
            .open(&container_path)
            .unwrap()
            .set_len(len - 1)
            .unwrap();
        let (store, entries) = BucketStore::open_dir(&stats.bucket_dir).unwrap();
        let entry = entries
            .iter()
            .find(|entry| entry.graph_id == 0)
            .expect("bucket in manifest");
        let mut truncated = store.reader(entry).unwrap();
        let mut record = BucketPackedRecord::default();
        let mut failed = false;
        loop {
            match truncated.next_packed_record_into(&mut record) {
                Ok(true) => {}
                Ok(false) => break,
                Err(_) => {
                    failed = true;
                    break;
                }
            }
        }
        assert!(failed, "truncated compressed block must be rejected");
        fs::remove_dir_all(dir).unwrap();
    }

    #[test]
    fn colored_worker_tails_preserve_cpp_worker_order() {
        let dir = std::env::temp_dir().join(format!(
            "cf3-colored-worker-tails-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        fs::create_dir_all(&dir).unwrap();
        let mut params = BuildParams::new(crate::GraphInput::References, "test".to_string());
        params.color = true;
        params.k = 31;
        params.minimizer_len = 15;
        params.threads = 2;
        params.work_dir = dir.to_string_lossy().into_owned();
        let sink = SharedBucketSink::create(&params, 1).unwrap();

        let mut emitters = Vec::new();
        for sources in [[3, 1], [4, 2]] {
            let mut emitter = sink.emitter();
            for source_id in sources {
                emitter
                    .add_valid(
                        &WeakSuperKmer {
                            graph_id: 0,
                            offset: 0,
                            len: 31,
                            source_id: Some(source_id),
                            left_discontinuous: false,
                            right_discontinuous: false,
                        },
                        &[b'A'; 31],
                    )
                    .unwrap();
            }
            emitters.push(emitter);
        }
        sink.flush_colored_emitters(emitters).unwrap();
        let stats = sink.finish().unwrap();

        let (store, entries) = BucketStore::open_dir(&stats.bucket_dir).unwrap();
        let entry = entries
            .iter()
            .find(|entry| entry.graph_id == 0)
            .expect("bucket in manifest");
        let mut reader = store.reader(entry).unwrap();
        let mut sources = Vec::new();
        let mut record = BucketPackedRecord::default();
        while reader.next_packed_record_into(&mut record).unwrap() {
            sources.push(record.source_id.unwrap());
        }
        assert_eq!(sources, [3, 1, 4, 2]);
        fs::remove_dir_all(dir).unwrap();
    }
}