znippy-common 0.12.0

Core logic and data structures for Znippy, a parallel chunked compression system.
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
//! `HotArchive` — the **dynamic half** of a znippy archive: append blobs and
//! index rows at O(1) per append, and pay the static seal exactly once.
//!
//! # The defect this exists to remove, measured
//!
//! [`append_files`](crate::append_files) re-seals the *whole* metadata tail on
//! every call: [`ArrowIpcSinkAppend::open_existing`](crate::ArrowIpcSinkAppend::open_existing)
//! decodes every pre-existing row out of the lookup section, `finish()` re-emits
//! them as a data sub-index, re-sorts all of them, rebuilds the fst trie over all
//! of them, and rewrites manifest and footer. So one append costs O(rows already
//! in the archive) and N appends cost **O(N²)**.
//!
//! That is not a theory. **MEASURED on oden 2026-08-04**, loadavg 14–17, 32
//! cores / 512 GB, release build, archive on **md1** (`/dev/md1`, not tmpfs — so
//! the two fsyncs per append are real), one archive, two entries appended per
//! call (a `pack-*.pack` and its `.idx`, ~1.5 KiB together),
//! `SkipPolicy::already_compressed()`. Same fixture, same rungs, A/B in one
//! binary:
//!
//! | appends | CPU/append, re-seal | CPU/append, hot | wall total, re-seal | wall total, hot |
//! |---|---|---|---|---|
//! | 800 | 1.88 ms | — | | |
//! | 2 000 | 2.66 ms | 0.075 ms | | |
//! | 4 000 | 5.38 ms | 0.075 ms | | |
//! | 8 000 | **10.18 ms** | **0.060 ms** | **61.16 s** | **2.29 s** |
//! | 32 000 | (not run) | 0.061 ms | | 5.62 s |
//!
//! Re-seal's per-append cost doubles every time N doubles — a straight line
//! through the origin, the signature of a quadratic total. The hot path's is
//! **flat from 2 000 to 32 000 appends**, which is the claim. At 8 000 appends
//! that is **26.7× on wall clock and 170× on CPU per append**, and both ratios
//! grow with N because only one side of them grows.
//!
//! INFERRED, not measured: extrapolating re-seal's line, the 100 000th append
//! costs ~127 ms and getting there costs ~1.8 h of CPU. The hot path's 100 000th
//! append costs what its 2 000th did.
//!
//! The seal is the once-only price: **0.08 s of CPU for 64 000 rows**. At 8 000
//! appends the two paths land on the same archive — 15 929 871 B sealed from hot
//! against 15 932 909 B re-sealed, the 3 038 B being the seed entry
//! `append_files` needs and the hot path does not (it can start from nothing).
//!
//! # The two-phase shape
//!
//! ```text
//!   HOT                                        COLD
//!   foo.znippy        blobs only, pure append   foo.znippy   [blobs][index][lookup][trie][manifest][footer]
//!   foo.znippy.hot.NNNNN   Arrow IPC journal    (journal removed)
//! ```
//!
//! * [`HotArchive::append`] writes the blob bytes past the blob cursor and
//!   *one* Arrow IPC RecordBatch of the new index rows to the journal. It never
//!   reads, sorts or rewrites a row it wrote earlier, so its cost depends only on
//!   what is being appended. **O(1) in the archive's size.**
//! * [`HotArchive::seal`] pays the static cost once: one sorted lookup, one fst
//!   trie, one manifest, one footer.
//!
//! This is znippy's own `znippy-iceberg` architecture — dynamic metadata store,
//! then `seal()` freezing it into the static `.znippy` with the blobs copied
//! verbatim — with the metadata store made local and cheap instead of an Iceberg
//! warehouse. Iceberg's `fast_append` rewrites its manifest list on every commit,
//! which is the same O(N²) in a different format.
//!
//! # Why the sealed output is byte-identical to `create_archive`
//!
//! The blobs are written in the same order at the same offsets, and the seal
//! pushes exactly one data sub-index carrying the rows in insertion order —
//! literally the same call [`create_archive`](crate::create_archive) makes. So
//! *appending N files one at a time and sealing* produces the **same bytes** as
//! *creating the archive from all N at once*. `seal_matches_create_archive_byte_for_byte`
//! asserts that on real archives rather than asserting a row count, because a
//! seal that silently dropped the trie would still be able to report the right
//! number of rows.
//!
//! # Journal segments, and why there is more than one file
//!
//! An Arrow IPC *stream* begins with a schema message, so appending batches to
//! one across process restarts is not possible without re-emitting the schema —
//! 424 B of flatbuffer metadata on a four-row batch, paid per push. Instead each
//! **process** that opens the archive for append starts a new segment
//! `foo.znippy.hot.NNNNN`; the schema is written once per segment, and a push
//! costs one RecordBatch message. Segment count grows with restarts, not with
//! pushes.
//!
//! A torn segment (killed mid-write) is read up to its last complete message and
//! the rest is discarded, which is what a log reader must do; the blob bytes
//! whose rows were lost stay in the file as dead payload the seal drops, exactly
//! like [`AppendReport::rows_replaced`](crate::AppendReport::rows_replaced).
//!
//! # Ordering, so a row never points at a blob that is not there
//!
//! `append` fsyncs the blob bytes **before** the journal batch that references
//! them. A crash between the two loses the append and nothing else; a crash the
//! other way round would leave an index row pointing into a hole.
//!
//! # Groups, bodies from a reader, two names on one blob, ends
//!
//! * Every row lies in a **group** ([`Group`]: one package type in one repository).
//!   The path-only calls ([`append`](HotArchive::append), the [`ZnippyReader`]
//!   methods) use the default group, so an archive that never names a group seals
//!   byte for byte as before. [`append_in`](HotArchive::append_in) and the
//!   [`commit`](HotArchive::commit) ops name one; the seal writes one data
//!   sub-index per group.
//! * [`stage_from`](HotArchive::stage_from) writes a body from a reader a piece at
//!   a time past the blob cursor ([`STREAM_PIECE`] in memory at most), BLAKE3 and
//!   size computed as it goes, and fsyncs it. The body is read outside the writer
//!   lock, which it takes for one piece at a time: a slow reader holds no other
//!   writer. No row names it yet: a read error, a short body or a wrong digest
//!   leaves an orphan, which the next open cuts when it is last in the file.
//!   [`commit`](HotArchive::commit) then writes the rows of many ops as ONE journal
//!   message with one fsync — a put, a second name on a blob already written
//!   (no byte written), an end.
//! * An **end** hides a name. In a plain archive the seal drops it; in a stack
//!   layer it is a tombstone over the layers below.
//!
//! A journal written before groups existed holds the base columns alone ("V1"),
//! and a plain archive keeps writing them while every row fits — default group,
//! own bytes, nothing ended — so the per-append journal cost measured above is
//! unchanged. The first row that does not fit starts a new segment with the wider
//! schema ("V2").
//!
//! # Cuts the open repairs
//!
//! * A journal that no longer starts at segment 0 beside a sealed file is a seal
//!   whose segment removal was cut: the sealed tail is the truth, and the open
//!   finishes the removal instead of reading half a journal and cutting the tail.
//! * Re-heating a sealed archive writes segment 0 under a temporary name and
//!   renames it into place, so a cut never leaves an empty segment 0 that would
//!   read as "no rows" and cut every blob.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs::File;
use std::io::Read;
use std::os::unix::fs::FileExt;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard};

use anyhow::{anyhow, bail, ensure, Result};
use arrow::datatypes::Schema;
use arrow::ipc::writer::StreamWriter;

use crate::archive::ZnippyReader;
use crate::codec::CompressCtx;
use crate::index::{data_subindex_schema, ChunkLoc, ZNIPPY_LINKS_MODULE, ZNIPPY_STACK_MODULE};
use crate::meta_sink::{ArchiveMetaSink, ArrowIpcSink, ReservedSection, ReservedSectionBuilder};
use crate::meta_sink_append::write_blobs;
use crate::rows::{
    fill, fits_v1, own_bytes_end, rows_batch, rows_schema, sync_dir_of, Blob, BlobRef, Group, SectionRows,
    Lookup, RowEntry, RowIndex, SegmentCursor, Was, STREAM_PIECE,
};
use crate::stack::{LayerInfo, StackSection};

/// Suffix of a journal segment: `<archive>.hot.<NNNNN>`.
const JOURNAL_INFIX: &str = ".hot.";

/// What one [`HotArchive::append`] did. Deliberately the same three counts
/// [`AppendReport`](crate::AppendReport) reports, so a caller can swap paths
/// without re-reading its own accounting.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct HotAppendReport {
    /// Index rows written by this append (one per chunk).
    pub rows_added: u64,
    /// Rows already in the journal that this append superseded, by
    /// `relative_path`. Their blob bytes stay in the file as dead payload.
    pub rows_replaced: u64,
    /// Byte offset the appended blob region started at.
    pub blob_append_offset: u64,
    /// Blob payload bytes written (compressed or stored raw).
    pub blob_bytes_added: u64,
    /// Bytes the journal batch cost — the index-side price of this append.
    pub journal_bytes_added: u64,
}

/// What one [`HotArchive::commit`] did.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct HotCommitReport {
    /// Rows the journal message carries (one per chunk, one per end).
    pub rows_added: u64,
    /// Names that were live before and were replaced or ended.
    pub rows_replaced: u64,
    pub journal_bytes_added: u64,
}

/// What one [`HotArchive::seal`] did.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct HotSealReport {
    pub archive: PathBuf,
    /// Rows carried out of the journal into the static index.
    pub rows_sealed: u64,
    /// Journal segments removed.
    pub segments_removed: usize,
    /// Journal bytes reclaimed.
    pub journal_bytes_reclaimed: u64,
    /// Final size of the sealed archive.
    pub sealed_total_bytes: u64,
}

/// What a body written from a reader must be. A mismatch is refused after the
/// last byte, before any row names the body.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Expect {
    pub size: Option<u64>,
    pub blake3: Option<[u8; 32]>,
}

/// A body written and fsynced by [`HotArchive::stage_from`], named by no row
/// yet. Commit it with [`HotOp::Put`] — on the archive that wrote it, and on no
/// other. Cloning it lets two names share the one body.
#[derive(Debug, Clone)]
pub struct Staged {
    owner: Arc<()>,
    at: BlobRef,
    size: u64,
    blake3: [u8; 32],
    written: u64,
    hashed: u64,
}

impl Staged {
    /// The body's length.
    pub fn size(&self) -> u64 {
        self.size
    }

    /// The bytes of the body this stage wrote to the file: what it stores, after
    /// compression.
    pub fn written(&self) -> u64 {
        self.written
    }

    /// The bytes this stage fed to BLAKE3, laying the body: the whole body's and every
    /// chunk's.
    pub fn hashed(&self) -> u64 {
        self.hashed
    }

    /// The BLAKE3 of the whole body, computed as it was written.
    pub fn blake3(&self) -> [u8; 32] {
        self.blake3
    }

    /// Where the bytes lie: one chunk when stored raw or compressed whole, one
    /// per [`STREAM_PIECE`] when a compressible body was compressed in pieces.
    pub fn location(&self) -> &BlobRef {
        &self.at
    }
}

/// One change [`HotArchive::commit`] writes.
#[derive(Debug, Clone)]
pub enum HotOp {
    /// Name a staged body.
    Put {
        group: Group,
        name: String,
        staged: Staged,
    },
    /// Name bytes already in the archive (or, in a stack layer, in a layer below)
    /// — no byte is written. Both names then keep the bytes.
    Link {
        group: Group,
        name: String,
        to: BlobRef,
    },
    /// Hide a name.
    End { group: Group, name: String },
}

/// A znippy archive in its **hot** phase: blobs appended in place, index rows in
/// a journal beside it.
///
/// [`open`](Self::open) reads the journal once (O(rows)); every [`append`](Self::append)
/// after that is O(what is appended). Holding the rows in memory is what buys
/// that, and it is the same set of rows the old path decoded *per append*.
///
/// # Why an append no longer stops the readers
///
/// `append` used to take `&mut self`, so a caller sharing one archive across
/// threads had to put it behind an `RwLock` and take the EXCLUSIVE guard for the
/// whole call — and the whole call is two `fsync`s. MEASURED in holger
/// (`.nornir/stinky/12-dataplane-finished.md` §5.4, oden 2026-09-20, 32 readers
/// against 4 publishers): readers kept **2.2–3.0 %** of their throughput, and it
/// got WORSE when group commit doubled the write rate, because the write side
/// then held that guard for a larger share of the window. Nothing the caller
/// could write shortened it; the `&mut` was the mechanism.
///
/// The exclusion was never needed for the durable part. An append writes blob
/// bytes **past** the blob cursor and a journal message **past** the journal's
/// end — two regions no reader can name, because no index row points at them
/// yet. The only instant a reader must not observe is the index swap, and that
/// is a `Vec::push` and a `HashMap::insert` per row appended.
///
/// So the three states are guarded separately:
///
/// | state | guard | held for |
/// |---|---|---|
/// | blob cursor · journal writer · codec context | `HotWriter` behind a `Mutex` | the whole append, one piece of a body staged from a reader — WRITERS ONLY |
/// | the live index rows | the row index behind an `RwLock` | the swap, after both fsyncs |
/// | blob end, for the accessor | `AtomicU64` | nothing |
///
/// `append` therefore takes `&self`, and a reader that is not naming a row this
/// append creates never waits on either fsync. [`fsyncs`](Self::fsyncs) counts them so
/// the claim is countable rather than argued.
pub struct HotArchive {
    archive: PathBuf,
    blobs: Arc<File>,
    /// Reader-visible state, and the ONLY thing an append takes an exclusive
    /// guard on — after both fsyncs are already durable.
    index: RwLock<RowIndex>,
    /// Published mirror of `HotWriter::blob_end`.
    blob_end: AtomicU64,
    /// Append-side state: one appender at a time, and no reader waits on it.
    writer: Mutex<HotWriter>,
    /// `fsync`s this archive has paid inside [`append`](Self::append),
    /// [`stage_from`](Self::stage_from) and [`commit`](Self::commit). An append
    /// costs exactly TWO, whatever it appends; a stage one and a commit one.
    fsyncs: AtomicU64,
    /// Whole copies of the live index taken so far: one per seal, and no read pays one
    /// ([`with_index`](Self::with_index) reads under the guard).
    index_copies: AtomicU64,
    policy: crate::SkipPolicy,
    /// Set when this archive is a stack layer.
    layer: Option<LayerInfo>,
    /// Identity a [`Staged`] carries, so a body is only ever named by the
    /// archive whose file holds it.
    token: Arc<()>,
    /// The journal segments of other writers of this file, each read up to where this
    /// writer left it, and the numbers of its own ([`catch_up`](Self::catch_up)).
    others: Mutex<Others>,
    /// A test's own, run once by the next append once it took its write position
    /// ([`at_position`](Self::at_position)).
    #[cfg(test)]
    at_position: Mutex<Option<Box<dyn FnOnce() + Send>>>,
}

/// **The other writers' journal segments, as this writer read them**: a stack's writers
/// write one hot layer in turns, each into a segment of its own
/// ([`crate::StackWriter::catch_up`]). Locked after the writer's lock, never before.
#[derive(Default)]
struct Others {
    /// Segments not this writer's own, each read up to where it was left.
    cursors: BTreeMap<u32, SegmentCursor>,
    /// The segments this writer made.
    mine: BTreeSet<u32>,
    /// Rows the open read from the journal.
    at_open: u64,
}

/// The append side, behind a `Mutex` that serialises WRITERS against each other
/// and nothing else.
struct HotWriter {
    /// Byte offset one past the last blob written — the authoritative cursor.
    blob_end: u64,
    /// The segment this process appends to, schema already written.
    journal: Journal,
    /// Long-lived, per Design Law 2. The raw OpenZL context is `Send` but not
    /// `Sync`; the append lock owns it.
    ctx: CompressCtx,
}

/// **A body being laid a piece at a time** ([`HotArchive::stage_from`],
/// [`HotArchive::stage_all`]): where its pieces lie, its size and its BLAKE3 so
/// far. Each piece is laid under the writer lock, at the cursor as it is then.
struct Laying {
    raw: bool,
    whole: blake3::Hasher,
    size: u64,
    chunks: Vec<ChunkLoc>,
    /// Raw: the BLAKE3 of the last chunk so far, when it is not the first. A piece
    /// that lies right after that chunk in the file makes it longer. The first chunk is
    /// the body so far: its BLAKE3 is `whole`'s, and its bytes are hashed once.
    run: blake3::Hasher,
    /// A compressed piece, the buffer kept from one piece to the next.
    frame: Vec<u8>,
    /// The bytes written to the file, and the bytes fed to BLAKE3 ([`Staged::hashed`]).
    written: u64,
    hashed: u64,
}

impl Laying {
    fn new(raw: bool) -> Self {
        Self {
            raw,
            whole: blake3::Hasher::new(),
            size: 0,
            chunks: Vec::new(),
            run: blake3::Hasher::new(),
            frame: Vec::new(),
            written: 0,
            hashed: 0,
        }
    }

    /// `bytes`, one piece, at the cursor of `w`: written, and the cursor moved
    /// past it. Nothing of it is counted when it was not written.
    fn lay(&mut self, w: &mut HotWriter, blobs: &File, bytes: &[u8]) -> Result<()> {
        let at = w.blob_end;
        let n = bytes.len() as u64;
        if self.raw {
            blobs.write_all_at(bytes, at)?;
            match self.chunks.last_mut() {
                Some(c) if c.blob_offset + c.blob_size == at => {
                    c.blob_size += n;
                    c.uncompressed_size += n;
                }
                _ => {
                    self.close_last();
                    self.chunks.push(ChunkLoc {
                        chunk_seq: u32::try_from(self.chunks.len())?,
                        fdata_offset: self.size,
                        blob_offset: at,
                        blob_size: n,
                        uncompressed_size: n,
                        compressed: false,
                        checksum: [0; 32],
                    });
                }
            }
            if self.chunks.len() > 1 {
                self.run.update(bytes);
                self.hashed += n;
            }
            self.written += n;
            w.blob_end = at + n;
        } else {
            self.close_last();
            w.ctx.compress_into(bytes, &mut self.frame)?;
            let (on_disk, compressed): (&[u8], bool) = if self.frame.len() < bytes.len() {
                (&self.frame, true)
            } else {
                (bytes, false)
            };
            blobs.write_all_at(on_disk, at)?;
            // The first piece's BLAKE3 is `whole`'s once it is whole (`close_last`).
            let checksum = if self.chunks.is_empty() {
                [0; 32]
            } else {
                self.hashed += n;
                *blake3::hash(bytes).as_bytes()
            };
            let written = on_disk.len() as u64;
            self.chunks.push(ChunkLoc {
                chunk_seq: u32::try_from(self.chunks.len())?,
                fdata_offset: self.size,
                blob_offset: at,
                blob_size: written,
                uncompressed_size: n,
                compressed,
                checksum,
            });
            self.written += written;
            w.blob_end = at + on_disk.len() as u64;
        }
        self.whole.update(bytes);
        self.hashed += n;
        self.size += n;
        Ok(())
    }

    /// The last chunk is whole, before a piece of the body after it: its BLAKE3. The
    /// first chunk is all of the body so far, so its BLAKE3 is `whole`'s, and no byte
    /// of it is hashed twice; a raw run after it has its own. (A compressed piece after
    /// the first was hashed as it was laid.)
    fn close_last(&mut self) {
        if let [first] = self.chunks.as_mut_slice() {
            first.checksum = *self.whole.clone().finalize().as_bytes();
        } else if self.raw
            && let Some(c) = self.chunks.last_mut()
        {
            let run = std::mem::replace(&mut self.run, blake3::Hasher::new());
            c.checksum = *run.finalize().as_bytes();
        }
    }

    /// The body as `expect` says it must be, else why not.
    fn check(&self, expect: &Expect) -> Result<()> {
        if let Some(want) = expect.size {
            let size = self.size;
            ensure!(
                want == size,
                "the body is {size} bytes, {want} were expected"
            );
        }
        if let Some(want) = expect.blake3 {
            let digest = *self.whole.clone().finalize().as_bytes();
            ensure!(want == digest, "the body's BLAKE3 is not the one expected");
        }
        Ok(())
    }

    /// Where its bytes lie, when they are one run in the file: its first byte and
    /// one past its last.
    fn one_run(&self) -> Option<(u64, u64)> {
        let first = self.chunks.first()?;
        let mut end = first.blob_offset;
        for c in &self.chunks {
            if c.blob_offset != end {
                return None;
            }
            end += c.blob_size;
        }
        Some((first.blob_offset, end))
    }

    /// The body laid, staged for `owner`: where it lies (an empty body is one empty
    /// chunk at `empty_at`, as `create_archive` stores it), its size, its BLAKE3 and
    /// the counts.
    fn end(mut self, empty_at: u64, owner: Arc<()>) -> Staged {
        let digest = *self.whole.finalize().as_bytes();
        if let [one] = self.chunks.as_mut_slice() {
            one.checksum = digest;
        } else {
            self.close_last();
        }
        if self.chunks.is_empty() {
            self.chunks.push(ChunkLoc {
                chunk_seq: 0,
                fdata_offset: 0,
                blob_offset: empty_at,
                blob_size: 0,
                uncompressed_size: 0,
                compressed: false,
                checksum: digest,
            });
        }
        Staged {
            owner,
            at: BlobRef::new(None, self.chunks, Some(digest)),
            size: self.size,
            blake3: digest,
            written: self.written,
            hashed: self.hashed,
        }
    }
}

/// One open journal segment.
struct Journal {
    w: StreamWriter<File>,
    schema: Arc<Schema>,
    v2: bool,
    number: u32,
    len: u64,
}

impl Journal {
    fn schema_for(v2: bool, layer: Option<&LayerInfo>) -> Arc<Schema> {
        if v2 {
            rows_schema(&layer.map(|l| l.to_metadata()).unwrap_or_default())
        } else {
            data_subindex_schema()
        }
    }

    /// A new, empty segment `number`, its schema written.
    fn create(archive: &Path, number: u32, v2: bool, layer: Option<&LayerInfo>) -> Result<Self> {
        let path = segment_path(archive, number);
        let f = File::create(&path)
            .map_err(|e| anyhow!("hot: create journal segment {}: {e}", path.display()))?;
        let j = Self::start(f, number, v2, layer)?;
        sync_dir_of(&path);
        Ok(j)
    }

    /// Segment `number` holding `entries` from its first byte: written under a
    /// temporary name, fsynced, then renamed into place — so no reader and no
    /// later open ever sees it without them.
    fn create_seeded(
        archive: &Path,
        number: u32,
        v2: bool,
        layer: Option<&LayerInfo>,
        entries: &[RowEntry],
    ) -> Result<Self> {
        let path = segment_path(archive, number);
        let mut tmp = path.as_os_str().to_os_string();
        tmp.push(".seed");
        let tmp = PathBuf::from(tmp);
        let f = File::create(&tmp)
            .map_err(|e| anyhow!("hot: create journal seed {}: {e}", tmp.display()))?;
        let mut j = Self::start(f, number, v2, layer)?;
        if !entries.is_empty() {
            let batch = rows_batch(&j.schema, entries)?;
            j.w.write(&batch)
                .map_err(|e| anyhow!("hot: seeding journal: {e}"))?;
            j.w.flush()
                .map_err(|e| anyhow!("hot: journal flush: {e}"))?;
        }
        j.w.get_ref()
            .sync_all()
            .map_err(|e| anyhow!("hot: journal fsync: {e}"))?;
        j.len = j.w.get_ref().metadata()?.len();
        std::fs::rename(&tmp, &path)
            .map_err(|e| anyhow!("hot: placing journal segment {}: {e}", path.display()))?;
        sync_dir_of(&path);
        Ok(j)
    }

    fn start(f: File, number: u32, v2: bool, layer: Option<&LayerInfo>) -> Result<Self> {
        let schema = Self::schema_for(v2, layer);
        let opts = arrow::ipc::writer::IpcWriteOptions::try_new(
            JOURNAL_ALIGNMENT,
            false,
            arrow::ipc::MetadataVersion::V5,
        )
        .map_err(|e| anyhow!("hot: journal write options: {e}"))?;
        let w = StreamWriter::try_new_with_options(f, schema.as_ref(), opts)
            .map_err(|e| anyhow!("hot: journal schema: {e}"))?;
        let len = w.get_ref().metadata().map(|m| m.len()).unwrap_or(0);
        Ok(Self {
            w,
            schema,
            v2,
            number,
            len,
        })
    }
}

/// What the open found on disk.
struct Loaded {
    index: RowIndex,
    /// One past the furthest own byte any row ever read names — live, replaced
    /// or ended — so the cursor never moves back under bytes a reader of an
    /// older index may still name.
    own_end: u64,
    /// Rows to seed a fresh segment 0 with (a sealed archive going hot).
    seed: Option<Vec<RowEntry>>,
    next_segment: u32,
    /// The segments hold rows the V1 schema cannot carry.
    needs_v2: bool,
    /// The segments read, each where the read ended, and the rows read.
    cursors: Vec<SegmentCursor>,
    read: u64,
}

impl HotArchive {
    /// Open `archive` for hot appends, creating it if absent.
    ///
    /// Three entry states, all handled here so no caller has to know which it is:
    ///
    /// * **already hot** — journal segments exist; their rows are loaded and the
    ///   blob cursor is taken from them.
    /// * **sealed** — a static `.znippy`; its rows are recovered into a fresh
    ///   segment and the (rebuildable) metadata tail is dropped. O(rows), once.
    ///   A stack's file (it carries a stack section) is refused: a stack's seal
    ///   is never consumed — see [`crate::stack`].
    /// * **absent** — a new archive at blob offset 0.
    pub fn open(archive: &Path, level: i32, policy: crate::SkipPolicy) -> Result<Self> {
        Self::open_inner(archive, level, policy, None)
    }

    /// Open (or create) the hot layer of a stack at `path`. Its journal carries
    /// `layer`; a journal that names another place in the stack is refused.
    pub(crate) fn open_layer(
        path: &Path,
        level: i32,
        policy: crate::SkipPolicy,
        layer: LayerInfo,
    ) -> Result<Self> {
        Self::open_inner(path, level, policy, Some(layer))
    }

    fn open_inner(
        archive: &Path,
        level: i32,
        policy: crate::SkipPolicy,
        layer: Option<LayerInfo>,
    ) -> Result<Self> {
        let archive = archive.to_path_buf();
        let loaded = Self::load(&archive, layer.as_ref())?;
        let v2 = layer.is_some() || loaded.needs_v2;
        let journal = match &loaded.seed {
            Some(entries) => {
                Journal::create_seeded(&archive, loaded.next_segment, v2, layer.as_ref(), entries)?
            }
            None => Journal::create(&archive, loaded.next_segment, v2, layer.as_ref())?,
        };
        let blob_end = loaded.own_end;
        let others = Others {
            cursors: (loaded.cursors.into_iter())
                .map(|c| (c.number, c))
                .collect(),
            mine: BTreeSet::from([journal.number]),
            at_open: loaded.read,
        };
        let blobs = Arc::new(
            std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(false)
                .open(&archive)
                .map_err(|e| anyhow!("hot: open {} : {e}", archive.display()))?,
        );
        // Drop anything past the blob region — a stale metadata tail from the
        // sealed path, or the orphan payload of a cut append. Idempotent.
        if blobs.metadata()?.len() > blob_end {
            blobs.set_len(blob_end)?;
            blobs.sync_all()?;
        }
        Ok(Self {
            archive,
            blobs,
            blob_end: AtomicU64::new(blob_end),
            index: RwLock::new(loaded.index),
            writer: Mutex::new(HotWriter {
                blob_end,
                journal,
                ctx: CompressCtx::new(level)?,
            }),
            policy,
            fsyncs: AtomicU64::new(0),
            index_copies: AtomicU64::new(0),
            layer,
            token: Arc::new(()),
            others: Mutex::new(others),
            #[cfg(test)]
            at_position: Mutex::new(None),
        })
    }

    fn load(archive: &Path, layer: Option<&LayerInfo>) -> Result<Loaded> {
        let mut segments = journal_segments(archive)?;
        let sealed_manifest = || {
            (archive.is_file())
                .then(|| crate::index::read_znippy_full_manifest(archive).ok())
                .flatten()
        };
        // A journal that does not start at 0 beside a sealed file: the seal wrote
        // its tail and was cut while removing the segments. Finish the removal.
        if segments.first().is_some_and(|(n, _)| *n != 0) && layer.is_none() {
            ensure!(
                sealed_manifest().is_some(),
                "hot: {} has journal segments from {} on, segment 0 is gone and the file is \
                 not sealed: rows are lost; refusing to cut the file",
                archive.display(),
                segments[0].0
            );
            for (_, seg) in &segments {
                std::fs::remove_file(seg)
                    .map_err(|e| anyhow!("hot: removing journal {}: {e}", seg.display()))?;
            }
            sync_dir_of(archive);
            segments.clear();
        }

        let mut index = RowIndex::default();
        let mut own_end = 0u64;
        let mut needs_v2 = false;
        let mut cursors = Vec::new();
        let mut read = 0u64;
        if !segments.is_empty() {
            let mut found: Option<LayerInfo> = None;
            let mut plain = false;
            for (n, p) in &segments {
                let mut c = SegmentCursor::new(*n, p.clone());
                let (entries, _) = c.read_more(true)?;
                if let Some(m) = &c.metadata {
                    match LayerInfo::from_metadata(m)? {
                        Some(l) => {
                            ensure!(
                                found.is_none_or(|f| f == l),
                                "hot: the journal segments of {} name two places in a stack",
                                archive.display()
                            );
                            found = Some(l);
                        }
                        None => plain = true,
                    }
                }
                needs_v2 |= !fits_v1(&entries);
                read += entries.len() as u64;
                for e in entries {
                    own_end = own_end.max(own_bytes_end(&e));
                    index.apply(e);
                }
                cursors.push(c);
            }
            match (layer, found) {
                (None, Some(_)) => bail!(
                    "hot: {} is a stack layer; it is opened through its stack",
                    archive.display()
                ),
                (Some(want), Some(got)) => ensure!(
                    *want == got,
                    "hot: {} is layer {:?}, not {:?}",
                    archive.display(),
                    got,
                    want
                ),
                (Some(_), None) => ensure!(
                    !plain,
                    "hot: {} has a plain journal where a stack layer was asked for",
                    archive.display()
                ),
                (None, None) => {}
            }
            let next_segment = segments.last().map(|(n, _)| n + 1).unwrap_or(0);
            return Ok(Loaded {
                index,
                own_end,
                seed: None,
                next_segment,
                needs_v2,
                cursors,
                read,
            });
        }

        let Some((entries, _)) = sealed_manifest() else {
            // Absent, empty, or bytes no row names: a new archive.
            return Ok(Loaded {
                index,
                own_end,
                seed: None,
                next_segment: 0,
                needs_v2,
                cursors,
                read,
            });
        };
        ensure!(
            layer.is_none(),
            "hot: {} is sealed but has no journal; a sealed layer is never reopened hot",
            archive.display()
        );
        ensure!(
            !(entries.iter())
                .any(|e| e.module_name == ZNIPPY_STACK_MODULE
                    || e.module_name == ZNIPPY_LINKS_MODULE),
            "hot: {} is a stack's file; a stack's seal is never consumed — write a layer through \
             StackWriter",
            archive.display()
        );
        // Sealed → hot. The rows go into segment 0 (written whole, then renamed
        // in) BEFORE the tail is cut, so a cut in between leaves them readable.
        let data: Vec<&crate::index::ManifestEntry> = entries
            .iter()
            .filter(|e| !crate::index::is_reserved_module(&e.module_name))
            .collect();
        let seed = if data.iter().all(|e| e.pkg_type == 0 && e.repo.is_empty()) {
            let (paths, locs, bodies) = crate::meta_sink_append::recover_rows(archive, &entries)?;
            entries_by_name(Group::default(), paths, locs, bodies)
        } else {
            let file = File::open(archive)?;
            let sealed = crate::stack::load_sealed(&file)?;
            let mut out = Vec::new();
            for g in sealed.index.groups() {
                for (name, slot) in sealed.index.slots(g) {
                    out.push(RowEntry {
                        group: g.clone(),
                        name: name.to_string(),
                        slot: slot.clone(),
                    });
                }
            }
            out
        };
        needs_v2 = !fits_v1(&seed);
        for e in &seed {
            own_end = own_end.max(own_bytes_end(e));
            index.apply(e.clone());
        }
        Ok(Loaded {
            index,
            own_end,
            seed: Some(seed),
            next_segment: 0,
            needs_v2,
            cursors,
            read,
        })
    }

    /// Whether `archive` currently has a journal — i.e. is in its hot phase.
    pub fn is_hot(archive: &Path) -> bool {
        journal_segments(archive)
            .map(|s| !s.is_empty())
            .unwrap_or(false)
    }

    /// The archive path.
    pub fn archive(&self) -> &Path {
        &self.archive
    }

    /// Live names, over every group.
    pub fn rows(&self) -> u64 {
        self.index_read().live()
    }

    /// Whether any name was ever set (live or ended) since the last seal.
    pub fn has_rows(&self) -> bool {
        self.index_read().has_rows()
    }

    /// Byte offset one past the last blob.
    pub fn blob_end(&self) -> u64 {
        self.blob_end.load(Ordering::Acquire)
    }

    /// `fsync`s paid so far: two per non-empty append, one per stage, one per
    /// non-empty commit.
    pub fn fsyncs(&self) -> u64 {
        self.fsyncs.load(Ordering::Relaxed)
    }

    /// The stack place, when this archive is a stack layer.
    pub fn layer(&self) -> Option<LayerInfo> {
        self.layer
    }

    /// The live index, shared.
    ///
    /// A poisoned lock means a thread panicked holding it. The index is mutated
    /// only under the write guard, with no fallible step, so there is nothing
    /// half-applied to recover from and refusing every later read would be the
    /// worse answer.
    fn index_read(&self) -> RwLockReadGuard<'_, RowIndex> {
        self.index.read().unwrap_or_else(|e| e.into_inner())
    }

    /// A whole copy of the live index, for a seal; a read takes
    /// [`with_index`](Self::with_index) instead, which copies nothing.
    pub(crate) fn index_snapshot(&self) -> RowIndex {
        self.index_copies.fetch_add(1, Ordering::Relaxed);
        self.index_read().clone()
    }

    /// `f` over the live index, under its read guard: nothing is copied. An append
    /// that publishes waits until `f` returns.
    pub(crate) fn with_index<R>(&self, f: impl FnOnce(&RowIndex) -> R) -> R {
        f(&self.index_read())
    }

    /// Whole copies of the live index taken so far ([`index_snapshot`](Self::index_snapshot)).
    #[cfg(test)]
    pub(crate) fn index_copies(&self) -> u64 {
        self.index_copies.load(Ordering::Relaxed)
    }

    /// **`at` runs once, in the next append, once that append took its write position**
    /// (a test's own): the append, holding the writers' lock, waits until `at` returns.
    #[cfg(test)]
    pub(crate) fn at_position(&self, at: impl FnOnce() + Send + 'static) {
        *self.at_position.lock().unwrap_or_else(|e| e.into_inner()) = Some(Box::new(at));
    }

    /// The append took its write position: a test's hook runs, once.
    #[cfg(test)]
    fn positioned(&self) {
        let at = self
            .at_position
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .take();
        if let Some(at) = at {
            at();
        }
    }

    pub(crate) fn blob_file(&self) -> Arc<File> {
        Arc::clone(&self.blobs)
    }

    /// What this archive says about `name` in `group`.
    pub fn lookup(&self, group: &Group, name: &str) -> Lookup {
        self.index_read().lookup(group, name)
    }

    /// The body of a live `name` whose bytes lie in this archive's file.
    pub fn get(&self, group: &Group, name: &str) -> Option<Blob> {
        match self.lookup(group, name) {
            Lookup::Live(b) if b.pack.is_none() => Some(Blob::new(Arc::clone(&self.blobs), b)),
            _ => None,
        }
    }

    /// Live names of `group`, in first-insertion order.
    pub fn names(&self, group: &Group) -> Vec<String> {
        self.index_read().names(group)
    }

    /// Every group that ever held a row, in first-insertion order.
    pub fn groups(&self) -> Vec<Group> {
        self.index_read().groups().to_vec()
    }

    /// Append `files` to the default group, paying only for `files`.
    ///
    /// Replace semantics match [`append_files`](crate::append_files): a
    /// `relative_path` already present is superseded and its old blob bytes
    /// become dead payload.
    ///
    /// Takes `&self`. The blob write with its fsync, and the journal commit with
    /// its fsync, are guarded against other WRITERS only; the live index is
    /// taken exclusively once, at the end, for the rows this call adds. A reader
    /// on a region this append is not writing never waits on either fsync — and
    /// it cannot be on one that it IS writing, because the row naming those
    /// bytes does not exist until after both.
    pub fn append(&self, files: &[(String, Vec<u8>)]) -> Result<HotAppendReport> {
        self.append_in(&Group::default(), files)
    }

    /// [`append`](Self::append) into `group`.
    pub fn append_in(&self, group: &Group, files: &[(String, Vec<u8>)]) -> Result<HotAppendReport> {
        group.check()?;
        if files.is_empty() {
            return Ok(HotAppendReport {
                blob_append_offset: self.blob_end(),
                ..Default::default()
            });
        }

        // ── writers only, from here down to the swap ─────────────────────────
        let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
        let w = &mut *guard;
        let blob_append_offset = w.blob_end;
        #[cfg(test)]
        self.positioned();

        // Blobs first, and durable before any row points at them. Written PAST
        // the cursor, into a region no live row names.
        let (paths, locs, cursor) =
            write_blobs(&self.blobs, w.blob_end, files, &mut w.ctx, self.policy)?;
        let blob_bytes_added = cursor - blob_append_offset;
        self.blobs.sync_all()?;
        self.fsyncs.fetch_add(1, Ordering::Relaxed);
        w.blob_end = cursor;
        self.blob_end.store(cursor, Ordering::Release);

        let entries: Vec<RowEntry> = (paths.into_iter().zip(locs))
            .map(|(name, loc)| RowEntry {
                group: group.clone(),
                name,
                slot: Some(BlobRef::new(None, vec![loc], None)),
            })
            .collect();
        // One RecordBatch, one message on the journal. No re-sort, no trie, no
        // manifest — that is the entire difference from `append_files`.
        let (rows_added, journal_bytes_added) = self.write_journal(w, &entries)?;
        let rows_replaced = self.publish(entries);
        Ok(HotAppendReport {
            rows_added,
            rows_replaced,
            blob_append_offset,
            blob_bytes_added,
            journal_bytes_added,
        })
    }

    /// Write a body from `body` past the blob cursor, a piece at a time, and
    /// fsync it. No row names it until [`commit`](Self::commit).
    ///
    /// * At most [`STREAM_PIECE`] of the body is in memory, whatever its size.
    /// * **The body is read outside the writer lock**: the lock is taken for one
    ///   piece at a time (compressed, placed at the cursor, written, the cursor
    ///   moved), never while the body is waited for. A slow reader (a socket, a
    ///   pipe) holds no other writer: the pieces of two bodies staged at once may
    ///   lie between each other in the file.
    /// * Stored raw (the [`SkipPolicy`](crate::SkipPolicy) says so by `name` or by
    ///   the first bytes): written as it is read; pieces that lie one after the
    ///   other in the file are ONE chunk, so a body no other writer came between
    ///   is one chunk, its BLAKE3 the body's.
    /// * Compressible: each piece is compressed on its own and kept compressed
    ///   when that is smaller — one chunk per piece. A body of one piece is one
    ///   chunk carrying the body's BLAKE3; a longer one carries one per piece.
    /// * A read error, a size other than `expect.size` or a digest other than
    ///   `expect.blake3` is refused: no row names the bytes written. When they
    ///   are the last bytes of the file (no other writer came after them) the
    ///   cursor goes back over them, and the next open cuts them; else they are
    ///   dead payload, as a replaced row's bytes are, until a compaction.
    pub fn stage_from(&self, name: &str, body: &mut dyn Read, expect: &Expect) -> Result<Staged> {
        let mut piece = vec![0u8; STREAM_PIECE];
        let mut n = fill(body, &mut piece)?;
        let mut laying = Laying::new(self.raw(name, &piece[..n]));
        let laid = loop {
            if n == 0 {
                break laying.check(expect);
            }
            if let Err(e) = self.lay_piece(&mut laying, &piece[..n]) {
                break Err(e);
            }
            n = match fill(body, &mut piece) {
                Ok(n) => n,
                Err(e) => break Err(e),
            };
        };
        if let Err(e) = laid {
            self.give_back(&laying);
            return Err(e);
        }
        self.blobs.sync_all()?;
        self.fsyncs.fetch_add(1, Ordering::Relaxed);
        Ok(laying.end(self.blob_end(), Arc::clone(&self.token)))
    }

    /// One piece of a body at the cursor, under the writer lock for that piece alone.
    fn lay_piece(&self, laying: &mut Laying, bytes: &[u8]) -> Result<()> {
        let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
        laying.lay(&mut guard, &self.blobs, bytes)?;
        self.blob_end.store(guard.blob_end, Ordering::Release);
        Ok(())
    }

    /// A refused body: the cursor goes back over its bytes when they are the last
    /// of the file, one run from where it started (no other writer came between
    /// or after them).
    fn give_back(&self, laying: &Laying) {
        let Some((start, end)) = laying.one_run() else {
            return;
        };
        let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
        if guard.blob_end == end {
            guard.blob_end = start;
            self.blob_end.store(start, Ordering::Release);
        }
    }

    /// Is a body called `name` that starts with `first` stored raw?
    fn raw(&self, name: &str, first: &[u8]) -> bool {
        self.policy.skip_by_path(Path::new(name))
            || (self.policy).skip_by_bytes(&first[..first.len().min(crate::SNIFF_PREFIX_LEN)])
    }

    /// **Was `staged` staged by this archive?** Only then can a commit here name it.
    pub fn staged_here(&self, staged: &Staged) -> bool {
        Arc::ptr_eq(&staged.owner, &self.token)
    }

    /// **The bytes of `staged`**, which no row names yet: read as a row's are.
    pub fn staged_body(&self, staged: &Staged) -> Result<Blob> {
        ensure!(
            self.staged_here(staged),
            "the body was staged by another archive"
        );
        Ok(Blob::new(Arc::clone(&self.blobs), staged.at.clone()))
    }

    /// **Many small bodies, one fsync**: each of `bodies` written past the blob
    /// cursor as [`stage_from`](Self::stage_from) writes one, one after the
    /// other, then ONE fsync for all. The bodies are in memory: the writer lock
    /// is held for all of them. No row names any until [`commit`](Self::commit).
    /// A refused body refuses all: the cursor does not move, and the next open
    /// cuts what was written.
    pub fn stage_all(&self, bodies: &[(&str, &[u8])]) -> Result<Vec<Staged>> {
        if bodies.is_empty() {
            return Ok(Vec::new());
        }
        let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
        let w = &mut *guard;
        let start = w.blob_end;
        let mut out = Vec::with_capacity(bodies.len());
        for (name, bytes) in bodies {
            let mut laying = Laying::new(self.raw(name, bytes));
            for piece in bytes.chunks(STREAM_PIECE) {
                if let Err(e) = laying.lay(w, &self.blobs, piece) {
                    w.blob_end = start;
                    return Err(e);
                }
            }
            out.push(laying.end(w.blob_end, Arc::clone(&self.token)));
        }
        if let Err(e) = self.blobs.sync_all() {
            w.blob_end = start;
            return Err(e.into());
        }
        self.fsyncs.fetch_add(1, Ordering::Relaxed);
        self.blob_end.store(w.blob_end, Ordering::Release);
        Ok(out)
    }

    /// Write `ops` as ONE journal message with one fsync, then make them visible
    /// together. A put must name a body this archive staged; a link must name
    /// bytes this archive holds (or, in a stack layer, bytes of a layer below).
    pub fn commit(&self, ops: Vec<HotOp>) -> Result<HotCommitReport> {
        if ops.is_empty() {
            return Ok(HotCommitReport::default());
        }
        let mut guard = self.writer.lock().unwrap_or_else(|e| e.into_inner());
        let w = &mut *guard;
        let mut entries = Vec::with_capacity(ops.len());
        for op in ops {
            let e = match op {
                HotOp::Put {
                    group,
                    name,
                    staged,
                } => {
                    ensure!(
                        Arc::ptr_eq(&staged.owner, &self.token),
                        "{name}: the body was staged by another archive"
                    );
                    RowEntry {
                        group,
                        name,
                        slot: Some(staged.at),
                    }
                }
                HotOp::Link { group, name, to } => {
                    self.check_ref(&to, w.blob_end)?;
                    RowEntry {
                        group,
                        name,
                        slot: Some(to),
                    }
                }
                HotOp::End { group, name } => RowEntry {
                    group,
                    name,
                    slot: None,
                },
            };
            e.group.check()?;
            entries.push(e);
        }
        let (rows_added, journal_bytes_added) = self.write_journal(w, &entries)?;
        let rows_replaced = self.publish(entries);
        Ok(HotCommitReport {
            rows_added,
            rows_replaced,
            journal_bytes_added,
        })
    }

    fn check_ref(&self, to: &BlobRef, blob_end: u64) -> Result<()> {
        ensure!(!to.chunks.is_empty(), "a link names no bytes");
        match to.pack {
            None => ensure!(
                to.end() <= blob_end,
                "a link names bytes up to {} past the blob end {blob_end}",
                to.end()
            ),
            Some(p) => {
                let Some(l) = self.layer else {
                    bail!("a plain archive names no other file's bytes");
                };
                ensure!(
                    p < l.generation,
                    "layer {} cannot name bytes of generation {p}",
                    l.generation
                );
            }
        }
        Ok(())
    }

    /// Stage `body` and name it `name` in `group` — two fsyncs, as an append.
    pub fn append_from(
        &self,
        group: &Group,
        name: &str,
        body: &mut dyn Read,
        expect: &Expect,
    ) -> Result<Staged> {
        let staged = self.stage_from(name, body, expect)?;
        self.commit(vec![HotOp::Put {
            group: group.clone(),
            name: name.to_string(),
            staged: staged.clone(),
        }])?;
        Ok(staged)
    }

    /// Name the bytes of `from_name` (in `from_group`) also `name` in `group`. No
    /// byte is written.
    pub fn link(
        &self,
        group: &Group,
        name: &str,
        from_group: &Group,
        from_name: &str,
    ) -> Result<()> {
        let Lookup::Live(to) = self.lookup(from_group, from_name) else {
            bail!("{from_name}: no live name to link to");
        };
        self.commit(vec![HotOp::Link {
            group: group.clone(),
            name: name.to_string(),
            to,
        }])?;
        Ok(())
    }

    /// Hide `name` in `group`.
    pub fn end(&self, group: &Group, name: &str) -> Result<()> {
        self.commit(vec![HotOp::End {
            group: group.clone(),
            name: name.to_string(),
        }])?;
        Ok(())
    }

    /// One message on the journal, fsynced. A V1 segment that cannot carry the
    /// rows gives way to a new V2 segment first.
    fn write_journal(&self, w: &mut HotWriter, entries: &[RowEntry]) -> Result<(u64, u64)> {
        if !w.journal.v2 && !fits_v1(entries) {
            self.new_segment(w, true)?;
        }
        let batch = rows_batch(&w.journal.schema, entries)?;
        let wrote = (|| -> Result<u64> {
            w.journal
                .w
                .write(&batch)
                .map_err(|e| anyhow!("hot: journal write: {e}"))?;
            w.journal
                .w
                .flush()
                .map_err(|e| anyhow!("hot: journal flush: {e}"))?;
            w.journal
                .w
                .get_ref()
                .sync_all()
                .map_err(|e| anyhow!("hot: journal fsync: {e}"))?;
            Ok(w.journal.w.get_ref().metadata()?.len())
        })();
        let len = match wrote {
            Ok(len) => len,
            Err(e) => {
                // A message cut in the middle would hide every later one from a
                // reader: the next message goes to a fresh segment.
                let v2 = w.journal.v2;
                let _ = self.new_segment(w, v2);
                return Err(e);
            }
        };
        self.fsyncs.fetch_add(1, Ordering::Relaxed);
        let added = len - w.journal.len;
        w.journal.len = len;
        Ok((batch.num_rows() as u64, added))
    }

    /// **A new journal segment of this writer's own**, numbered above every segment of
    /// the file: another writer's may lie above its own ([`catch_up`](Self::catch_up)).
    fn new_segment(&self, w: &mut HotWriter, v2: bool) -> Result<()> {
        let top = journal_segments(&self.archive)?.last().map(|(n, _)| *n);
        let number = top.map_or(0, |n| n + 1).max(w.journal.number + 1);
        w.journal = Journal::create(&self.archive, number, v2, self.layer.as_ref())?;
        self.others().mine.insert(number);
        Ok(())
    }

    fn others(&self) -> std::sync::MutexGuard<'_, Others> {
        self.others.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Rows the open read from the journal.
    pub(crate) fn rows_at_open(&self) -> u64 {
        self.others().at_open
    }

    /// **The rows other writers of this file committed since this writer last looked**
    /// (a stack's writers in turns, [`crate::StackWriter::catch_up`]), read while the
    /// caller's lock lets this writer alone write: each segment not its own is read
    /// from where it was left, in the segments' order, into the index, and the blob
    /// cursor moves past every byte the rows read name (it never moves back). When a
    /// row came from a segment numbered above its own, its next commit goes into a new
    /// segment numbered above every one there, so that a replay applies it after them.
    /// The rows read, and whether a segment was made.
    pub(crate) fn catch_up(&self) -> Result<(u64, bool)> {
        let mut w = self.writer.lock().unwrap_or_else(|e| e.into_inner());
        let segments = journal_segments(&self.archive)?;
        let mut fresh = Vec::new();
        let mut above = false;
        {
            let mut others = self.others();
            let Others { cursors, mine, .. } = &mut *others;
            for (n, path) in &segments {
                if mine.contains(n) {
                    continue;
                }
                let cursor =
                    (cursors.entry(*n)).or_insert_with(|| SegmentCursor::new(*n, path.clone()));
                let (entries, _) = cursor.read_more(true)?;
                above |= !entries.is_empty() && *n > w.journal.number;
                fresh.extend(entries);
            }
        }
        let rows = fresh.len() as u64;
        let end = fresh.iter().map(own_bytes_end).max().unwrap_or(0);
        if end > w.blob_end {
            w.blob_end = end;
            self.blob_end.store(end, Ordering::Release);
        }
        if !fresh.is_empty() {
            let mut idx = self.index.write().unwrap_or_else(|e| e.into_inner());
            for e in fresh {
                idx.apply(e);
            }
        }
        if above {
            let v2 = w.journal.v2;
            self.new_segment(&mut w, v2)?;
        }
        Ok((rows, above))
    }

    /// The index swap: the ONLY part a reader is excluded from. Both halves are
    /// on disk already. The names that were live and are now replaced or ended.
    fn publish(&self, entries: Vec<RowEntry>) -> u64 {
        let mut idx = self.index.write().unwrap_or_else(|e| e.into_inner());
        (entries.into_iter())
            .filter(|e| idx.set(e.group.clone(), e.name.clone(), e.slot.clone()) == Was::Live)
            .count() as u64
    }

    /// Freeze the hot archive into a static `.znippy` and drop the journal.
    ///
    /// The blobs are already in place and are not touched: the seal writes the
    /// metadata tail only — one data sub-index per group, live rows in the order
    /// they first came. `reserved` is the same hook
    /// [`ArrowIpcSink::with_reserved_builder`](crate::ArrowIpcSink::with_reserved_builder)
    /// offers, so a caller with its own sections (gunnar's `__gunnar_refs__`)
    /// seals them here rather than needing a second seal.
    pub fn seal(self, reserved: Option<ReservedSectionBuilder>) -> Result<HotSealReport> {
        self.seal_with(reserved, true)
    }

    /// The seal, keeping the journal when `remove_journal` is false (a stack
    /// renames the sealed layer into place first, then drops the journal).
    pub(crate) fn seal_with(
        self,
        reserved: Option<ReservedSectionBuilder>,
        remove_journal: bool,
    ) -> Result<HotSealReport> {
        let Self {
            archive,
            blobs,
            index,
            writer,
            layer,
            ..
        } = self;
        let index = index.into_inner().unwrap_or_else(|e| e.into_inner());
        let HotWriter {
            blob_end, journal, ..
        } = writer.into_inner().unwrap_or_else(|e| e.into_inner());
        drop(journal);

        let mut sink = ArrowIpcSink::new(Arc::clone(&blobs), blob_end);
        let mut rows_sealed = 0u64;
        let mut links: Vec<RowEntry> = Vec::new();
        let mut groups: Vec<SectionRows> = Vec::new();
        for g in index.groups() {
            let mut rows = SectionRows::new(g.clone());
            for (name, slot) in index.slots(g) {
                match slot {
                    Some(b) if b.pack.is_none() => {
                        rows_sealed += 1;
                        rows.push(name, b);
                    }
                    Some(_) => links.push(RowEntry {
                        group: g.clone(),
                        name: name.to_string(),
                        slot: slot.clone(),
                    }),
                    None if layer.is_some() => links.push(RowEntry {
                        group: g.clone(),
                        name: name.to_string(),
                        slot: None,
                    }),
                    None => {}
                }
            }
            if !rows.is_empty() {
                groups.push(rows);
            }
        }
        let mut mine: Vec<ReservedSection> = Vec::new();
        if let Some(l) = layer {
            if !links.is_empty() {
                let schema = rows_schema(&HashMap::new());
                let batch = rows_batch(&schema, &links)?;
                mine.push(ReservedSection::arrow(
                    ZNIPPY_LINKS_MODULE,
                    schema,
                    vec![batch],
                ));
            }
            mine.push(ReservedSection::raw(
                ZNIPPY_STACK_MODULE,
                StackSection::layer(l).encode(),
            ));
        }
        if let Some(b) = compose_reserved(reserved, mine) {
            sink = sink.with_reserved_builder(b);
        }
        for rows in &groups {
            rows.push_to(&mut sink)?;
        }
        let sealed_total_bytes = Box::new(sink).finish()?;
        // A cut stage may have left bytes past the tail: the footer must end the file.
        if blobs.metadata()?.len() > sealed_total_bytes {
            blobs.set_len(sealed_total_bytes)?;
            blobs.sync_all()?;
        }

        // The static archive is durable; only now is the journal redundant.
        let mut segments_removed = 0usize;
        let mut journal_bytes_reclaimed = 0u64;
        if remove_journal {
            let segments = journal_segments(&archive)?;
            for (_, seg) in &segments {
                journal_bytes_reclaimed += std::fs::metadata(seg).map(|m| m.len()).unwrap_or(0);
                std::fs::remove_file(seg)
                    .map_err(|e| anyhow!("hot: removing journal {}: {e}", seg.display()))?;
            }
            segments_removed = segments.len();
            sync_dir_of(&archive);
        }
        Ok(HotSealReport {
            archive,
            rows_sealed,
            segments_removed,
            journal_bytes_reclaimed,
            sealed_total_bytes,
        })
    }
}

/// The caller's reserved sections, then the archive's own. The caller may not
/// write the archive's own.
pub(crate) fn compose_reserved(
    reserved: Option<ReservedSectionBuilder>,
    mine: Vec<ReservedSection>,
) -> Option<ReservedSectionBuilder> {
    if reserved.is_none() && mine.is_empty() {
        return None;
    }
    Some(Box::new(move |view: &crate::meta_sink::LookupView<'_>| {
        let mut out = match reserved {
            Some(b) => b(view)?,
            None => Vec::new(),
        };
        for s in &out {
            ensure!(
                s.module_name != ZNIPPY_STACK_MODULE && s.module_name != ZNIPPY_LINKS_MODULE,
                "{} is written by the archive itself",
                s.module_name
            );
        }
        out.extend(mine);
        Ok(out)
    }))
}

/// Flat rows (one per chunk) as names, in the order each name first came.
fn entries_by_name(
    group: Group,
    paths: Vec<String>,
    locs: Vec<ChunkLoc>,
    bodies: Vec<Option<[u8; 32]>>,
) -> Vec<RowEntry> {
    let mut at: HashMap<String, usize> = HashMap::with_capacity(paths.len());
    let mut out: Vec<RowEntry> = Vec::new();
    for ((name, loc), body) in paths.into_iter().zip(locs).zip(bodies) {
        match at.get(&name) {
            Some(&i) => {
                let b = out[i].slot.as_mut().expect("built live");
                b.chunks.retain(|c| c.fdata_offset != loc.fdata_offset);
                b.chunks.push(loc);
                b.body_checksum = body.or(b.body_checksum);
            }
            None => {
                at.insert(name.clone(), out.len());
                out.push(RowEntry {
                    group: group.clone(),
                    name,
                    slot: Some(BlobRef {
                        pack: None,
                        chunks: vec![loc],
                        body_checksum: body,
                    }),
                });
            }
        }
    }
    for e in &mut out {
        if let Some(b) = &mut e.slot {
            b.chunks.sort_by_key(|c| c.fdata_offset);
            b.keep_body_checksum_only_when_needed();
            for (i, c) in b.chunks.iter_mut().enumerate() {
                // A sealed archive's chunk_seq is already 0..n; a row recovered
                // twice keeps the last copy, so the sequence is renumbered to
                // what the journal codec needs.
                c.chunk_seq = u32::try_from(i).unwrap_or(u32::MAX);
            }
        }
    }
    out
}

/// The hot archive reads without being sealed — the default group, through the
/// same trait the static [`ZnippyArchive`](crate::ZnippyArchive) implements, so a
/// caller does not branch on phase.
///
/// Every one of these takes the index's SHARED guard, and none of them holds it
/// across I/O: the row is copied out and the `pread` runs with the guard already
/// released. So the index lock is held for a hash lookup and nothing else, on the
/// read side as on the write side.
impl ZnippyReader for HotArchive {
    fn list_files(&self) -> Result<Vec<String>> {
        Ok(self.names(&Group::default()))
    }

    fn contains(&self, relative_path: &str) -> bool {
        matches!(
            self.lookup(&Group::default(), relative_path),
            Lookup::Live(_)
        )
    }

    fn file_size(&self, relative_path: &str) -> Option<u64> {
        match self.lookup(&Group::default(), relative_path) {
            Lookup::Live(b) => Some(b.size()),
            _ => None,
        }
    }

    fn extract_file(&self, relative_path: &str) -> Result<Vec<u8>> {
        (self.get(&Group::default(), relative_path))
            .ok_or_else(|| anyhow!("file not found in archive: {relative_path}"))?
            .read()
    }

    fn checksum(&self, relative_path: &str) -> Option<[u8; 32]> {
        match self.lookup(&Group::default(), relative_path) {
            Lookup::Live(b) => b.checksum(),
            _ => None,
        }
    }
}

pub(crate) fn segment_path(archive: &Path, n: u32) -> PathBuf {
    let mut s = archive.as_os_str().to_os_string();
    s.push(format!("{JOURNAL_INFIX}{n:05}"));
    PathBuf::from(s)
}

/// Every journal segment for `archive`, sorted by sequence number.
pub(crate) fn journal_segments(archive: &Path) -> Result<Vec<(u32, PathBuf)>> {
    let dir = archive.parent().filter(|p| !p.as_os_str().is_empty());
    let dir = dir
        .map(|d| d.to_path_buf())
        .unwrap_or_else(|| PathBuf::from("."));
    let stem = archive
        .file_name()
        .and_then(|n| n.to_str())
        .ok_or_else(|| anyhow!("hot: {} has no usable file name", archive.display()))?;
    let prefix = format!("{stem}{JOURNAL_INFIX}");
    let mut out = Vec::new();
    let rd = match std::fs::read_dir(&dir) {
        Ok(rd) => rd,
        Err(_) => return Ok(out),
    };
    for e in rd.flatten() {
        let name = e.file_name();
        let Some(name) = name.to_str() else { continue };
        let Some(tail) = name.strip_prefix(&prefix) else {
            continue;
        };
        let Ok(n) = tail.parse::<u32>() else { continue };
        out.push((n, e.path()));
    }
    out.sort_by_key(|(n, _)| *n);
    Ok(out)
}

/// Buffer alignment for the journal, in bytes.
///
/// **8, not arrow-rs's default 64.** The 64 is arrow-rs's choice, not Arrow's —
/// arrow-cpp and pyarrow have always written 8 — so this is what the C++
/// reference implementation does and not a bent format. It matters here and
/// almost nowhere else, because a journal batch is *small*: the base schema has
/// eight columns and a two-row batch therefore carries a dozen-plus buffers that
/// are each rounded up. MEASURED on oden, 2026-08-04, two rows per append
/// (a `pack-*.pack` and its `.idx`, 40-hex names): **1 664 B/append at 64-byte
/// alignment, 824 B at 8** — 2.02×, for byte-identical rows. Flat at 824 B all
/// the way to 32 000 appends, so it is a per-append constant and not a curve.
///
/// The **sealed** archive is untouched by this: it is written by `ArrowIpcSink`
/// with arrow-rs's default, so every `.znippy` on disk keeps the bytes its
/// readers already expect. This is the transient half only.
const JOURNAL_ALIGNMENT: usize = 8;

/// `HotArchive::seal` as a free function, for a caller that has a path and not a
/// handle. Refuses an archive with no journal rather than silently producing an
/// empty one.
pub fn seal_hot(archive: &Path, level: i32, policy: crate::SkipPolicy) -> Result<HotSealReport> {
    if !HotArchive::is_hot(archive) {
        bail!("{} has no journal; it is not hot", archive.display());
    }
    HotArchive::open(archive, level, policy)?.seal(None)
}

// ── tests ────────────────────────────────────────────────────────────────────
// Every test here seals a real archive through a `CompressCtx`, so all of them
// need the codec — the same gate `meta_sink_append::tests` carries.
#[cfg(all(test, feature = "openzl"))]
mod tests {
    use super::*;
    use crate::{create_archive, ZnippyArchive};
    use std::time::{SystemTime, UNIX_EPOCH};

    fn unique_dir(tag: &str) -> PathBuf {
        let ns = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let d = std::env::temp_dir().join(format!(
            "znippy_hot_{tag}_{ns}_{:?}",
            std::thread::current().id()
        ));
        std::fs::create_dir_all(&d).unwrap();
        d
    }

    /// Deterministic, lexicographically spread, and *compressible* — so the codec
    /// really runs and a byte-identity claim is about compressed output, not about
    /// two stored-raw copies of the same input.
    fn synth(n: usize, salt: u64) -> Vec<(String, Vec<u8>)> {
        (0..n)
            .map(|i| {
                let g = (i.wrapping_mul(2_654_435_761) ^ salt as usize) % 997;
                let p = format!("repo/grp{g:03}/file{i:08}_{salt}.bin");
                let body = format!("payload {i} salt {salt} {}\n", "z".repeat(8 + (i % 40)));
                (p, body.into_bytes())
            })
            .collect()
    }

    /// **The correctness claim the whole module rests on.** Appending N files one
    /// at a time through the hot journal and then sealing must produce the SAME
    /// BYTES as creating the archive from all N at once — same blob offsets, same
    /// data sub-index, same sorted lookup, same fst trie, same manifest, same
    /// footer.
    ///
    /// This is an applied-output assertion, not a round trip: a seal that dropped
    /// the trie, or emitted rows in journal-segment order instead of insertion
    /// order, would still list N files and still read every one of them back
    /// correctly. Only the bytes catch it.
    ///
    /// Seen RED by emitting the rows sorted instead of in insertion order in
    /// `HotArchive::seal` — the data sub-index differs and the assertion fires
    /// with a first-difference offset inside it.
    #[test]
    fn seal_matches_create_archive_byte_for_byte() {
        let dir = unique_dir("identity");
        let files = synth(400, 11);

        let reference = dir.join("ref.znippy");
        create_archive(&reference, &files, 3).unwrap();

        let hot = dir.join("hot.znippy");
        {
            let h = HotArchive::open(&hot, 3, crate::SkipPolicy::resolve()).unwrap();
            for f in &files {
                h.append(std::slice::from_ref(f)).unwrap();
            }
            let report = h.seal(None).unwrap();
            assert_eq!(report.rows_sealed, files.len() as u64);
            assert_eq!(report.segments_removed, 1, "one process, one segment");
        }

        let a = std::fs::read(&reference).unwrap();
        let b = std::fs::read(&hot).unwrap();
        assert_eq!(
            a.len(),
            b.len(),
            "sealed length differs: create_archive {} vs hot-then-seal {}",
            a.len(),
            b.len()
        );
        let first_diff = a.iter().zip(&b).position(|(x, y)| x != y);
        assert!(
            first_diff.is_none(),
            "hot-then-seal is NOT byte-identical to create_archive; first difference at byte {:?}",
            first_diff
        );

        // …and the journal is gone, so the archive is genuinely cold.
        assert!(!HotArchive::is_hot(&hot), "seal must remove the journal");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The hot archive is READABLE before it is sealed — otherwise a two-phase
    /// tier would be write-only until compaction, which is not "worth having".
    #[test]
    fn a_hot_archive_serves_reads_before_the_seal() {
        let dir = unique_dir("read");
        let path = dir.join("a.znippy");
        let files = synth(120, 3);
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        for f in &files {
            h.append(std::slice::from_ref(f)).unwrap();
        }
        for (p, bytes) in &files {
            assert!(h.contains(p), "hot archive must contain {p}");
            assert_eq!(h.file_size(p), Some(bytes.len() as u64));
            assert_eq!(
                &h.extract_file(p).unwrap(),
                bytes,
                "hot read mismatch for {p}"
            );
        }
        assert_eq!(h.list_files().unwrap().len(), files.len());

        // And after the seal the ORDINARY static reader answers the same bytes.
        h.seal(None).unwrap();
        let ar = ZnippyArchive::open(&path).unwrap();
        for (p, bytes) in &files {
            assert_eq!(
                &ar.extract_file(p).unwrap(),
                bytes,
                "sealed read mismatch for {p}"
            );
        }
        // Random access through the rebuilt trie+lookup.
        assert!(!crate::locate_file(&path, &files[77].0).unwrap().is_empty());
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A restart must not lose the journal, and must not corrupt the blob cursor.
    /// Three processes' worth of appends (three segments), then one seal.
    #[test]
    fn reopening_recovers_every_segment() {
        let dir = unique_dir("reopen");
        let path = dir.join("a.znippy");
        let mut all: Vec<(String, Vec<u8>)> = Vec::new();
        for round in 0..3u64 {
            let files = synth(40, round + 1);
            let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
            assert_eq!(h.rows(), all.len() as u64, "reopen must recover prior rows");
            for f in &files {
                h.append(std::slice::from_ref(f)).unwrap();
            }
            all.extend(files);
        }
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        assert_eq!(h.rows(), all.len() as u64);
        let report = h.seal(None).unwrap();
        assert_eq!(
            report.segments_removed, 4,
            "three appending opens + the final one"
        );

        let ar = ZnippyArchive::open(&path).unwrap();
        for (p, bytes) in &all {
            assert_eq!(
                &ar.extract_file(p).unwrap(),
                bytes,
                "byte mismatch after restarts for {p}"
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A SEALED archive goes hot again without losing anything: the static rows
    /// are recovered into segment 0 and the rebuildable tail is dropped. This is
    /// the path gunnar's cold tier takes after a `repack()` fold.
    #[test]
    fn a_sealed_archive_reheats_and_keeps_its_rows() {
        let dir = unique_dir("reheat");
        let path = dir.join("a.znippy");
        let sealed = synth(60, 5);
        create_archive(&path, &sealed, 3).unwrap();
        let cold_len = std::fs::metadata(&path).unwrap().len();

        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        assert_eq!(
            h.rows(),
            sealed.len() as u64,
            "re-heat must recover the sealed rows"
        );
        assert!(
            h.blob_end() < cold_len,
            "the metadata tail must be dropped: blob_end {} vs sealed length {cold_len}",
            h.blob_end()
        );
        let extra = synth(20, 6);
        for f in &extra {
            h.append(std::slice::from_ref(f)).unwrap();
        }
        h.seal(None).unwrap();

        let ar = ZnippyArchive::open(&path).unwrap();
        for (p, bytes) in sealed.iter().chain(extra.iter()) {
            assert_eq!(
                &ar.extract_file(p).unwrap(),
                bytes,
                "byte mismatch after re-heat for {p}"
            );
        }
        let mut listed = ar.list_files().unwrap();
        listed.sort();
        let mut want: Vec<String> = sealed
            .iter()
            .chain(extra.iter())
            .map(|(p, _)| p.clone())
            .collect();
        want.sort();
        assert_eq!(listed, want);
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// Last writer wins, exactly as `append_files` does — one live row per path,
    /// and the bytes read back are the NEW ones. The old blob stays in the file as
    /// dead payload, which is the documented cost, so the assertion is on the row
    /// count and the bytes, not on the file size.
    #[test]
    fn re_appending_a_path_replaces_it() {
        let dir = unique_dir("replace");
        let path = dir.join("a.znippy");
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        h.append(&[("x.bin".into(), b"first version".to_vec())])
            .unwrap();
        h.append(&[("y.bin".into(), b"other".to_vec())]).unwrap();
        let r = h
            .append(&[("x.bin".into(), b"SECOND version, longer".to_vec())])
            .unwrap();
        assert_eq!(
            r.rows_replaced, 1,
            "re-appending x.bin must replace, not duplicate"
        );
        assert_eq!(h.rows(), 2);
        assert_eq!(h.extract_file("x.bin").unwrap(), b"SECOND version, longer");
        h.seal(None).unwrap();

        let ar = ZnippyArchive::open(&path).unwrap();
        assert_eq!(
            ar.list_files().unwrap().len(),
            2,
            "the seal must carry ONE row per path"
        );
        assert_eq!(ar.extract_file("x.bin").unwrap(), b"SECOND version, longer");
        assert_eq!(ar.extract_file("y.bin").unwrap(), b"other");
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// A killed process leaves a partial final message. Everything before it is
    /// real and must survive; the partial one must be dropped rather than failing
    /// the open. Simulated by truncating the segment inside its last message.
    #[test]
    fn a_torn_journal_tail_is_dropped_not_fatal() {
        let dir = unique_dir("torn");
        let path = dir.join("a.znippy");
        let files = synth(30, 2);
        {
            let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
            for f in &files {
                h.append(std::slice::from_ref(f)).unwrap();
            }
        }
        let seg = segment_path(&path, 0);
        let len = std::fs::metadata(&seg).unwrap().len();
        // Cut 40 bytes: inside the last batch message, past many complete ones.
        std::fs::OpenOptions::new()
            .write(true)
            .open(&seg)
            .unwrap()
            .set_len(len - 40)
            .unwrap();

        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        let rows = h.rows();
        assert!(
            rows > 0 && rows < files.len() as u64,
            "a torn tail must cost SOME rows and not all of them; got {rows} of {}",
            files.len()
        );
        // Every surviving row still reads back byte-exact.
        for p in h.list_files().unwrap() {
            let want = &files.iter().find(|(q, _)| *q == p).unwrap().1;
            assert_eq!(
                &h.extract_file(&p).unwrap(),
                want,
                "torn-journal read mismatch for {p}"
            );
        }
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// **The O(1) claim, as an applied output.** The index-side cost of an append
    /// is the journal bytes it writes. If that is flat across a 100× growth in
    /// archive size, the append is not paying for the archive; if the old
    /// re-sealing path were behind this API the number would grow with N.
    ///
    /// Bytes, not CPU: instructions and wall clock are unusable as absolutes on a
    /// contended box, and a byte count is exact.
    #[test]
    fn the_index_cost_of_an_append_does_not_grow_with_the_archive() {
        let dir = unique_dir("flat");
        let path = dir.join("a.znippy");
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        let mut early = 0u64;
        let mut late = 0u64;
        for i in 0..2_000usize {
            // Constant-shape rows so the comparison is about N, not about payload.
            let f = vec![(format!("pack-{i:040x}.pack"), vec![b'q'; 64])];
            let r = h.append(&f).unwrap();
            if i == 10 {
                early = r.journal_bytes_added;
            }
            if i == 1_999 {
                late = r.journal_bytes_added;
            }
        }
        assert!(
            early > 0,
            "an append must cost SOME journal bytes; the probe read 0"
        );
        assert_eq!(
            early, late,
            "the index cost of an append grew from {early} B at row 10 to {late} B at row 2000 — \
             the append is paying for the archive again"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// `HotArchive` is shared across threads by every real caller (holger holds
    /// exactly one per writable repo and serves every request off it), so the
    /// auto traits are part of the contract, not an accident of the fields.
    #[test]
    fn hot_archive_is_send_and_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<HotArchive>();
    }

    /// **The property this module's locking exists for: a reader on a region the
    /// append is not touching does not wait for the append.**
    ///
    /// Before this shape `append` took `&mut self`, so a shared archive lived
    /// behind an `RwLock` and an append took the EXCLUSIVE guard for its whole
    /// body — compression, the blob write, `sync_all`, the journal batch, the
    /// journal `sync_all`. Every reader of that archive stopped for all of it.
    /// MEASURED downstream (holger `.nornir/stinky/12-dataplane-finished.md`
    /// §5.4): 32 readers against 4 publishers kept **2.2–3.0 %** of their
    /// throughput.
    ///
    /// The test puts the read INSIDE the append, by order, with no clock: the
    /// append, once it took its write position (the writers' lock held, the
    /// blob cursor read), tells the reader so and waits ([`HotArchive::at_position`]);
    /// the reader reads a row that was in the archive before the append started —
    /// so the append cannot be writing its bytes, by construction, since an append
    /// only ever writes PAST the blob cursor — and says on a channel that it read;
    /// only then does the append go on. Under the old shape the read waits for
    /// the append and the append for the read: the test hangs, and its end names
    /// it (libtest: "has been running for over 60 seconds").
    #[test]
    fn a_reader_on_an_untouched_region_proceeds_during_an_append() {
        use std::sync::mpsc::channel;

        let dir = unique_dir("reader_during_append");
        let path = dir.join("a.znippy");

        // A row that exists BEFORE the append, at a blob offset the append
        // cannot reach.
        let cold: Vec<(String, Vec<u8>)> = synth(64, 7);
        let probe = cold[0].0.clone();
        let probe_body = cold[0].1.clone();

        let h = Arc::new(HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap());
        h.append(&cold).unwrap();

        let (positioned, at_position) = channel::<()>();
        let (read, has_read) = channel::<()>();
        h.at_position(move || {
            positioned.send(()).unwrap();
            has_read
                .recv()
                .expect("the reader reads the untouched row while the append holds");
        });
        let reader = {
            let (h, probe) = (Arc::clone(&h), probe.clone());
            std::thread::spawn(move || {
                at_position
                    .recv()
                    .expect("the append takes its write position");
                let body = h.extract_file(&probe);
                read.send(()).unwrap();
                body
            })
        };

        // ONE append, of a body the codec has real work on. None of it is a
        // reason for the reader to stop.
        let mut body = vec![0u8; 1024 * 1024];
        let mut s: u64 = 0x2545_F491_4F6C_DD1D;
        for b in body.iter_mut() {
            s = s
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            *b = (s >> 33) as u8;
        }
        let report = h.append(&[("hot/big.bin".to_string(), body)]).unwrap();

        let during = reader.join().unwrap();
        assert_eq!(
            during.unwrap(),
            probe_body,
            "the reader read the untouched row, whole, while the append held its position"
        );
        assert_eq!(report.rows_added, 1);
        assert!(
            report.blob_append_offset >= 1,
            "the append must start past the cold rows, not on top of them"
        );

        // And the archive is correct afterwards: the cold row and the new one.
        assert_eq!(h.extract_file(&probe).unwrap(), probe_body);
        assert_eq!(h.extract_file("hot/big.bin").unwrap().len(), 1024 * 1024);
        assert_eq!(h.rows(), 65);

        let _ = std::fs::remove_dir_all(&dir);
    }

    /// The COUNTED half of the same claim: an append costs exactly two `fsync`s
    /// — the blob region, then the journal message that names it — whatever it
    /// is appending, and an empty append costs none.
    ///
    /// Per-archive, not process-wide, so the count is EXACT and this test cannot
    /// be made to pass or fail by whatever else the test binary is doing on
    /// another thread. It is what makes "fsyncs per append" a number rather than
    /// an argument downstream.
    #[test]
    fn an_append_pays_exactly_two_fsyncs_and_an_empty_one_pays_none() {
        let dir = unique_dir("fsync_count");
        let path = dir.join("a.znippy");
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        assert_eq!(
            h.fsyncs(),
            0,
            "a freshly opened archive has appended nothing"
        );

        for f in synth(8, 11) {
            h.append(std::slice::from_ref(&f)).unwrap();
        }
        assert_eq!(
            h.fsyncs(),
            16,
            "8 one-at-a-time appends are 8 x (blob, journal)"
        );

        h.append(&[]).unwrap();
        assert_eq!(h.fsyncs(), 16, "an empty append must not touch the disk");

        // Batched: 8 files in ONE call is still two fsyncs. That is the whole
        // reason holger group-commits N publishes into one append — N entries
        // cost two fsyncs, not 2N.
        h.append(&synth(8, 12)).unwrap();
        assert_eq!(
            h.fsyncs(),
            18,
            "8 files in one append are two fsyncs, not sixteen"
        );
        assert_eq!(h.rows(), 16);

        let _ = std::fs::remove_dir_all(&dir);
    }
}

// ── groups, bodies from a reader, shared blobs, ends, cuts ──────────────────
#[cfg(all(test, feature = "openzl"))]
pub(crate) mod stream_tests {
    use super::*;
    use crate::index::{read_znippy_index_filtered, IndexFilter};
    use crate::{create_archive, HotView, ZnippyArchive};
    use std::io::Cursor;

    /// Pseudo-random bytes (incompressible), produced as they are read.
    pub(crate) struct Noise {
        pub s: u64,
        pub left: u64,
    }

    impl Read for Noise {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let n = usize::try_from(self.left).map_or(buf.len(), |l| l.min(buf.len()));
            for b in &mut buf[..n] {
                self.s = self
                    .s
                    .wrapping_mul(6_364_136_223_846_793_005)
                    .wrapping_add(1_442_695_040_888_963_407);
                *b = (self.s >> 33) as u8;
            }
            self.left -= n as u64;
            Ok(n)
        }
    }

    /// Compressible text, produced as it is read.
    pub(crate) struct Text {
        pub at: u64,
        pub left: u64,
    }

    impl Read for Text {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let n = usize::try_from(self.left).map_or(buf.len(), |l| l.min(buf.len()));
            for b in &mut buf[..n] {
                let line = self.at / 64;
                let col = self.at % 64;
                *b = if col == 63 {
                    b'\n'
                } else {
                    b"line of text number "[(col % 20) as usize] ^ ((line % 3) as u8)
                };
                self.at += 1;
            }
            self.left -= n as u64;
            Ok(n)
        }
    }

    pub(crate) fn noise(seed: u64, n: u64) -> Vec<u8> {
        let mut v = Vec::new();
        Noise { s: seed, left: n }.read_to_end(&mut v).unwrap();
        v
    }

    pub(crate) fn text(n: u64) -> Vec<u8> {
        let mut v = Vec::new();
        Text { at: 0, left: n }.read_to_end(&mut v).unwrap();
        v
    }

    fn raw() -> crate::SkipPolicy {
        crate::SkipPolicy::already_compressed()
    }

    fn seg_batches(path: &Path) -> usize {
        let bytes = std::fs::read(path).unwrap();
        let whole = crate::ipc_guard::valid_prefix(&bytes);
        arrow::ipc::reader::StreamReader::try_new(Cursor::new(whole), None)
            .unwrap()
            .count()
    }

    /// While the body is being read, no row names it and the journal has not
    /// grown; after the last byte, ONE row names it, and it reads back whole.
    #[test]
    fn append_from_a_reader_writes_one_row_after_the_last_byte() {
        struct Probe<'a> {
            h: &'a HotArchive,
            seg: PathBuf,
            body: Noise,
            seen: Vec<(u64, u64)>,
        }
        impl Read for Probe<'_> {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                self.seen
                    .push((self.h.rows(), std::fs::metadata(&self.seg).unwrap().len()));
                self.body.read(buf)
            }
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        let seg = segment_path(&path, 0);
        let journal_before = std::fs::metadata(&seg).unwrap().len();
        let size = 10 * (1 << 20) + 7;
        let mut probe = Probe {
            h: &h,
            seg: seg.clone(),
            body: Noise { s: 1, left: size },
            seen: Vec::new(),
        };
        let staged = h
            .append_from(&Group::default(), "big.bin", &mut probe, &Expect::default())
            .unwrap();
        assert!(probe.seen.len() >= 3, "a 10 MiB body is read in pieces");
        assert!(
            probe
                .seen
                .iter()
                .all(|&(rows, j)| rows == 0 && j == journal_before),
            "a row or a journal message appeared before the last byte: {:?}",
            probe.seen
        );
        let want = noise(1, size);
        assert_eq!(staged.size(), size);
        assert_eq!(staged.blake3(), *blake3::hash(&want).as_bytes());
        assert_eq!(staged.location().chunks.len(), 1, "a raw body is one chunk");
        assert_eq!(h.rows(), 1);
        assert_eq!(seg_batches(&seg), 1, "one journal message");
        assert_eq!(h.fsyncs(), 2, "the body, then the row");
        assert_eq!(h.extract_file("big.bin").unwrap(), want);
        h.seal(None).unwrap();
        let ar = ZnippyArchive::open(&path).unwrap();
        assert_eq!(ar.extract_file_verified("big.bin").unwrap(), want);
    }

    /// A compressible body is compressed a piece at a time: one chunk per
    /// `STREAM_PIECE`, each smaller than its piece, and it reads back whole —
    /// hot, through a view, and sealed.
    #[test]
    fn a_compressible_stream_is_stored_in_compressed_pieces() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        let size = 2 * STREAM_PIECE as u64 + 1000;
        let staged = h
            .append_from(
                &Group::default(),
                "data.txt",
                &mut Text { at: 0, left: size },
                &Expect::default(),
            )
            .unwrap();
        let want = text(size);
        let at = staged.location();
        assert_eq!(at.chunks.len(), 3);
        assert!(at.chunks[..2].iter().all(|c| c.compressed), "{at:?}");
        assert!(
            at.stored_bytes() < size / 4,
            "stored {} of {size}",
            at.stored_bytes()
        );
        assert_eq!(staged.blake3(), *blake3::hash(&want).as_bytes());
        assert_eq!(
            at.checksum(),
            Some(staged.blake3()),
            "a body in pieces carries the digest of the whole beside its pieces'"
        );
        assert_eq!(
            h.get(&Group::default(), "data.txt")
                .unwrap()
                .read_verified()
                .unwrap(),
            want
        );
        let v = HotView::open(&path).unwrap();
        assert_eq!(v.extract_file("data.txt").unwrap(), want);
        h.seal(None).unwrap();
        let ar = ZnippyArchive::open(&path).unwrap();
        assert_eq!(ar.extract_file_verified("data.txt").unwrap(), want);
    }

    /// **A body laid as one chunk is hashed once**: its chunk's BLAKE3 is the body's, so
    /// laying it feeds each byte to BLAKE3 once, stored raw or compressed whole; a body in
    /// pieces is hashed whole once, and once more by every chunk after the first. A reader
    /// checking chunks reads the stored bytes once and hashes each body byte once.
    /// Counted on the instances.
    #[test]
    fn a_body_laid_as_one_chunk_is_hashed_once() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        let bodies = [
            ("raw.gz", noise(8, 3 << 20)),
            ("one.txt", text(1 << 20)),
            ("pieces.txt", text(2 * STREAM_PIECE as u64 + 1000)),
        ];
        let staged: Vec<Staged> = (bodies.iter())
            .map(|(name, body)| {
                (h.stage_from(name, &mut Cursor::new(body), &Expect::default())).unwrap()
            })
            .collect();
        let (raw, one, pieces) = (&staged[0], &staged[1], &staged[2]);
        assert_eq!(raw.location().chunks.len(), 1);
        assert!(!raw.location().chunks[0].compressed);
        assert_eq!(raw.written(), raw.size());
        assert_eq!(raw.hashed(), raw.size(), "a raw body in one chunk");
        assert_eq!(one.location().chunks.len(), 1);
        assert!(one.location().chunks[0].compressed);
        assert_eq!(one.written(), one.location().stored_bytes());
        assert_eq!(one.hashed(), one.size(), "a body compressed whole");
        let chunks = &pieces.location().chunks;
        assert_eq!(chunks.len(), 3);
        assert_eq!(pieces.written(), pieces.location().stored_bytes());
        assert_eq!(
            pieces.hashed(),
            2 * pieces.size() - chunks[0].uncompressed_size,
            "a body in pieces: whole once, and every chunk after the first"
        );
        for (s, (name, body)) in staged.iter().zip(&bodies) {
            assert_eq!(s.blake3(), *blake3::hash(body).as_bytes(), "{name}");
            assert_eq!(s.location().checksum(), Some(s.blake3()), "{name}");
            let blob = h.staged_body(s).unwrap();
            let mut p = blob.pieces(STREAM_PIECE, true).unwrap();
            let mut got = Vec::new();
            for piece in &mut p {
                got.extend(piece.unwrap());
            }
            assert_eq!(&got, body, "{name}");
            assert_eq!(p.read(), s.location().stored_bytes(), "{name}: read once");
            assert_eq!(p.hashed(), s.size(), "{name}: checked once");
        }
    }

    /// **A body laid in pieces has the BLAKE3 of the whole body in its row** (H40-LIST 98).
    /// A compressible body over [`STREAM_PIECE`] is compressed a piece at a time, one chunk
    /// and one checksum per piece. The digest of the whole body, computed in that same pass,
    /// is in its row: the archive that wrote it, another process's view, a reopen, the seal
    /// and the sealed archive hot again each give it from the row. Not from the bytes: the
    /// body's first chunk is overwritten before any of them is asked, and a verified read
    /// fails on it at the end.
    #[test]
    fn a_body_laid_in_pieces_has_its_whole_blake3_in_its_row() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let g = Group::default();
        let size = 2 * STREAM_PIECE as u64 + 1000;
        let want = *blake3::hash(&text(size)).as_bytes();
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        let staged = h
            .append_from(&g, "data.txt", &mut Text { at: 0, left: size }, &Expect::default())
            .unwrap();
        let at = staged.location().clone();
        assert_eq!(at.chunks.len(), 3, "laid in pieces: {at:?}");
        assert_eq!(staged.blake3(), want);
        assert_eq!(at.checksum(), Some(want), "the staged body's place");

        let c = &at.chunks[0];
        let f = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
        f.write_all_at(&vec![0u8; c.blob_size as usize], c.blob_offset).unwrap();
        drop(f);

        let Lookup::Live(row) = h.lookup(&g, "data.txt") else {
            panic!("no row for data.txt")
        };
        assert_eq!(row.checksum(), Some(want), "its row");
        assert_eq!(h.get(&g, "data.txt").unwrap().checksum(), Some(want), "its blob");
        assert_eq!(ZnippyReader::checksum(&h, "data.txt"), Some(want), "the archive");
        let v = HotView::open(&path).unwrap();
        assert_eq!(v.checksum("data.txt"), Some(want), "another process's view");
        drop(h);
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        assert_eq!(ZnippyReader::checksum(&h, "data.txt"), Some(want), "reopened");
        h.seal(None).unwrap();
        let ar = ZnippyArchive::open(&path).unwrap();
        assert_eq!(ar.checksum("data.txt"), Some(want), "sealed");
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        assert_eq!(ZnippyReader::checksum(&h, "data.txt"), Some(want), "sealed, hot again");
        assert!(
            ar.extract_file_verified("data.txt").is_err(),
            "the first chunk was overwritten: only the row can have given the digest"
        );
    }

    /// A read error mid-body: no row, the cursor does not move, the bytes written
    /// are an orphan the next open cuts. The next append starts where the cut
    /// body did.
    #[test]
    fn a_read_error_mid_body_leaves_no_row_and_the_orphan_is_cut_at_reopen() {
        struct Breaks(Noise);
        impl Read for Breaks {
            fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
                if self.0.left == 0 {
                    return Err(std::io::Error::other("the source broke"));
                }
                self.0.read(buf)
            }
        }
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        {
            let h = HotArchive::open(&path, 3, raw()).unwrap();
            h.append(&[("first".into(), b"one".to_vec())]).unwrap();
            let end = h.blob_end();
            let err = h
                .append_from(
                    &Group::default(),
                    "cut.bin",
                    &mut Breaks(Noise {
                        s: 2,
                        left: 5 << 20,
                    }),
                    &Expect::default(),
                )
                .unwrap_err();
            assert!(format!("{err:#}").contains("the source broke"), "{err:#}");
            assert_eq!(h.rows(), 1);
            assert_eq!(h.blob_end(), end, "the cursor does not move");
            assert!(
                std::fs::metadata(&path).unwrap().len() >= end + STREAM_PIECE as u64,
                "the orphan is there"
            );
            assert!(!h.contains("cut.bin"));
        }
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        assert_eq!(
            std::fs::metadata(&path).unwrap().len(),
            3,
            "the open cut the orphan"
        );
        assert_eq!(h.rows(), 1);
        let r = h.append(&[("second".into(), b"two".to_vec())]).unwrap();
        assert_eq!(r.blob_append_offset, 3);
        assert_eq!(h.extract_file("second").unwrap(), b"two");
    }

    /// **A body that waits for its reader**: one whole piece, then it says so on
    /// `told` and waits for `go` before it gives `rest`. No clock: the test lets it
    /// go.
    struct Waits {
        first: Vec<u8>,
        rest: Vec<u8>,
        told: Option<std::sync::mpsc::Sender<()>>,
        go: std::sync::mpsc::Receiver<()>,
    }

    impl Read for Waits {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            if !self.first.is_empty() {
                let n = buf.len().min(self.first.len());
                buf[..n].copy_from_slice(&self.first[..n]);
                self.first.drain(..n);
                return Ok(n);
            }
            if let Some(told) = self.told.take() {
                let _ = told.send(());
                self.go
                    .recv()
                    .map_err(|_| std::io::Error::other("the test ended"))?;
            }
            let n = buf.len().min(self.rest.len());
            buf[..n].copy_from_slice(&self.rest[..n]);
            self.rest.drain(..n);
            Ok(n)
        }
    }

    fn waits(
        first: Vec<u8>,
        rest: Vec<u8>,
    ) -> (
        Waits,
        std::sync::mpsc::Receiver<()>,
        std::sync::mpsc::Sender<()>,
    ) {
        let (told, heard) = std::sync::mpsc::channel();
        let (go, wait) = std::sync::mpsc::channel();
        let body = Waits {
            first,
            rest,
            told: Some(told),
            go: wait,
        };
        (body, heard, go)
    }

    /// **A body whose reader waits holds no other writer** (holger's H40-LIST item
    /// 54: a slow socket must not hold other writers). While a body staged from a
    /// reader waits in its middle, another body is staged and committed and an
    /// append ends. The pieces lie between each other in the file: the waiting raw
    /// body is one chunk a run, and stores no digest of the whole; each reads back
    /// whole. A raw body no writer came between is one chunk, as before.
    #[test]
    fn a_body_whose_reader_waits_holds_no_other_writer() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        let (first, rest) = (noise(11, STREAM_PIECE as u64), noise(12, 1000));
        let whole = [first.clone(), rest.clone()].concat();
        let (mut body, heard, go) = waits(first, rest);
        let g = Group::new(1, "crates");
        std::thread::scope(|s| {
            let slow = s.spawn(|| h.stage_from("slow.crate", &mut body, &Expect::default()));
            heard.recv().unwrap();
            let other = noise(13, 100);
            let staged = h
                .stage_from("other.crate", &mut Cursor::new(&other), &Expect::default())
                .unwrap();
            h.commit(vec![HotOp::Put {
                group: g.clone(),
                name: "other.crate".into(),
                staged,
            }])
            .unwrap();
            h.append(&[("appended".into(), b"appended".to_vec())])
                .unwrap();
            assert_eq!(h.get(&g, "other.crate").unwrap().read().unwrap(), other);
            go.send(()).unwrap();
            let slow = slow.join().unwrap().unwrap();
            assert_eq!(slow.size(), whole.len() as u64);
            assert_eq!(&slow.blake3(), blake3::hash(&whole).as_bytes());
            let chunks = &slow.location().chunks;
            assert_eq!(chunks.len(), 2, "two runs, the others' bytes between");
            assert!(chunks[1].blob_offset > chunks[0].blob_offset + chunks[0].blob_size);
            assert_eq!(
                slow.location().checksum(),
                Some(*blake3::hash(&whole).as_bytes()),
                "two runs carry the digest of the whole beside theirs"
            );
            h.commit(vec![HotOp::Put {
                group: g.clone(),
                name: "slow.crate".into(),
                staged: slow,
            }])
            .unwrap();
        });
        let read = h.get(&g, "slow.crate").unwrap();
        assert_eq!(read.read_verified().unwrap(), whole);

        let alone = noise(14, STREAM_PIECE as u64 + 10);
        let staged = h
            .stage_from("alone.crate", &mut Cursor::new(&alone), &Expect::default())
            .unwrap();
        assert_eq!(staged.location().chunks.len(), 1, "one run, one chunk");
        assert_eq!(
            staged.location().checksum(),
            Some(*blake3::hash(&alone).as_bytes())
        );
        assert_eq!(
            h.staged_body(&staged).unwrap().read_verified().unwrap(),
            alone
        );
        drop(h);
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        assert_eq!(h.get(&g, "slow.crate").unwrap().read().unwrap(), whole);
        assert!(
            h.extract_file("alone.crate").is_err(),
            "staged, never named"
        );
    }

    /// **A body refused after another writer came after it** stays where it lies,
    /// named by no row: the cursor does not go back over the other's bytes.
    #[test]
    fn a_body_refused_after_another_writer_came_after_it_is_named_by_no_row() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        let (mut body, heard, go) = waits(noise(21, STREAM_PIECE as u64), noise(22, 10));
        let wrong = Expect {
            size: Some(1),
            blake3: None,
        };
        std::thread::scope(|s| {
            let slow = s.spawn(|| h.stage_from("slow.crate", &mut body, &wrong));
            heard.recv().unwrap();
            h.append(&[("after".into(), b"after".to_vec())]).unwrap();
            let end = h.blob_end();
            go.send(()).unwrap();
            assert!(slow.join().unwrap().is_err());
            assert_eq!(
                h.blob_end(),
                end + 10,
                "the cursor does not go back over the other's bytes: the refused body's last \
                 piece lies after them, dead"
            );
        });
        assert_eq!(h.rows(), 1);
        assert_eq!(h.extract_file("after").unwrap(), b"after");
    }

    /// A body shorter (or longer) than the size asked for, or with another
    /// digest, is refused after the last byte: no row.
    #[test]
    fn a_short_body_against_an_expected_size_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        let body = noise(3, 60);
        let short = Expect {
            size: Some(100),
            blake3: None,
        };
        assert!(h
            .append_from(&Group::default(), "x", &mut Cursor::new(&body), &short)
            .is_err());
        let wrong = Expect {
            size: None,
            blake3: Some([7u8; 32]),
        };
        assert!(h
            .append_from(&Group::default(), "x", &mut Cursor::new(&body), &wrong)
            .is_err());
        assert_eq!(h.rows(), 0);
        assert_eq!(h.blob_end(), 0);
        let right = Expect {
            size: Some(60),
            blake3: Some(*blake3::hash(&body).as_bytes()),
        };
        h.append_from(&Group::default(), "x", &mut Cursor::new(&body), &right)
            .unwrap();
        assert_eq!(h.extract_file("x").unwrap(), body);
    }

    /// Many small bodies staged with ONE fsync, each its own body, each named by
    /// a commit; they read back after a reopen, compressible or not.
    #[test]
    fn stage_all_is_one_fsync_for_many_bodies() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        let fs0 = h.fsyncs();
        assert!(h.stage_all(&[]).unwrap().is_empty());
        assert_eq!(h.fsyncs(), fs0, "nothing staged, nothing synced");
        let long = vec![b'z'; 10_000];
        let bodies: Vec<(&str, &[u8])> =
            vec![("a", b"AAAA"), ("empty", b""), ("long", &long), ("b", b"B")];
        let staged = h.stage_all(&bodies).unwrap();
        assert_eq!(h.fsyncs(), fs0 + 1, "one fsync for all");
        assert_eq!(staged.len(), 4);
        assert_eq!(staged[2].size(), 10_000);
        let g = Group::new(1, "rows");
        let ops = (bodies.iter().zip(staged))
            .map(|((name, _), staged)| HotOp::Put {
                group: g.clone(),
                name: (*name).into(),
                staged,
            })
            .collect();
        h.commit(ops).unwrap();
        assert_eq!(h.fsyncs(), fs0 + 2, "and one for the rows");
        drop(h);
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        for (name, bytes) in &bodies {
            assert_eq!(&h.get(&g, name).unwrap().read().unwrap(), bytes, "{name}");
        }
    }

    /// Many ops, one journal message, one fsync — and they become visible
    /// together. A body staged by another archive is refused.
    #[test]
    fn stage_then_commit_is_one_journal_message() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.append(&[("old".into(), b"old".to_vec())]).unwrap();
        let seg = segment_path(&path, 0);
        let before = seg_batches(&seg);
        let fs0 = h.fsyncs();
        let a = h
            .stage_from("a", &mut Cursor::new(b"AAAA".to_vec()), &Expect::default())
            .unwrap();
        let b = h
            .stage_from("b", &mut Cursor::new(b"BBBB".to_vec()), &Expect::default())
            .unwrap();
        assert_eq!(h.fsyncs(), fs0 + 2, "a stage is one fsync");
        assert_eq!(h.rows(), 1, "a staged body has no row");
        let g = Group::new(1, "crates");
        let r = h
            .commit(vec![
                HotOp::Put {
                    group: Group::default(),
                    name: "a".into(),
                    staged: a.clone(),
                },
                HotOp::Put {
                    group: g.clone(),
                    name: "b".into(),
                    staged: b,
                },
                HotOp::Put {
                    group: g.clone(),
                    name: "a-too".into(),
                    staged: a,
                },
                HotOp::End {
                    group: Group::default(),
                    name: "old".into(),
                },
            ])
            .unwrap();
        assert_eq!(h.fsyncs(), fs0 + 3, "a commit is one fsync");
        assert_eq!(r.rows_replaced, 1, "old was ended");
        assert_eq!(
            seg_batches(&seg) + seg_batches(&segment_path(&path, 1)),
            before + 1,
            "the four ops are one message (in the V2 segment the group needs)"
        );
        assert_eq!(h.get(&g, "a-too").unwrap().read().unwrap(), b"AAAA");
        assert_eq!(h.get(&g, "b").unwrap().read().unwrap(), b"BBBB");
        assert!(!h.contains("old"));

        let other = HotArchive::open(&dir.path().join("b.znippy"), 3, raw()).unwrap();
        let foreign = other
            .stage_from("f", &mut Cursor::new(b"F".to_vec()), &Expect::default())
            .unwrap();
        let err = h
            .commit(vec![HotOp::Put {
                group: g,
                name: "f".into(),
                staged: foreign,
            }])
            .unwrap_err();
        assert!(format!("{err:#}").contains("another archive"), "{err:#}");
    }

    /// A second name on a blob already written writes no byte, in the same group
    /// or another, and both read the one body — hot, sealed, and in a view.
    #[test]
    fn a_second_name_on_one_blob_writes_no_bytes() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let body = noise(4, 100_000);
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.append(&[("a".into(), body.clone())]).unwrap();
        let end = h.blob_end();
        let g = Group::new(3, "maven-central");
        h.link(&Group::default(), "a2", &Group::default(), "a")
            .unwrap();
        h.link(&g, "a", &Group::default(), "a").unwrap();
        assert_eq!(h.blob_end(), end, "a link writes no byte");
        assert_eq!(h.extract_file("a2").unwrap(), body);
        assert_eq!(h.get(&g, "a").unwrap().read().unwrap(), body);
        h.seal(None).unwrap();
        let ar = ZnippyArchive::open(&path).unwrap();
        assert_eq!(ar.extract_file_verified("a2").unwrap(), body);
        let v = HotView::open(&path).unwrap();
        assert!(v.is_sealed());
        let (Lookup::Live(x), Lookup::Live(y)) =
            (v.lookup(&Group::default(), "a"), v.lookup(&g, "a"))
        else {
            panic!("both names live after the seal");
        };
        assert_eq!(x.chunks, y.chunks, "both rows name the one blob");
        assert_eq!(v.get(&g, "a").unwrap().read_verified().unwrap(), body);
    }

    /// `compact_archive` (the git plugin's GC fold) copies a shared blob once and
    /// both names keep reading it.
    #[test]
    fn compact_archive_keeps_a_shared_blob_once() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let body = noise(5, 1 << 20);
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.append(&[("a".into(), body.clone())]).unwrap();
        h.link(&Group::default(), "a2", &Group::default(), "a")
            .unwrap();
        h.append(&[("dead".into(), noise(6, 1 << 20))]).unwrap();
        h.end(&Group::default(), "dead").unwrap();
        h.seal(None).unwrap();
        let report = crate::compact_archive(&path).unwrap();
        assert!(
            report.bytes_after < (1 << 20) + (1 << 18),
            "the compacted archive holds {} bytes: the shared 1 MiB body was copied twice, or the \
             ended one was kept",
            report.bytes_after
        );
        let ar = ZnippyArchive::open(&path).unwrap();
        assert_eq!(ar.extract_file_verified("a").unwrap(), body);
        assert_eq!(ar.extract_file_verified("a2").unwrap(), body);
        assert!(!ar.contains("dead"));
    }

    /// Ending one of two names on a blob leaves the other reading it — hot,
    /// sealed, and after `compact_archive`.
    #[test]
    fn ending_one_name_keeps_the_blob_for_the_other() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let body = noise(7, 50_000);
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.append(&[("a".into(), body.clone())]).unwrap();
        h.link(&Group::default(), "b", &Group::default(), "a")
            .unwrap();
        h.end(&Group::default(), "a").unwrap();
        assert!(!h.contains("a"));
        assert_eq!(h.extract_file("b").unwrap(), body);
        h.seal(None).unwrap();
        crate::compact_archive(&path).unwrap();
        let ar = ZnippyArchive::open(&path).unwrap();
        assert!(!ar.contains("a"));
        assert_eq!(ar.extract_file_verified("b").unwrap(), body);
    }

    /// Piece 5: the stored BLAKE3 of a name, without reading its bytes — on the
    /// hot archive, its view and the sealed archive alike.
    #[test]
    fn checksum_is_the_stored_blake3_of_a_name() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let small = b"small body".to_vec();
        let big = noise(8, 9 << 20);
        let h = HotArchive::open(&path, 3, crate::SkipPolicy::resolve()).unwrap();
        h.append(&[("small".into(), small.clone())]).unwrap();
        h.append_from(
            &Group::default(),
            "big.gz",
            &mut Cursor::new(&big),
            &Expect::default(),
        )
        .unwrap();
        h.append_from(
            &Group::default(),
            "pieces.txt",
            &mut Text {
                at: 0,
                left: 9 << 20,
            },
            &Expect::default(),
        )
        .unwrap();
        let want_small = Some(*blake3::hash(&small).as_bytes());
        let want_big = Some(*blake3::hash(&big).as_bytes());
        let want_pieces = Some(*blake3::hash(&text(9 << 20)).as_bytes());
        let v = HotView::open(&path).unwrap();
        let readers: [&dyn ZnippyReader; 2] = [&h, &v];
        for r in readers {
            assert_eq!(r.checksum("small"), want_small);
            assert_eq!(
                r.checksum("big.gz"),
                want_big,
                "a raw stream stores the body's digest"
            );
            assert_eq!(
                r.checksum("pieces.txt"),
                want_pieces,
                "a body in pieces stores the whole's beside its pieces'"
            );
            assert_eq!(r.checksum("absent"), None);
        }
        h.seal(None).unwrap();
        let ar = ZnippyArchive::open(&path).unwrap();
        assert_eq!(ar.checksum("small"), want_small);
        assert_eq!(ar.checksum("big.gz"), want_big);
        assert_eq!(ar.checksum("pieces.txt"), want_pieces);
        assert_eq!(ar.checksum("absent"), None);
    }

    /// The seal wrote its tail and was cut while removing the journal: a reopen
    /// takes the seal as the truth and finishes the removal — before this, it
    /// read the segments left, lost the rows of the removed ones and cut the
    /// sealed tail.
    #[test]
    fn an_interrupted_seal_is_finished_at_reopen() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let mut all = Vec::new();
        for round in 0..3u64 {
            let h = HotArchive::open(&path, 3, raw()).unwrap();
            let files: Vec<(String, Vec<u8>)> = (0..5)
                .map(|i| (format!("r{round}/f{i}"), noise(round * 10 + i, 300)))
                .collect();
            h.append(&files).unwrap();
            all.extend(files);
        }
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.seal_with(None, false).unwrap();
        // The cut: segment 0 was removed, the rest were not.
        std::fs::remove_file(segment_path(&path, 0)).unwrap();
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        assert_eq!(h.rows(), all.len() as u64, "every row of the seal");
        for (p, b) in &all {
            assert_eq!(&h.extract_file(p).unwrap(), b, "{p}");
        }
        assert_eq!(
            journal_segments(&path).unwrap().len(),
            1,
            "only this open's own segment is left"
        );
        h.seal(None).unwrap();
        let ar = ZnippyArchive::open(&path).unwrap();
        assert_eq!(ar.list_files().unwrap().len(), all.len());
    }

    /// Re-heating writes segment 0 under a temporary name and renames it in: a
    /// cut before the rename leaves the seal untouched and a later open re-heats
    /// again.
    #[test]
    fn a_cut_reheat_leaves_the_seal_readable() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let files: Vec<(String, Vec<u8>)> =
            (0..20).map(|i| (format!("f{i}"), noise(i, 500))).collect();
        create_archive(&path, &files, 3).unwrap();
        let mut seed = segment_path(&path, 0).into_os_string();
        seed.push(".seed");
        std::fs::write(&seed, b"half a seed").unwrap();
        assert!(!HotArchive::is_hot(&path), "a seed is not a segment");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        assert_eq!(h.rows(), 20);
        for (p, b) in &files {
            assert_eq!(&h.extract_file(p).unwrap(), b);
        }
    }

    /// A plain archive keeps the eight-column journal while every row fits; the
    /// first row in a named group starts a V2 segment, and both read back.
    #[test]
    fn a_plain_archive_keeps_the_v1_journal_until_a_row_needs_more() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("a.znippy");
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        h.append(&[("a".into(), b"A".to_vec())]).unwrap();
        let schema_of = |n: u32| {
            let bytes = std::fs::read(segment_path(&path, n)).unwrap();
            let r = arrow::ipc::reader::StreamReader::try_new(Cursor::new(bytes), None).unwrap();
            r.schema().fields().len()
        };
        assert_eq!(schema_of(0), 9);
        h.append_in(&Group::new(2, "pypi"), &[("b".into(), b"B".to_vec())])
            .unwrap();
        assert_eq!(schema_of(1), 13);
        drop(h);
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        assert_eq!(h.extract_file("a").unwrap(), b"A");
        assert_eq!(
            h.get(&Group::new(2, "pypi"), "b").unwrap().read().unwrap(),
            b"B"
        );
    }

    /// Piece 6: one archive, many repositories of many types, the same name in
    /// several — through the hot path, the seal, a view, and a re-heat. Each
    /// group seals as its own data sub-index, found by `(pkg_type, repo)`.
    #[test]
    fn many_repositories_of_many_types_in_one_archive() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("account.znippy");
        let groups = [
            Group::new(1, "crates-io"),
            Group::new(1, "internal"),
            Group::new(3, "central"),
            Group::default(),
        ];
        let body = |g: &Group, i: usize| format!("{g:?} body {i}").into_bytes();
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        for g in &groups {
            let files: Vec<(String, Vec<u8>)> =
                (0..10).map(|i| (format!("pkg/{i}"), body(g, i))).collect();
            h.append_in(g, &files).unwrap();
        }
        h.seal(None).unwrap();
        for g in &groups {
            let (_, batches) = read_znippy_index_filtered(
                &path,
                &IndexFilter {
                    pkg_type: Some(g.pkg_type),
                    repo: Some(g.repo.clone()),
                },
            )
            .unwrap();
            let rows: usize = batches.iter().map(|b| b.num_rows()).sum();
            assert_eq!(rows, 10, "{g:?} is its own data sub-index");
        }
        let v = HotView::open(&path).unwrap();
        assert_eq!(v.groups().len(), 4);
        for g in &groups {
            for i in 0..10 {
                assert_eq!(
                    v.get(g, &format!("pkg/{i}"))
                        .unwrap()
                        .read_verified()
                        .unwrap(),
                    body(g, i)
                );
            }
        }
        // Re-heat: the groups come back, more rows go in, the seal keeps them apart.
        let h = HotArchive::open(&path, 3, raw()).unwrap();
        assert_eq!(h.rows(), 40);
        h.append_in(&groups[0], &[("pkg/new".into(), b"new".to_vec())])
            .unwrap();
        h.seal(None).unwrap();
        v.refresh().unwrap();
        assert_eq!(
            v.get(&groups[0], "pkg/new").unwrap().read().unwrap(),
            b"new"
        );
        assert!(v.get(&groups[1], "pkg/new").is_none());
        for g in &groups {
            assert_eq!(v.get(g, "pkg/3").unwrap().read().unwrap(), body(g, 3));
        }
    }
}